From 109a105d04b729c7b36196c8414ddb58e652c2ed Mon Sep 17 00:00:00 2001 From: Eduard Kerkhoven Date: Tue, 29 Sep 2026 16:28:57 +0200 Subject: [PATCH 1/7] Fix gurobi solving without Parallel Computing Toolbox --- solver/optimizeProb.m | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/solver/optimizeProb.m b/solver/optimizeProb.m index 3430c45d3..f2279e62d 100755 --- a/solver/optimizeProb.m +++ b/solver/optimizeProb.m @@ -90,7 +90,14 @@ solverparams.FeasibilityTol = defaultparams.feasTol; solverparams.OptimalityTol = defaultparams.optTol; solverparams.Presolve = 2; - if ~isempty(getCurrentTask) % If run in parallel, then one thread per gurobi + % If run in parallel, then one thread per gurobi. getCurrentTask + % requires the Parallel Computing Toolbox. + try + inParallel = ~isempty(getCurrentTask); + catch + inParallel = false; + end + if inParallel solverparams.Threads=1; end solverparams = structUpdate(solverparams,params); From 1c7ef31d0c7c0af672c1228fb2b11391e604d190 Mon Sep 17 00:00:00 2001 From: Eduard Kerkhoven Date: Tue, 29 Sep 2026 16:30:49 +0200 Subject: [PATCH 2/7] Report missing WSL when HMMER check fails on Windows --- installation/checkInstallation.m | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/installation/checkInstallation.m b/installation/checkInstallation.m index de8c12363..e480c0792 100755 --- a/installation/checkInstallation.m +++ b/installation/checkInstallation.m @@ -311,6 +311,15 @@ if res==false fprintf([' This is essential to run getKEGGModelFromHomology()\n'... ' when using a FASTA file as input\n']) + % On Windows, HMMER runs through Windows Subsystem for Linux + if ispc + [status,~]=system('wsl -e true'); + if status~=0 + printOrange([' WSL with a Linux distribution is not available, but HMMER\n'... + ' requires it on Windows. Install it with "wsl --install" in\n'... + ' a Command Prompt, restart, and rerun checkInstallation\n']) + end + end end if developMode From d1f47e740c9042af808da8f698697431ee679e50 Mon Sep 17 00:00:00 2001 From: Eduard Kerkhoven Date: Tue, 29 Sep 2026 16:37:54 +0200 Subject: [PATCH 3/7] Update documentation --- doc/installation/checkInstallation.html | 171 ++++++----- doc/solver/optimizeProb.html | 379 ++++++++++++------------ 2 files changed, 283 insertions(+), 267 deletions(-) diff --git a/doc/installation/checkInstallation.html b/doc/installation/checkInstallation.html index 3ee042608..4034591ce 100644 --- a/doc/installation/checkInstallation.html +++ b/doc/installation/checkInstallation.html @@ -383,90 +383,99 @@

SOURCE CODE ^if res==false 0312 fprintf([' This is essential to run getKEGGModelFromHomology()\n'... 0313 ' when using a FASTA file as input\n']) -0314 end -0315 -0316 if developMode -0317 fprintf('\n=== Development binary executables ===\n'); -0318 fprintf('NOTE: These binaries are only required when using KEGG FTP dump files in getKEGGModelForOrganism\n'); -0319 -0320 fprintf(myStr(' > Checking CD-HIT',40)) -0321 [~,res]=evalc("runtests('cdhitTests.m');"); -0322 interpretResults(res); -0323 -0324 fprintf(myStr(' > Checking MAFFT',40)) -0325 [~,res]=evalc("runtests('mafftTests.m');"); -0326 interpretResults(res); -0327 end -0328 end -0329 -0330 fprintf('\n=== Compatibility ===\n'); -0331 fprintf(myStr(' > Checking function uniqueness',40)) -0332 checkFunctionUniqueness(); -0333 -0334 fprintf('\n*** checkInstallation complete ***\n'); -0335 end -0336 -0337 function res = interpretResults(results) -0338 if results.Failed==0 && results.Incomplete==0 -0339 fprintf('Pass\n'); -0340 res=true; -0341 else -0342 printOrange('Fail\n') -0343 fprintf(' Download/compile the binary and rerun checkInstallation\n'); -0344 res=false; -0345 end -0346 end -0347 -0348 function str = myStr(InputStr,len) -0349 str=InputStr; -0350 lenDiff = len - length(str); -0351 if lenDiff < 0 -0352 warning('String too long'); -0353 else -0354 str = [str blanks(lenDiff)]; +0314 % On Windows, HMMER runs through Windows Subsystem for Linux +0315 if ispc +0316 [status,~]=system('wsl -e true'); +0317 if status~=0 +0318 printOrange([' WSL with a Linux distribution is not available, but HMMER\n'... +0319 ' requires it on Windows. Install it with "wsl --install" in\n'... +0320 ' a Command Prompt, restart, and rerun checkInstallation\n']) +0321 end +0322 end +0323 end +0324 +0325 if developMode +0326 fprintf('\n=== Development binary executables ===\n'); +0327 fprintf('NOTE: These binaries are only required when using KEGG FTP dump files in getKEGGModelForOrganism\n'); +0328 +0329 fprintf(myStr(' > Checking CD-HIT',40)) +0330 [~,res]=evalc("runtests('cdhitTests.m');"); +0331 interpretResults(res); +0332 +0333 fprintf(myStr(' > Checking MAFFT',40)) +0334 [~,res]=evalc("runtests('mafftTests.m');"); +0335 interpretResults(res); +0336 end +0337 end +0338 +0339 fprintf('\n=== Compatibility ===\n'); +0340 fprintf(myStr(' > Checking function uniqueness',40)) +0341 checkFunctionUniqueness(); +0342 +0343 fprintf('\n*** checkInstallation complete ***\n'); +0344 end +0345 +0346 function res = interpretResults(results) +0347 if results.Failed==0 && results.Incomplete==0 +0348 fprintf('Pass\n'); +0349 res=true; +0350 else +0351 printOrange('Fail\n') +0352 fprintf(' Download/compile the binary and rerun checkInstallation\n'); +0353 res=false; +0354 end 0355 end -0356 end -0357 -0358 function status = makeBinaryExecutable(ravenDir) -0359 % This function is required to run when RAVEN is downloaded as MATLAB -0360 % Add-On, in which case the file permissions are not correctly set -0361 if ispc -0362 status = 0; % No need to run on Windows -0363 return; +0356 +0357 function str = myStr(InputStr,len) +0358 str=InputStr; +0359 lenDiff = len - length(str); +0360 if lenDiff < 0 +0361 warning('String too long'); +0362 else +0363 str = [str blanks(lenDiff)]; 0364 end -0365 binDir = fullfile(ravenDir,'software'); +0365 end 0366 -0367 binList = {fullfile(binDir,'blast+','blastp'); fullfile(binDir,'blast+','blastp.mac'); -0368 fullfile(binDir,'blast+','makeblastdb'); fullfile(binDir,'blast+','makeblastdb.mac'); -0369 fullfile(binDir,'cd-hit','cd-hit'); fullfile(binDir,'cd-hit','cd-hit.mac'); -0370 fullfile(binDir,'diamond','diamond'); fullfile(binDir,'diamond','diamond.mac'); -0371 fullfile(binDir,'hmmer','hmmbuild'); fullfile(binDir,'hmmer','hmmbuild.mac'); -0372 fullfile(binDir,'hmmer','hmmsearch'); fullfile(binDir,'hmmer','hmmsearch.mac'); -0373 fullfile(binDir,'GLPKmex','glpkcc.mexa64'); fullfile(binDir,'GLPKmex','glpkcc.mexglx'); fullfile(binDir,'GLPKmex','glpkcc.mexmaci64'); fullfile(binDir,'GLPKmex','glpkcc.mexmaca64'); -0374 fullfile(binDir,'libSBML','TranslateSBML_RAVEN.mexa64'); fullfile(binDir,'libSBML','TranslateSBML_RAVEN.mexglx'); fullfile(binDir,'libSBML','TranslateSBML_RAVEN.mexmaci64'); fullfile(binDir,'libSBML','TranslateSBML_RAVEN.mexmaca64'); -0375 fullfile(binDir,'libSBML','OutputSBML_RAVEN.mexa64'); fullfile(binDir,'libSBML','OutputSBML_RAVEN.mexglx'); fullfile(binDir,'libSBML','OutputSBML_RAVEN.mexmaci64'); fullfile(binDir,'libSBML','OutputSBML_RAVEN.mexmaca64'); -0376 fullfile(binDir,'mafft','mafft-linux64','mafft.bat'); -0377 fullfile(binDir,'mafft','mafft-mac','mafft.bat');}; -0378 -0379 for i=1:numel(binList) -0380 [status,cmdout] = system(['chmod +x "' binList{i} '"']); -0381 if status ~= 0 -0382 warning('Failed to make %s executable: %s ',binList{i},strip(cmdout)) -0383 end -0384 end -0385 end -0386 -0387 function printOrange(stringToPrint) -0388 % printOrange -0389 % Duplicate of RAVEN/core/printOrange is also kept here, as this function -0390 % should be able to run before adding RAVEN to the MATLAB path. -0391 try useDesktop = usejava('desktop'); catch, useDesktop = false; end -0392 if useDesktop -0393 fprintf(['[\b' stringToPrint,']\b']) -0394 else -0395 fprintf(stringToPrint) -0396 end -0397 end +0367 function status = makeBinaryExecutable(ravenDir) +0368 % This function is required to run when RAVEN is downloaded as MATLAB +0369 % Add-On, in which case the file permissions are not correctly set +0370 if ispc +0371 status = 0; % No need to run on Windows +0372 return; +0373 end +0374 binDir = fullfile(ravenDir,'software'); +0375 +0376 binList = {fullfile(binDir,'blast+','blastp'); fullfile(binDir,'blast+','blastp.mac'); +0377 fullfile(binDir,'blast+','makeblastdb'); fullfile(binDir,'blast+','makeblastdb.mac'); +0378 fullfile(binDir,'cd-hit','cd-hit'); fullfile(binDir,'cd-hit','cd-hit.mac'); +0379 fullfile(binDir,'diamond','diamond'); fullfile(binDir,'diamond','diamond.mac'); +0380 fullfile(binDir,'hmmer','hmmbuild'); fullfile(binDir,'hmmer','hmmbuild.mac'); +0381 fullfile(binDir,'hmmer','hmmsearch'); fullfile(binDir,'hmmer','hmmsearch.mac'); +0382 fullfile(binDir,'GLPKmex','glpkcc.mexa64'); fullfile(binDir,'GLPKmex','glpkcc.mexglx'); fullfile(binDir,'GLPKmex','glpkcc.mexmaci64'); fullfile(binDir,'GLPKmex','glpkcc.mexmaca64'); +0383 fullfile(binDir,'libSBML','TranslateSBML_RAVEN.mexa64'); fullfile(binDir,'libSBML','TranslateSBML_RAVEN.mexglx'); fullfile(binDir,'libSBML','TranslateSBML_RAVEN.mexmaci64'); fullfile(binDir,'libSBML','TranslateSBML_RAVEN.mexmaca64'); +0384 fullfile(binDir,'libSBML','OutputSBML_RAVEN.mexa64'); fullfile(binDir,'libSBML','OutputSBML_RAVEN.mexglx'); fullfile(binDir,'libSBML','OutputSBML_RAVEN.mexmaci64'); fullfile(binDir,'libSBML','OutputSBML_RAVEN.mexmaca64'); +0385 fullfile(binDir,'mafft','mafft-linux64','mafft.bat'); +0386 fullfile(binDir,'mafft','mafft-mac','mafft.bat');}; +0387 +0388 for i=1:numel(binList) +0389 [status,cmdout] = system(['chmod +x "' binList{i} '"']); +0390 if status ~= 0 +0391 warning('Failed to make %s executable: %s ',binList{i},strip(cmdout)) +0392 end +0393 end +0394 end +0395 +0396 function printOrange(stringToPrint) +0397 % printOrange +0398 % Duplicate of RAVEN/core/printOrange is also kept here, as this function +0399 % should be able to run before adding RAVEN to the MATLAB path. +0400 try useDesktop = usejava('desktop'); catch, useDesktop = false; end +0401 if useDesktop +0402 fprintf(['[\b' stringToPrint,']\b']) +0403 else +0404 fprintf(stringToPrint) +0405 end +0406 end
Generated by m2html © 2005
\ No newline at end of file diff --git a/doc/solver/optimizeProb.html b/doc/solver/optimizeProb.html index 5fd16c557..a6ec84623 100644 --- a/doc/solver/optimizeProb.html +++ b/doc/solver/optimizeProb.html @@ -144,194 +144,201 @@

SOURCE CODE ^if ~isempty(getCurrentTask) % If run in parallel, then one thread per gurobi -0094 solverparams.Threads=1; -0095 end -0096 solverparams = structUpdate(solverparams,params); -0097 -0098 % Restructering problem according to gurobi format -0099 if isfield(prob, 'csense') -0100 prob.sense = renameparams(prob.csense, {'L','G','E'}, {'<','>','='}); -0101 prob = rmfield(prob, {'csense'}); +0093 % If run in parallel, then one thread per gurobi. getCurrentTask +0094 % requires the Parallel Computing Toolbox. +0095 try +0096 inParallel = ~isempty(getCurrentTask); +0097 catch +0098 inParallel = false; +0099 end +0100 if inParallel +0101 solverparams.Threads=1; 0102 end -0103 if isfield(prob, 'osense') -0104 osense = prob.osense; -0105 prob.modelsense = renameparams(num2str(prob.osense), {'1','-1'}, {'min','max'}); -0106 prob = rmfield(prob, {'osense'}); -0107 end -0108 [prob.obj, prob.rhs, prob.vtype] = deal(prob.c, prob.b, prob.vartype); -0109 prob = rmfield(prob, {'c','b','vartype'}); -0110 -0111 resG = gurobi(prob,solverparams); -0112 -0113 try -0114 % Name output fields the same as COBRA does -0115 res.full = resG.x; -0116 res.obj = resG.objval; -0117 res.origStat = resG.status; -0118 if isfield(resG,{'pi','rc'}) -0119 res.dual = -resG.pi*osense; -0120 res.rcost = -resG.rc*osense; -0121 end -0122 if milp && strcmp(resG.status, 'TIME_LIMIT') -0123 % If res has the objval field, it succeeded, regardless of -0124 % time_limit status -0125 resG.status = 'OPTIMAL'; -0126 end -0127 switch resG.status -0128 case 'OPTIMAL' -0129 res.stat = 1; -0130 case 'UNBOUNDED' -0131 res.stat = 2; -0132 otherwise -0133 res.stat = 0; -0134 end -0135 if ~milp -0136 res.vbasis = resG.vbasis; -0137 res.cbasis = resG.cbasis; -0138 else -0139 res.mipgap = resG.mipgap; -0140 end -0141 catch -0142 res.stat = 0; -0143 res.origStat = resG.status; % useful information to have -0144 end -0145 %% Use GLPK using RAVEN-provided binary -0146 case 'glpk' -0147 solverparams.scale = 1; % Auto scaling -0148 %solverparams.tmlim = defaultparams.timeLimit; -0149 solverparams.tolbnd = defaultparams.feasTol; -0150 solverparams.toldj = defaultparams.optTol; -0151 solverparams.tolint = defaultparams.intTol; -0152 solverparams.tolobj = defaultparams.objTol; -0153 solverparams.msglev = 0; % Level of verbosity -0154 solverparams = structUpdate(solverparams,params); -0155 -0156 prob.csense = renameparams(prob.csense, {'L','G','E'}, {'U','L','S'}); -0157 -0158 if milp -0159 solverparams.tmlim = solverparams.tmlim*10; -0160 solverparams.msglev = 1; % Level of verbosity -0161 disp('Issues have been observed when using GLPK for MILP solving. Be advised to carefully observe the results, or us another solver.') -0162 end -0163 -0164 % Ensure that RAVEN glpk binary is used, return to original -0165 % directory afterwards -0166 [ravenDir,currDir]=findRAVENroot(); -0167 cd(fullfile(ravenDir,'software','GLPKmex')) -0168 [xopt, fmin, errnum, extra] = glpk(prob.c, prob.A, prob.b, prob.lb, prob.ub, prob.csense, prob.vartype, prob.osense, solverparams); -0169 cd(currDir) +0103 solverparams = structUpdate(solverparams,params); +0104 +0105 % Restructering problem according to gurobi format +0106 if isfield(prob, 'csense') +0107 prob.sense = renameparams(prob.csense, {'L','G','E'}, {'<','>','='}); +0108 prob = rmfield(prob, {'csense'}); +0109 end +0110 if isfield(prob, 'osense') +0111 osense = prob.osense; +0112 prob.modelsense = renameparams(num2str(prob.osense), {'1','-1'}, {'min','max'}); +0113 prob = rmfield(prob, {'osense'}); +0114 end +0115 [prob.obj, prob.rhs, prob.vtype] = deal(prob.c, prob.b, prob.vartype); +0116 prob = rmfield(prob, {'c','b','vartype'}); +0117 +0118 resG = gurobi(prob,solverparams); +0119 +0120 try +0121 % Name output fields the same as COBRA does +0122 res.full = resG.x; +0123 res.obj = resG.objval; +0124 res.origStat = resG.status; +0125 if isfield(resG,{'pi','rc'}) +0126 res.dual = -resG.pi*osense; +0127 res.rcost = -resG.rc*osense; +0128 end +0129 if milp && strcmp(resG.status, 'TIME_LIMIT') +0130 % If res has the objval field, it succeeded, regardless of +0131 % time_limit status +0132 resG.status = 'OPTIMAL'; +0133 end +0134 switch resG.status +0135 case 'OPTIMAL' +0136 res.stat = 1; +0137 case 'UNBOUNDED' +0138 res.stat = 2; +0139 otherwise +0140 res.stat = 0; +0141 end +0142 if ~milp +0143 res.vbasis = resG.vbasis; +0144 res.cbasis = resG.cbasis; +0145 else +0146 res.mipgap = resG.mipgap; +0147 end +0148 catch +0149 res.stat = 0; +0150 res.origStat = resG.status; % useful information to have +0151 end +0152 %% Use GLPK using RAVEN-provided binary +0153 case 'glpk' +0154 solverparams.scale = 1; % Auto scaling +0155 %solverparams.tmlim = defaultparams.timeLimit; +0156 solverparams.tolbnd = defaultparams.feasTol; +0157 solverparams.toldj = defaultparams.optTol; +0158 solverparams.tolint = defaultparams.intTol; +0159 solverparams.tolobj = defaultparams.objTol; +0160 solverparams.msglev = 0; % Level of verbosity +0161 solverparams = structUpdate(solverparams,params); +0162 +0163 prob.csense = renameparams(prob.csense, {'L','G','E'}, {'U','L','S'}); +0164 +0165 if milp +0166 solverparams.tmlim = solverparams.tmlim*10; +0167 solverparams.msglev = 1; % Level of verbosity +0168 disp('Issues have been observed when using GLPK for MILP solving. Be advised to carefully observe the results, or us another solver.') +0169 end 0170 -0171 switch errnum % 1 = undefined; 2 = feasible; 3 = infeasible; 4 = no feasible solution; 5 = optimal; 6 = no unbounded solution -0172 case 5 -0173 res.stat = 1; % Optimal -0174 case 2 -0175 res.stat = 2; % Feasible, but not optimal -0176 otherwise -0177 res.stat = 0; -0178 end -0179 res.origStat = errnum; -0180 res.full = xopt; -0181 res.obj = fmin; -0182 res.dual = -extra.lambda*prob.osense; -0183 res.rcost = -extra.redcosts*prob.osense; -0184 %% Use scip -0185 case {'soplex','scip'} % Old 'soplex' option also allowed -0186 [xopt,fval,exitflag] = scip([], prob.c, prob.A,-prob.b, prob.b, prob.lb, prob.ub, prob.vartype); -0187 -0188 % [x,fval,exitflag,stats] = scip(H, f, A, rl, ru, lb, ub, xtype, sos, qc, nl, x0, opts) -0189 % -0190 % Input arguments*: -0191 % H - quadratic objective matrix (sparse, optional [NOT TRIL / TRIU]) -0192 % f - linear objective vector -0193 % A - linear constraint matrix (sparse) -0194 % rl - linear constraint lhs -0195 % ru - linear constraint rhs -0196 % lb - decision variable lower bounds -0197 % ub - decision variable upper bounds -0198 % xtype - string of variable integrality ('c' continuous, 'i' integer, 'b' binary) -0199 % sos - SOS structure with fields type, index and weight (see below) -0200 % qc - Quadratic Constraints structure with fields Q, l, qrl and qru (see below) -0201 % nl - Nonlinear Objective and Constraints structure (see below) -0202 % x0 - primal solution -0203 % opts - solver options (see below) -0204 % -0205 % Return arguments: -0206 % x - solution vector -0207 % fval - objective value at the solution -0208 % exitflag - exit status (see below) -0209 % stats - statistics structure -0210 % -0211 % Option Fields (all optional, see also optiset for a list): -0212 % solverOpts - specific SCIP options (list of pairs of parameter names and values) -0213 % maxiter - maximum LP solver iterations -0214 % maxnodes - maximum nodes to explore -0215 % maxtime - maximum execution time [s] -0216 % tolrfun - primal feasibility tolerance -0217 % display - solver display level [0-5] -0218 % probfile - write problem to given file -0219 % presolvedfile - write presolved problem to file -0220 % -0221 % Return Status: -0222 % 0 - Unknown -0223 % 1 - User Interrupted -0224 % 2 - Node Limit Reached -0225 % 3 - Total Node Limit Reached -0226 % 4 - Stall Node Limit Reached -0227 % 5 - Time Limit Reached -0228 % 6 - Memory Limit Reached -0229 % 7 - Gap Limit Reached -0230 % 8 - Solution Limit Reached -0231 % 9 - Solution Improvement Limit Reached -0232 % 10 - Restart Limit Reached -0233 % 11 - Problem Solved to Optimality -0234 % 12 - Problem is Infeasible -0235 % 13 - Problem is Unbounded -0236 % 14 - Problem is Either Infeasible or Unbounded -0237 -0238 res.origStat = exitflag; -0239 res.full = xopt; -0240 res.obj = fval; -0241 -0242 switch exitflag -0243 case 11 -0244 res.stat = 1; -0245 case {1, 5, 6, 7, 8, 9, 10, 13} % If user-interrupted, not sure if optimal -0246 res.stat = 2; -0247 otherwise -0248 res.stat = 0; -0249 end -0250 otherwise -0251 error('RAVEN solver not defined or unknown. Try using setRavenSolver(''solver'').'); -0252 end -0253 if res.stat>0 -0254 res.full=res.full(1:size(prob.a,2)); -0255 end -0256 end -0257 -0258 function s_merged=structUpdate(s_old,s_new) -0259 %Remove overlapping fields from first struct; -0260 %Obtain all unique names of remaining fields; -0261 %Merge both structs -0262 s_merged = rmfield(s_old, intersect(fieldnames(s_old), fieldnames(s_new))); -0263 names = [fieldnames(s_merged); fieldnames(s_new)]; -0264 s_merged = cell2struct([struct2cell(s_merged); struct2cell(s_new)], names, 1); -0265 end -0266 -0267 function paramlist = renameparams(paramlist,old,new) -0268 if ~iscell(paramlist) -0269 wasNoCell = true; -0270 paramlist={paramlist}; -0271 else -0272 wasNoCell = false; -0273 end -0274 for i=1:numel(old) -0275 paramlist = regexprep(paramlist,old{i},new{i}); -0276 end -0277 if wasNoCell -0278 paramlist=paramlist{1}; -0279 end -0280 end +0171 % Ensure that RAVEN glpk binary is used, return to original +0172 % directory afterwards +0173 [ravenDir,currDir]=findRAVENroot(); +0174 cd(fullfile(ravenDir,'software','GLPKmex')) +0175 [xopt, fmin, errnum, extra] = glpk(prob.c, prob.A, prob.b, prob.lb, prob.ub, prob.csense, prob.vartype, prob.osense, solverparams); +0176 cd(currDir) +0177 +0178 switch errnum % 1 = undefined; 2 = feasible; 3 = infeasible; 4 = no feasible solution; 5 = optimal; 6 = no unbounded solution +0179 case 5 +0180 res.stat = 1; % Optimal +0181 case 2 +0182 res.stat = 2; % Feasible, but not optimal +0183 otherwise +0184 res.stat = 0; +0185 end +0186 res.origStat = errnum; +0187 res.full = xopt; +0188 res.obj = fmin; +0189 res.dual = -extra.lambda*prob.osense; +0190 res.rcost = -extra.redcosts*prob.osense; +0191 %% Use scip +0192 case {'soplex','scip'} % Old 'soplex' option also allowed +0193 [xopt,fval,exitflag] = scip([], prob.c, prob.A,-prob.b, prob.b, prob.lb, prob.ub, prob.vartype); +0194 +0195 % [x,fval,exitflag,stats] = scip(H, f, A, rl, ru, lb, ub, xtype, sos, qc, nl, x0, opts) +0196 % +0197 % Input arguments*: +0198 % H - quadratic objective matrix (sparse, optional [NOT TRIL / TRIU]) +0199 % f - linear objective vector +0200 % A - linear constraint matrix (sparse) +0201 % rl - linear constraint lhs +0202 % ru - linear constraint rhs +0203 % lb - decision variable lower bounds +0204 % ub - decision variable upper bounds +0205 % xtype - string of variable integrality ('c' continuous, 'i' integer, 'b' binary) +0206 % sos - SOS structure with fields type, index and weight (see below) +0207 % qc - Quadratic Constraints structure with fields Q, l, qrl and qru (see below) +0208 % nl - Nonlinear Objective and Constraints structure (see below) +0209 % x0 - primal solution +0210 % opts - solver options (see below) +0211 % +0212 % Return arguments: +0213 % x - solution vector +0214 % fval - objective value at the solution +0215 % exitflag - exit status (see below) +0216 % stats - statistics structure +0217 % +0218 % Option Fields (all optional, see also optiset for a list): +0219 % solverOpts - specific SCIP options (list of pairs of parameter names and values) +0220 % maxiter - maximum LP solver iterations +0221 % maxnodes - maximum nodes to explore +0222 % maxtime - maximum execution time [s] +0223 % tolrfun - primal feasibility tolerance +0224 % display - solver display level [0-5] +0225 % probfile - write problem to given file +0226 % presolvedfile - write presolved problem to file +0227 % +0228 % Return Status: +0229 % 0 - Unknown +0230 % 1 - User Interrupted +0231 % 2 - Node Limit Reached +0232 % 3 - Total Node Limit Reached +0233 % 4 - Stall Node Limit Reached +0234 % 5 - Time Limit Reached +0235 % 6 - Memory Limit Reached +0236 % 7 - Gap Limit Reached +0237 % 8 - Solution Limit Reached +0238 % 9 - Solution Improvement Limit Reached +0239 % 10 - Restart Limit Reached +0240 % 11 - Problem Solved to Optimality +0241 % 12 - Problem is Infeasible +0242 % 13 - Problem is Unbounded +0243 % 14 - Problem is Either Infeasible or Unbounded +0244 +0245 res.origStat = exitflag; +0246 res.full = xopt; +0247 res.obj = fval; +0248 +0249 switch exitflag +0250 case 11 +0251 res.stat = 1; +0252 case {1, 5, 6, 7, 8, 9, 10, 13} % If user-interrupted, not sure if optimal +0253 res.stat = 2; +0254 otherwise +0255 res.stat = 0; +0256 end +0257 otherwise +0258 error('RAVEN solver not defined or unknown. Try using setRavenSolver(''solver'').'); +0259 end +0260 if res.stat>0 +0261 res.full=res.full(1:size(prob.a,2)); +0262 end +0263 end +0264 +0265 function s_merged=structUpdate(s_old,s_new) +0266 %Remove overlapping fields from first struct; +0267 %Obtain all unique names of remaining fields; +0268 %Merge both structs +0269 s_merged = rmfield(s_old, intersect(fieldnames(s_old), fieldnames(s_new))); +0270 names = [fieldnames(s_merged); fieldnames(s_new)]; +0271 s_merged = cell2struct([struct2cell(s_merged); struct2cell(s_new)], names, 1); +0272 end +0273 +0274 function paramlist = renameparams(paramlist,old,new) +0275 if ~iscell(paramlist) +0276 wasNoCell = true; +0277 paramlist={paramlist}; +0278 else +0279 wasNoCell = false; +0280 end +0281 for i=1:numel(old) +0282 paramlist = regexprep(paramlist,old{i},new{i}); +0283 end +0284 if wasNoCell +0285 paramlist=paramlist{1}; +0286 end +0287 end
Generated by m2html © 2005
\ No newline at end of file From 8ac5c54efb556c0957fc1fdf0ad46fbf3c19f104 Mon Sep 17 00:00:00 2001 From: Eduard Kerkhoven Date: Wed, 30 Sep 2026 11:42:55 +0200 Subject: [PATCH 4/7] Diagnose why the HMMER check fails on Windows --- installation/checkInstallation.m | 32 ++++++++++++++++++++++++++------ 1 file changed, 26 insertions(+), 6 deletions(-) diff --git a/installation/checkInstallation.m b/installation/checkInstallation.m index e480c0792..40ef456fe 100755 --- a/installation/checkInstallation.m +++ b/installation/checkInstallation.m @@ -309,15 +309,35 @@ [~,res]=evalc("runtests('hmmerTests.m')"); res=interpretResults(res); if res==false - fprintf([' This is essential to run getKEGGModelFromHomology()\n'... - ' when using a FASTA file as input\n']) + fprintf([' HMMER is only required by getKEGGModelForOrganism() when\n'... + ' using a FASTA file as input. If you do not use this function,\n'... + ' this failure can be ignored.\n']) % On Windows, HMMER runs through Windows Subsystem for Linux if ispc - [status,~]=system('wsl -e true'); + [status,~]=system('where wsl'); if status~=0 - printOrange([' WSL with a Linux distribution is not available, but HMMER\n'... - ' requires it on Windows. Install it with "wsl --install" in\n'... - ' a Command Prompt, restart, and rerun checkInstallation\n']) + printOrange([' MATLAB cannot find wsl.exe. On Windows, HMMER runs through WSL.\n'... + ' Install it with "wsl --install" in a Command Prompt, then restart\n'... + ' MATLAB (it inherits the system PATH at startup) and rerun checkInstallation\n']) + else + [status,~]=system('wsl -e true'); + if status~=0 + printOrange([' MATLAB finds wsl.exe, but cannot start a Linux distribution\n'... + ' through it. Run "wsl -l -v" in a Command Prompt to check that a\n'... + ' distribution is installed and set up, then restart MATLAB and\n'... + ' rerun checkInstallation\n']) + else + try + [status,~]=system(['wsl "' getWSLpath(fullfile(ravenDir,'software','hmmer','hmmsearch')) '" -h']); + catch + status=1; + end + if status~=0 + printOrange([' WSL works, but the RAVEN HMMER binary cannot be run in it.\n'... + ' Check that the files in software/hmmer are present and that\n'... + ' the drive holding RAVEN is accessible from WSL\n']) + end + end end end end From 6fd39837148a683a1ecae6ae40118415a46ffacf Mon Sep 17 00:00:00 2001 From: Eduard Kerkhoven Date: Wed, 30 Sep 2026 11:47:59 +0200 Subject: [PATCH 5/7] Update documentation --- doc/INIT/INITStepDesc.html | 126 -- doc/INIT/ftINIT.html | 580 ------- doc/INIT/ftINITFillGaps.html | 207 --- doc/INIT/ftINITFillGapsForAllTasks.html | 462 ------ doc/INIT/ftINITFillGapsMILP.html | 312 ---- doc/INIT/ftINITInternalAlg.html | 551 ------- doc/INIT/getExprForRxnScore.html | 85 -- doc/INIT/getINITModel.html | 609 -------- doc/INIT/getINITSteps.html | 210 --- doc/INIT/groupRxnScores.html | 124 -- doc/INIT/index.html | 29 - doc/INIT/mergeLinear.html | 281 ---- doc/INIT/prepINITModel.html | 407 ----- doc/INIT/removeLowScoreGenes.html | 372 ----- doc/INIT/rescaleModelForINIT.html | 129 -- doc/INIT/reverseRxns.html | 68 - doc/INIT/runINIT.html | 445 ------ doc/INIT/scoreComplexModel.html | 482 ------ doc/alpha.png | Bin 273 -> 0 bytes doc/c++.png | Bin 327 -> 0 bytes doc/c.png | Bin 252 -> 0 bytes doc/core/FSEOF.html | 224 --- doc/core/addExchangeRxns.html | 166 -- doc/core/addGenesRaven.html | 221 --- doc/core/addMets.html | 472 ------ doc/core/addRxns.html | 846 ----------- doc/core/addRxnsGenesMets.html | 274 ---- doc/core/addTransport.html | 250 --- doc/core/analyzeSampling.html | 250 --- doc/core/buildEquation.html | 122 -- doc/core/canConsume.html | 83 - doc/core/canProduce.html | 85 -- doc/core/changeGrRules.html | 116 -- doc/core/changeRxns.html | 249 --- doc/core/checkModelStruct.html | 517 ------- doc/core/checkProduction.html | 242 --- doc/core/checkRxn.html | 156 -- doc/core/checkTasks.html | 351 ----- doc/core/compareMultipleModels.html | 521 ------- doc/core/compareRxnsGenesMetsComps.html | 247 --- doc/core/constructEquations.html | 182 --- doc/core/constructS.html | 250 --- doc/core/consumeSomething.html | 263 ---- doc/core/contractModel.html | 251 --- doc/core/convertCharArray.html | 84 -- doc/core/convertToIrrev.html | 182 --- doc/core/copyToComps.html | 175 --- doc/core/deleteUnusedGenes.html | 111 -- doc/core/dispEM.html | 115 -- doc/core/expandModel.html | 212 --- doc/core/fillGaps.html | 325 ---- doc/core/findGeneDeletions.html | 293 ---- doc/core/findRAVENroot.html | 78 - doc/core/fitParameters.html | 199 --- doc/core/fitTasks.html | 409 ----- doc/core/followChanged.html | 170 --- doc/core/followFluxes.html | 109 -- doc/core/gapReport.html | 193 --- doc/core/generateNewIds.html | 123 -- doc/core/getAllRxnsFromGenes.html | 96 -- doc/core/getAllSubGraphs.html | 120 -- doc/core/getAllowedBounds.html | 146 -- doc/core/getElementalBalance.html | 215 --- doc/core/getEssentialRxns.html | 126 -- doc/core/getExchangeRxns.html | 170 --- doc/core/getExpressionStructure.html | 180 --- doc/core/getFluxZ.html | 120 -- doc/core/getGenesFromGrRules.html | 141 -- doc/core/getIndexes.html | 201 --- doc/core/getMetsInComp.html | 80 - doc/core/getMinNrFluxes.html | 237 --- doc/core/getModelFromHomology.html | 663 -------- doc/core/getRxnsInComp.html | 100 -- doc/core/getTransportRxns.html | 80 - doc/core/guessComposition.html | 247 --- doc/core/haveFlux.html | 148 -- doc/core/index.html | 29 - doc/core/makeSomething.html | 275 ---- doc/core/mapCompartments.html | 214 --- doc/core/mergeCompartments.html | 209 --- doc/core/mergeModels.html | 720 --------- doc/core/parallelPoolRAVEN.html | 123 -- doc/core/parseFormulas.html | 318 ---- doc/core/parseRxnEqu.html | 135 -- doc/core/parseTaskList.html | 441 ------ doc/core/permuteModel.html | 228 --- doc/core/predictLocalization.html | 1247 --------------- doc/core/printFluxes.html | 270 ---- doc/core/printModel.html | 147 -- doc/core/printModelStats.html | 221 --- doc/core/printOrange.html | 78 - doc/core/randomSampling.html | 317 ---- doc/core/removeBadRxns.html | 357 ----- doc/core/removeGenes.html | 194 --- doc/core/removeMets.html | 198 --- doc/core/removeReactions.html | 218 --- doc/core/replaceMets.html | 226 --- doc/core/reporterMetabolites.html | 274 ---- doc/core/runDynamicFBA.html | 218 --- doc/core/runPhenotypePhasePlane.html | 161 -- doc/core/runProductionEnvelope.html | 127 -- doc/core/runRobustnessAnalysis.html | 140 -- doc/core/runSimpleOptKnock.html | 198 --- doc/core/setExchangeBounds.html | 309 ---- doc/core/setParam.html | 202 --- doc/core/simplifyModel.html | 403 ----- doc/core/sortModel.html | 249 --- doc/core/standardizeGrRules.html | 236 --- doc/demoicon.gif | Bin 214 -> 0 bytes doc/down.png | Bin 133 -> 0 bytes doc/doxysearch.php | 329 ---- doc/external/combineMetaCycKEGGModels.html | 380 ----- doc/external/getBlast.html | 267 ---- doc/external/getBlastFromExcel.html | 185 --- doc/external/getDiamond.html | 250 --- doc/external/getWoLFScores.html | 113 -- doc/external/index.html | 31 - doc/external/kegg/constructMultiFasta.html | 222 --- doc/external/kegg/getGenesFromKEGG.html | 516 ------- .../kegg/getKEGGModelForOrganism.html | 1342 ----------------- doc/external/kegg/getMetsFromKEGG.html | 391 ----- doc/external/kegg/getModelFromKEGG.html | 381 ----- doc/external/kegg/getPhylDist.html | 208 --- doc/external/kegg/getRxnsFromKEGG.html | 620 -------- doc/external/kegg/getWSLpath.html | 83 - doc/external/kegg/index.html | 31 - doc/external/makeFakeBlastStructure.html | 129 -- doc/external/metacyc/addSpontaneousRxns.html | 157 -- .../metacyc/getEnzymesFromMetaCyc.html | 366 ----- .../metacyc/getMetaCycModelForOrganism.html | 350 ----- doc/external/metacyc/getMetsFromMetaCyc.html | 362 ----- doc/external/metacyc/getModelFromMetaCyc.html | 261 ---- doc/external/metacyc/getRxnsFromMetaCyc.html | 629 -------- doc/external/metacyc/index.html | 31 - doc/external/metacyc/linkMetaCycKEGGRxns.html | 159 -- doc/external/parseScores.html | 189 --- doc/external/updateDocumentation.html | 95 -- doc/fortran.png | Bin 265 -> 0 bytes doc/hp.png | Bin 255 -> 0 bytes doc/hpa/index.html | 29 - doc/hpa/parseHPA.html | 188 --- doc/hpa/parseHPArna.html | 136 -- doc/hpa/scoreModel.html | 428 ------ doc/index.html | 81 - doc/installation/addRavenToUserPath.html | 98 -- doc/installation/checkFunctionUniqueness.html | 161 -- doc/installation/checkInstallation.html | 481 ------ doc/installation/index.html | 29 - doc/installation/removeRavenFromPath.html | 97 -- doc/io/SBMLFromExcel.html | 94 -- doc/io/addJavaPaths.html | 76 - doc/io/checkFileExistence.html | 152 -- doc/io/cleanSheet.html | 170 --- doc/io/closeModel.html | 115 -- doc/io/exportForGit.html | 244 --- doc/io/exportModel.html | 868 ----------- doc/io/exportModelToSIF.html | 148 -- doc/io/exportToExcelFormat.html | 459 ------ doc/io/exportToTabDelimited.html | 407 ----- doc/io/getFullPath.html | 439 ------ doc/io/getMD5Hash.html | 118 -- doc/io/getToolboxVersion.html | 146 -- doc/io/importExcelModel.html | 1051 ------------- doc/io/importModel.html | 1263 ---------------- doc/io/index.html | 29 - doc/io/loadSheet.html | 130 -- doc/io/loadWorkbook.html | 119 -- doc/io/readYAMLmodel.html | 750 --------- doc/io/sortIdentifiers.html | 83 - doc/io/startup.html | 49 - doc/io/writeSheet.html | 211 --- doc/io/writeYAMLmodel.html | 448 ------ doc/left.png | Bin 136 -> 0 bytes doc/legacy/core/changeGeneAssoc.html | 117 -- doc/legacy/core/index.html | 29 - .../constructPathwayFromCelldesigner.html | 590 -------- doc/legacy/external/index.html | 29 - doc/linux.png | Bin 272 -> 0 bytes doc/m2html.css | 90 -- doc/matlabicon.gif | Bin 574 -> 0 bytes doc/mex.png | Bin 242 -> 0 bytes doc/pathway/colorPathway.html | 143 -- doc/pathway/getPathwayDimensions.html | 109 -- doc/pathway/index.html | 29 - doc/pathway/mapPathwayRxnNames.html | 98 -- doc/pathway/markPathwayWithExpression.html | 118 -- doc/pathway/markPathwayWithFluxes.html | 111 -- doc/pathway/trimPathway.html | 146 -- doc/pcode.png | Bin 212 -> 0 bytes doc/plotting/colorSubsystem.html | 121 -- doc/plotting/drawMap.html | 211 --- doc/plotting/drawPathway.html | 481 ------ doc/plotting/getColorCodes.html | 208 --- doc/plotting/getObjectiveString.html | 114 -- doc/plotting/index.html | 29 - doc/plotting/plotAdditionalInfo.html | 189 --- doc/plotting/plotLabels.html | 76 - doc/plotting/setColorToMapRxns.html | 659 -------- doc/plotting/setOmicDataToRxns.html | 103 -- doc/plotting/setTitle.html | 70 - doc/right.png | Bin 136 -> 0 bytes doc/sgi.png | Bin 263 -> 0 bytes doc/simulinkicon.gif | Bin 977 -> 0 bytes doc/solaris.png | Bin 286 -> 0 bytes doc/solver/checkSolution.html | 83 - doc/solver/index.html | 29 - doc/solver/optimizeProb.html | 344 ----- doc/solver/qMOMA.html | 150 -- doc/solver/setRavenSolver.html | 119 -- doc/solver/solveLP.html | 310 ---- doc/solver/solveQP.html | 127 -- .../addIdentifierPrefix.html | 128 -- doc/struct_conversion/editMiriam.html | 200 --- doc/struct_conversion/extractMiriam.html | 156 -- doc/struct_conversion/index.html | 29 - doc/struct_conversion/ravenCobraWrapper.html | 528 ------- .../removeIdentifierPrefix.html | 143 -- .../standardizeModelFieldOrder.html | 123 -- doc/testing/manual_tests/ManualINITTests.html | 170 --- doc/testing/manual_tests/index.html | 29 - doc/testing/unit_tests/blastPlusTests.html | 108 -- doc/testing/unit_tests/cdhitTests.html | 129 -- doc/testing/unit_tests/checkTasksTests.html | 138 -- doc/testing/unit_tests/diamondTests.html | 107 -- .../unit_tests/fillGapsLargeTests.html | 146 -- .../unit_tests/fillGapsSmallTests.html | 144 -- doc/testing/unit_tests/hmmerTests.html | 203 --- doc/testing/unit_tests/importExportTests.html | 153 -- doc/testing/unit_tests/index.html | 31 - doc/testing/unit_tests/mafftTests.html | 117 -- doc/testing/unit_tests/mergeModelsTests.html | 159 -- doc/testing/unit_tests/miriamTests.html | 86 -- .../unit_tests/modelAbilitiesTests.html | 173 --- .../unit_tests/modelConversionTests.html | 75 - .../unit_tests/modelCurationTests.html | 543 ------- doc/testing/unit_tests/modelSortingTests.html | 118 -- doc/testing/unit_tests/solverTests.html | 192 --- doc/testing/unit_tests/tinitTests.html | 665 -------- doc/tutorial/index.html | 31 - doc/tutorial/tutorial1.html | 194 --- doc/tutorial/tutorial2.html | 73 - doc/tutorial/tutorial2_solutions.html | 67 - doc/tutorial/tutorial3.html | 134 -- doc/tutorial/tutorial3_solutions.html | 166 -- doc/tutorial/tutorial4.html | 84 -- doc/tutorial/tutorial4_solutions.html | 207 --- doc/tutorial/tutorial5.html | 252 ---- doc/tutorial/tutorial6.html | 208 --- doc/up.png | Bin 162 -> 0 bytes doc/utils/emptyOrLogicalScalar.html | 53 - doc/utils/emptyOrTextOrCellOfText.html | 90 -- doc/utils/emptyOrTextScalar.html | 59 - doc/utils/index.html | 29 - doc/utils/runRAVENtests.html | 60 - doc/windows.png | Bin 286 -> 0 bytes 255 files changed, 55253 deletions(-) delete mode 100644 doc/INIT/INITStepDesc.html delete mode 100644 doc/INIT/ftINIT.html delete mode 100644 doc/INIT/ftINITFillGaps.html delete mode 100644 doc/INIT/ftINITFillGapsForAllTasks.html delete mode 100644 doc/INIT/ftINITFillGapsMILP.html delete mode 100644 doc/INIT/ftINITInternalAlg.html delete mode 100644 doc/INIT/getExprForRxnScore.html delete mode 100644 doc/INIT/getINITModel.html delete mode 100644 doc/INIT/getINITSteps.html delete mode 100644 doc/INIT/groupRxnScores.html delete mode 100644 doc/INIT/index.html delete mode 100644 doc/INIT/mergeLinear.html delete mode 100644 doc/INIT/prepINITModel.html delete mode 100644 doc/INIT/removeLowScoreGenes.html delete mode 100644 doc/INIT/rescaleModelForINIT.html delete mode 100644 doc/INIT/reverseRxns.html delete mode 100644 doc/INIT/runINIT.html delete mode 100644 doc/INIT/scoreComplexModel.html delete mode 100644 doc/alpha.png delete mode 100644 doc/c++.png delete mode 100644 doc/c.png delete mode 100644 doc/core/FSEOF.html delete mode 100644 doc/core/addExchangeRxns.html delete mode 100644 doc/core/addGenesRaven.html delete mode 100644 doc/core/addMets.html delete mode 100644 doc/core/addRxns.html delete mode 100644 doc/core/addRxnsGenesMets.html delete mode 100644 doc/core/addTransport.html delete mode 100644 doc/core/analyzeSampling.html delete mode 100644 doc/core/buildEquation.html delete mode 100644 doc/core/canConsume.html delete mode 100644 doc/core/canProduce.html delete mode 100644 doc/core/changeGrRules.html delete mode 100644 doc/core/changeRxns.html delete mode 100644 doc/core/checkModelStruct.html delete mode 100644 doc/core/checkProduction.html delete mode 100644 doc/core/checkRxn.html delete mode 100644 doc/core/checkTasks.html delete mode 100644 doc/core/compareMultipleModels.html delete mode 100644 doc/core/compareRxnsGenesMetsComps.html delete mode 100644 doc/core/constructEquations.html delete mode 100644 doc/core/constructS.html delete mode 100644 doc/core/consumeSomething.html delete mode 100644 doc/core/contractModel.html delete mode 100644 doc/core/convertCharArray.html delete mode 100644 doc/core/convertToIrrev.html delete mode 100644 doc/core/copyToComps.html delete mode 100644 doc/core/deleteUnusedGenes.html delete mode 100644 doc/core/dispEM.html delete mode 100644 doc/core/expandModel.html delete mode 100644 doc/core/fillGaps.html delete mode 100644 doc/core/findGeneDeletions.html delete mode 100644 doc/core/findRAVENroot.html delete mode 100644 doc/core/fitParameters.html delete mode 100644 doc/core/fitTasks.html delete mode 100644 doc/core/followChanged.html delete mode 100644 doc/core/followFluxes.html delete mode 100644 doc/core/gapReport.html delete mode 100644 doc/core/generateNewIds.html delete mode 100644 doc/core/getAllRxnsFromGenes.html delete mode 100644 doc/core/getAllSubGraphs.html delete mode 100644 doc/core/getAllowedBounds.html delete mode 100644 doc/core/getElementalBalance.html delete mode 100644 doc/core/getEssentialRxns.html delete mode 100644 doc/core/getExchangeRxns.html delete mode 100644 doc/core/getExpressionStructure.html delete mode 100644 doc/core/getFluxZ.html delete mode 100644 doc/core/getGenesFromGrRules.html delete mode 100644 doc/core/getIndexes.html delete mode 100644 doc/core/getMetsInComp.html delete mode 100644 doc/core/getMinNrFluxes.html delete mode 100644 doc/core/getModelFromHomology.html delete mode 100644 doc/core/getRxnsInComp.html delete mode 100644 doc/core/getTransportRxns.html delete mode 100644 doc/core/guessComposition.html delete mode 100644 doc/core/haveFlux.html delete mode 100644 doc/core/index.html delete mode 100644 doc/core/makeSomething.html delete mode 100644 doc/core/mapCompartments.html delete mode 100644 doc/core/mergeCompartments.html delete mode 100644 doc/core/mergeModels.html delete mode 100644 doc/core/parallelPoolRAVEN.html delete mode 100644 doc/core/parseFormulas.html delete mode 100644 doc/core/parseRxnEqu.html delete mode 100644 doc/core/parseTaskList.html delete mode 100644 doc/core/permuteModel.html delete mode 100644 doc/core/predictLocalization.html delete mode 100644 doc/core/printFluxes.html delete mode 100644 doc/core/printModel.html delete mode 100644 doc/core/printModelStats.html delete mode 100644 doc/core/printOrange.html delete mode 100644 doc/core/randomSampling.html delete mode 100644 doc/core/removeBadRxns.html delete mode 100644 doc/core/removeGenes.html delete mode 100644 doc/core/removeMets.html delete mode 100644 doc/core/removeReactions.html delete mode 100644 doc/core/replaceMets.html delete mode 100644 doc/core/reporterMetabolites.html delete mode 100644 doc/core/runDynamicFBA.html delete mode 100644 doc/core/runPhenotypePhasePlane.html delete mode 100644 doc/core/runProductionEnvelope.html delete mode 100644 doc/core/runRobustnessAnalysis.html delete mode 100644 doc/core/runSimpleOptKnock.html delete mode 100644 doc/core/setExchangeBounds.html delete mode 100644 doc/core/setParam.html delete mode 100644 doc/core/simplifyModel.html delete mode 100644 doc/core/sortModel.html delete mode 100644 doc/core/standardizeGrRules.html delete mode 100644 doc/demoicon.gif delete mode 100644 doc/down.png delete mode 100644 doc/doxysearch.php delete mode 100644 doc/external/combineMetaCycKEGGModels.html delete mode 100644 doc/external/getBlast.html delete mode 100644 doc/external/getBlastFromExcel.html delete mode 100644 doc/external/getDiamond.html delete mode 100644 doc/external/getWoLFScores.html delete mode 100644 doc/external/index.html delete mode 100644 doc/external/kegg/constructMultiFasta.html delete mode 100644 doc/external/kegg/getGenesFromKEGG.html delete mode 100644 doc/external/kegg/getKEGGModelForOrganism.html delete mode 100644 doc/external/kegg/getMetsFromKEGG.html delete mode 100644 doc/external/kegg/getModelFromKEGG.html delete mode 100644 doc/external/kegg/getPhylDist.html delete mode 100644 doc/external/kegg/getRxnsFromKEGG.html delete mode 100644 doc/external/kegg/getWSLpath.html delete mode 100644 doc/external/kegg/index.html delete mode 100644 doc/external/makeFakeBlastStructure.html delete mode 100644 doc/external/metacyc/addSpontaneousRxns.html delete mode 100644 doc/external/metacyc/getEnzymesFromMetaCyc.html delete mode 100644 doc/external/metacyc/getMetaCycModelForOrganism.html delete mode 100644 doc/external/metacyc/getMetsFromMetaCyc.html delete mode 100644 doc/external/metacyc/getModelFromMetaCyc.html delete mode 100644 doc/external/metacyc/getRxnsFromMetaCyc.html delete mode 100644 doc/external/metacyc/index.html delete mode 100644 doc/external/metacyc/linkMetaCycKEGGRxns.html delete mode 100644 doc/external/parseScores.html delete mode 100644 doc/external/updateDocumentation.html delete mode 100644 doc/fortran.png delete mode 100644 doc/hp.png delete mode 100644 doc/hpa/index.html delete mode 100644 doc/hpa/parseHPA.html delete mode 100644 doc/hpa/parseHPArna.html delete mode 100644 doc/hpa/scoreModel.html delete mode 100644 doc/index.html delete mode 100644 doc/installation/addRavenToUserPath.html delete mode 100644 doc/installation/checkFunctionUniqueness.html delete mode 100644 doc/installation/checkInstallation.html delete mode 100644 doc/installation/index.html delete mode 100644 doc/installation/removeRavenFromPath.html delete mode 100644 doc/io/SBMLFromExcel.html delete mode 100644 doc/io/addJavaPaths.html delete mode 100644 doc/io/checkFileExistence.html delete mode 100644 doc/io/cleanSheet.html delete mode 100644 doc/io/closeModel.html delete mode 100644 doc/io/exportForGit.html delete mode 100644 doc/io/exportModel.html delete mode 100644 doc/io/exportModelToSIF.html delete mode 100644 doc/io/exportToExcelFormat.html delete mode 100644 doc/io/exportToTabDelimited.html delete mode 100644 doc/io/getFullPath.html delete mode 100644 doc/io/getMD5Hash.html delete mode 100644 doc/io/getToolboxVersion.html delete mode 100644 doc/io/importExcelModel.html delete mode 100644 doc/io/importModel.html delete mode 100644 doc/io/index.html delete mode 100644 doc/io/loadSheet.html delete mode 100644 doc/io/loadWorkbook.html delete mode 100644 doc/io/readYAMLmodel.html delete mode 100644 doc/io/sortIdentifiers.html delete mode 100644 doc/io/startup.html delete mode 100644 doc/io/writeSheet.html delete mode 100644 doc/io/writeYAMLmodel.html delete mode 100644 doc/left.png delete mode 100644 doc/legacy/core/changeGeneAssoc.html delete mode 100644 doc/legacy/core/index.html delete mode 100644 doc/legacy/external/constructPathwayFromCelldesigner.html delete mode 100644 doc/legacy/external/index.html delete mode 100644 doc/linux.png delete mode 100644 doc/m2html.css delete mode 100644 doc/matlabicon.gif delete mode 100644 doc/mex.png delete mode 100644 doc/pathway/colorPathway.html delete mode 100644 doc/pathway/getPathwayDimensions.html delete mode 100644 doc/pathway/index.html delete mode 100644 doc/pathway/mapPathwayRxnNames.html delete mode 100644 doc/pathway/markPathwayWithExpression.html delete mode 100644 doc/pathway/markPathwayWithFluxes.html delete mode 100644 doc/pathway/trimPathway.html delete mode 100644 doc/pcode.png delete mode 100644 doc/plotting/colorSubsystem.html delete mode 100644 doc/plotting/drawMap.html delete mode 100644 doc/plotting/drawPathway.html delete mode 100644 doc/plotting/getColorCodes.html delete mode 100644 doc/plotting/getObjectiveString.html delete mode 100644 doc/plotting/index.html delete mode 100644 doc/plotting/plotAdditionalInfo.html delete mode 100644 doc/plotting/plotLabels.html delete mode 100644 doc/plotting/setColorToMapRxns.html delete mode 100644 doc/plotting/setOmicDataToRxns.html delete mode 100644 doc/plotting/setTitle.html delete mode 100644 doc/right.png delete mode 100644 doc/sgi.png delete mode 100644 doc/simulinkicon.gif delete mode 100644 doc/solaris.png delete mode 100644 doc/solver/checkSolution.html delete mode 100644 doc/solver/index.html delete mode 100644 doc/solver/optimizeProb.html delete mode 100644 doc/solver/qMOMA.html delete mode 100644 doc/solver/setRavenSolver.html delete mode 100644 doc/solver/solveLP.html delete mode 100644 doc/solver/solveQP.html delete mode 100644 doc/struct_conversion/addIdentifierPrefix.html delete mode 100644 doc/struct_conversion/editMiriam.html delete mode 100644 doc/struct_conversion/extractMiriam.html delete mode 100644 doc/struct_conversion/index.html delete mode 100644 doc/struct_conversion/ravenCobraWrapper.html delete mode 100644 doc/struct_conversion/removeIdentifierPrefix.html delete mode 100644 doc/struct_conversion/standardizeModelFieldOrder.html delete mode 100644 doc/testing/manual_tests/ManualINITTests.html delete mode 100644 doc/testing/manual_tests/index.html delete mode 100644 doc/testing/unit_tests/blastPlusTests.html delete mode 100644 doc/testing/unit_tests/cdhitTests.html delete mode 100644 doc/testing/unit_tests/checkTasksTests.html delete mode 100644 doc/testing/unit_tests/diamondTests.html delete mode 100644 doc/testing/unit_tests/fillGapsLargeTests.html delete mode 100644 doc/testing/unit_tests/fillGapsSmallTests.html delete mode 100644 doc/testing/unit_tests/hmmerTests.html delete mode 100644 doc/testing/unit_tests/importExportTests.html delete mode 100644 doc/testing/unit_tests/index.html delete mode 100644 doc/testing/unit_tests/mafftTests.html delete mode 100644 doc/testing/unit_tests/mergeModelsTests.html delete mode 100644 doc/testing/unit_tests/miriamTests.html delete mode 100644 doc/testing/unit_tests/modelAbilitiesTests.html delete mode 100644 doc/testing/unit_tests/modelConversionTests.html delete mode 100644 doc/testing/unit_tests/modelCurationTests.html delete mode 100644 doc/testing/unit_tests/modelSortingTests.html delete mode 100644 doc/testing/unit_tests/solverTests.html delete mode 100644 doc/testing/unit_tests/tinitTests.html delete mode 100644 doc/tutorial/index.html delete mode 100644 doc/tutorial/tutorial1.html delete mode 100644 doc/tutorial/tutorial2.html delete mode 100644 doc/tutorial/tutorial2_solutions.html delete mode 100644 doc/tutorial/tutorial3.html delete mode 100644 doc/tutorial/tutorial3_solutions.html delete mode 100644 doc/tutorial/tutorial4.html delete mode 100644 doc/tutorial/tutorial4_solutions.html delete mode 100644 doc/tutorial/tutorial5.html delete mode 100644 doc/tutorial/tutorial6.html delete mode 100644 doc/up.png delete mode 100644 doc/utils/emptyOrLogicalScalar.html delete mode 100644 doc/utils/emptyOrTextOrCellOfText.html delete mode 100644 doc/utils/emptyOrTextScalar.html delete mode 100644 doc/utils/index.html delete mode 100644 doc/utils/runRAVENtests.html delete mode 100644 doc/windows.png diff --git a/doc/INIT/INITStepDesc.html b/doc/INIT/INITStepDesc.html deleted file mode 100644 index 113533f71..000000000 --- a/doc/INIT/INITStepDesc.html +++ /dev/null @@ -1,126 +0,0 @@ - - - - Description of INITStepDesc - - - - - - - - - -
Home > INIT > INITStepDesc.m
- - - -

INITStepDesc -

- -

PURPOSE ^

-
- -

SYNOPSIS ^

-
This is a script file.
- -

DESCRIPTION ^

-
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 classdef INITStepDesc
-0002 % Describes a step in the ftINIT algorithm. A cell array of objects of this
-0003 % class is used as input to ftINIT to specify how the algorithm should be run.
-0004    properties
-0005       PosRevOff
-0006       AllowMetSecr
-0007       HowToUsePrevResults %'ignore', 'exclude', 'essential'
-0008       RxnsToIgnoreMask %Specifies reactions to leave outside the problem in
-0009                        %the MILP.
-0010                        % [b1,b2,b3,b4,b5,b6,b7,b8], bx is either 0 or 1,
-0011                        % where 1 means that the group is excluded.
-0012                        % b1 - Exchange rxns
-0013                        % b2 - Import rxns without GPRs (from s into the cell)
-0014                        % b3 - Simple transport reactions without GPRs (moves one metabolite between compartments)
-0015                        % b4 - Advanced transport reactions without GPRs (moves metabolites between compartments, more complex function such as antiporter)
-0016                        % b5 - Spontaneous reactions
-0017                        % b6 - Reactions in the s compartment without GPRs
-0018                        % b7 - Customly specified rxns (sent in when generating prepData)
-0019                        % b8 - All rxns without GPRs
-0020 
-0021       MetsToIgnore % Structure describing mets that can be removed from the model
-0022                    % before running ftINIT, such as water etc.
-0023                    % .simpleMets
-0024                    %      .mets        Names of metabolites to remove
-0025                    %      .compsToKeep Compartments for which metabolites should be kept.
-0026       MILPParams %Cell array of MILPparams - dictates how many iterations that will be run in this step.
-0027                  %Typically, MIPGap and TimeLimit is specified. ftINIT additionally
-0028                  %defaults Threads to 1 (single-threaded Gurobi) for determinism;
-0029                  %set Threads here to override (0 = use all cores).
-0030       AbsMIPGaps %If the objective is close to zero, a percentage of that is very small.
-0031                  %Therefore, also set an absolut value for this (typically 10 or 20).
-0032                  %For practical reasons, the first number is not used
-0033    end
-0034    methods
-0035       function obj = INITStepDesc(posRevOff_, AllowMetSecr_, howToUsePrevResults_, rxnsToIgnoreMask_, metsToIgnore_, MILPParams_, absMIPGaps_)
-0036          if nargin > 0
-0037             obj.PosRevOff = posRevOff_;
-0038          else
-0039             obj.PosRevOff = false;
-0040          end
-0041          if nargin > 1
-0042             obj.AllowMetSecr = AllowMetSecr_;
-0043          else
-0044             obj.AllowMetSecr = false;
-0045          end
-0046          if nargin > 2
-0047             obj.HowToUsePrevResults = howToUsePrevResults_;
-0048          else
-0049             obj.HowToUsePrevResults = 'essential';
-0050          end
-0051          if nargin > 3
-0052             obj.RxnsToIgnoreMask = rxnsToIgnoreMask_;
-0053          else
-0054             obj.RxnsToIgnoreMask = [1;0;0;0;0;0;0;0];
-0055          end
-0056          if nargin > 4
-0057             obj.MetsToIgnore = metsToIgnore_;
-0058          else
-0059             obj.MetsToIgnore = [1;0;0;0;0;0;0;0];
-0060          end
-0061          if nargin > 5
-0062             obj.MILPParams = MILPParams_;
-0063          else
-0064             params = struct();
-0065             params.TimeLimit = 5000;
-0066             params.MIPGap = 0.0004;            
-0067             obj.MILPParams = {params};
-0068          end
-0069          
-0070          if nargin > 6
-0071             obj.AbsMIPGaps = absMIPGaps_;
-0072          else
-0073             obj.AbsMIPGaps = 10;            
-0074          end
-0075       end
-0076    end
-0077 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/INIT/ftINIT.html b/doc/INIT/ftINIT.html deleted file mode 100644 index 6133e894d..000000000 --- a/doc/INIT/ftINIT.html +++ /dev/null @@ -1,580 +0,0 @@ - - - - Description of ftINIT - - - - - - - - - -
Home > INIT > ftINIT.m
- - - -

ftINIT -

- -

PURPOSE ^

-
ftINIT
- -

SYNOPSIS ^

-
function [model, metProduction, addedRxnsForTasks, deletedRxnsInINIT, fullMipRes] = ftINIT(prepData, tissue, celltype, hpaData, transcrData, metabolomicsData, INITSteps, removeGenes, useScoresForTasks, paramsFT, verbose)
- -

DESCRIPTION ^

-
 ftINIT
-   Main function for generates a model using the ftINIT algorithm, based 
-   on proteomics and/or transcriptomics and/or metabolomics and/or metabolic 
-   tasks. The algorithm is not designed for running with metabolomics only.
-   The function prepINITModel needs to be run first for the template
-   model (such as the generic Human-GEM), but only need to be run once. This
-   function precalculates things independent of the omics to speed up the model
-   generation process, and outputs the prepData, which is input to this function.
-
-   prepData            The prepdata for the model.
-   tissue              tissue to score for. Should exist in either
-                       hpaData.tissues or transcrData.tissues
-   celltype            cell type to score for. Should exist in either
-                       hpaData.celltypes or transcrData.celltypes for this
-                       tissue (optional, default is to use the max values
-                       among all the cell types for the tissue.
-   hpaData             HPA data structure from parseHPA (optional if transcrData
-                       is supplied, default [])
-   transcrData         gene expression data structure (optional if hpaData is
-                       supplied, default []). Used to be called arrayData.
-       genes           cell array with the unique gene names
-       tissues         cell array with the tissue names. The list may not
-                       be unique, as there can be multiple cell types per
-                       tissue.
-       celltypes       cell array with the cell type names for each tissue
-       levels          GENESxTISSUES array with the expression level for
-                       each gene in each tissue/celltype. NaN should be
-                       used when no measurement was performed
-       threshold       a single value or a vector of gene expression 
-                       thresholds, above which genes are considered to be
-                       "expressed". default = 1(optional, by default, the mean expression
-                       levels of each gene across all tissues in transcrData
-                       will be used as the threshold values)
-       singleCells     binary value selecting whether to use the
-                       single-cell algorithm to identify expressed genes.
-                       If used, specify cell subpopulations in CELLTYPES
-                       (optional, default [])
-       plotResults     true if single cell probability distributions
-                       should be plotted (optional, default = false)
-   metabolomicsData    cell array with metabolite names that the model
-                       should produce (optional, default [])
-   INITSteps           Specifies the steps in the algorithm. For more info,
-                       see INITStepDesc and getINITSteps. 
-                       (optional, default getINITSteps(), which is the standard ftINIT).
-   removeGenes         if true, low-abundance genes will be removed from
-                       grRules, unless they are the only gene associated 
-                       with a reaction, or a subunit of an enzyme complex
-                       (see "removeLowScoreGenes" function for details).
-                       If false, grRules will not be modified; however,
-                       genes that were associated only with removed 
-                       reactions will not be present in the final model.
-                       (optional, default true).
-   useScoresForTasks   true if the calculated reaction scored should be 
-                       used as weights when fitting to tasks (optional, default
-                       true)
-   paramsFT            *obsolete option*
-   verbose             if true, the MILP progression will be shown. 
-                       (optional, default false)
-
-   model                   the resulting model structure
-   metProduction           array that indicates which of the
-                           metabolites in metabolomicsData that could be
-                           produced. Note that this is before the
-                           gap-filling process to enable defined tasks. To
-                           see which metabolites that can be produced in
-                           the final model, use canProduce.
-                           -2: metabolite name not found in model
-                           -1: metabolite found, but it could not be produced
-                           1: metabolite could be produced
-   addedRxnsForTasks       cell array of the reactions which were added in
-                           order to perform the tasks
-   deletedRxnsInINIT       cell array of reactions deleted because they
-                           could not carry flux (INIT requires a
-                           functional input model)
-   fullMipRes              The solver results from the last MILP step run
-
-   This is the main function for automatic reconstruction of models based
-   on the ftINIT algorithm (). 
-
-   NOTE: Exchange metabolites should normally not be removed from the model
-   when using this approach, since checkTasks/fitTasks rely on putting specific
-   constraints for each task. The INIT algorithm will remove exchange metabolites
-   if any are present. Use importModel(file,false) to import a model with
-   exchange metabolites remaining.
-
- Usage: [model, metProduction, addedRxnsForTasks, deletedRxnsInINIT, ...
-               fullMipRes] = ...
-               ftINIT(prepData, tissue, celltype, hpaData, transcrData, ...
-               metabolomicsData, INITSteps, removeGenes, useScoresForTasks, ...
-               paramsFT);
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 function [model, metProduction, addedRxnsForTasks, deletedRxnsInINIT, fullMipRes] = ftINIT(prepData, tissue, celltype, hpaData, transcrData, metabolomicsData, INITSteps, removeGenes, useScoresForTasks, paramsFT, verbose)
-0002 % ftINIT
-0003 %   Main function for generates a model using the ftINIT algorithm, based
-0004 %   on proteomics and/or transcriptomics and/or metabolomics and/or metabolic
-0005 %   tasks. The algorithm is not designed for running with metabolomics only.
-0006 %   The function prepINITModel needs to be run first for the template
-0007 %   model (such as the generic Human-GEM), but only need to be run once. This
-0008 %   function precalculates things independent of the omics to speed up the model
-0009 %   generation process, and outputs the prepData, which is input to this function.
-0010 %
-0011 %   prepData            The prepdata for the model.
-0012 %   tissue              tissue to score for. Should exist in either
-0013 %                       hpaData.tissues or transcrData.tissues
-0014 %   celltype            cell type to score for. Should exist in either
-0015 %                       hpaData.celltypes or transcrData.celltypes for this
-0016 %                       tissue (optional, default is to use the max values
-0017 %                       among all the cell types for the tissue.
-0018 %   hpaData             HPA data structure from parseHPA (optional if transcrData
-0019 %                       is supplied, default [])
-0020 %   transcrData         gene expression data structure (optional if hpaData is
-0021 %                       supplied, default []). Used to be called arrayData.
-0022 %       genes           cell array with the unique gene names
-0023 %       tissues         cell array with the tissue names. The list may not
-0024 %                       be unique, as there can be multiple cell types per
-0025 %                       tissue.
-0026 %       celltypes       cell array with the cell type names for each tissue
-0027 %       levels          GENESxTISSUES array with the expression level for
-0028 %                       each gene in each tissue/celltype. NaN should be
-0029 %                       used when no measurement was performed
-0030 %       threshold       a single value or a vector of gene expression
-0031 %                       thresholds, above which genes are considered to be
-0032 %                       "expressed". default = 1(optional, by default, the mean expression
-0033 %                       levels of each gene across all tissues in transcrData
-0034 %                       will be used as the threshold values)
-0035 %       singleCells     binary value selecting whether to use the
-0036 %                       single-cell algorithm to identify expressed genes.
-0037 %                       If used, specify cell subpopulations in CELLTYPES
-0038 %                       (optional, default [])
-0039 %       plotResults     true if single cell probability distributions
-0040 %                       should be plotted (optional, default = false)
-0041 %   metabolomicsData    cell array with metabolite names that the model
-0042 %                       should produce (optional, default [])
-0043 %   INITSteps           Specifies the steps in the algorithm. For more info,
-0044 %                       see INITStepDesc and getINITSteps.
-0045 %                       (optional, default getINITSteps(), which is the standard ftINIT).
-0046 %   removeGenes         if true, low-abundance genes will be removed from
-0047 %                       grRules, unless they are the only gene associated
-0048 %                       with a reaction, or a subunit of an enzyme complex
-0049 %                       (see "removeLowScoreGenes" function for details).
-0050 %                       If false, grRules will not be modified; however,
-0051 %                       genes that were associated only with removed
-0052 %                       reactions will not be present in the final model.
-0053 %                       (optional, default true).
-0054 %   useScoresForTasks   true if the calculated reaction scored should be
-0055 %                       used as weights when fitting to tasks (optional, default
-0056 %                       true)
-0057 %   paramsFT            *obsolete option*
-0058 %   verbose             if true, the MILP progression will be shown.
-0059 %                       (optional, default false)
-0060 %
-0061 %   model                   the resulting model structure
-0062 %   metProduction           array that indicates which of the
-0063 %                           metabolites in metabolomicsData that could be
-0064 %                           produced. Note that this is before the
-0065 %                           gap-filling process to enable defined tasks. To
-0066 %                           see which metabolites that can be produced in
-0067 %                           the final model, use canProduce.
-0068 %                           -2: metabolite name not found in model
-0069 %                           -1: metabolite found, but it could not be produced
-0070 %                           1: metabolite could be produced
-0071 %   addedRxnsForTasks       cell array of the reactions which were added in
-0072 %                           order to perform the tasks
-0073 %   deletedRxnsInINIT       cell array of reactions deleted because they
-0074 %                           could not carry flux (INIT requires a
-0075 %                           functional input model)
-0076 %   fullMipRes              The solver results from the last MILP step run
-0077 %
-0078 %   This is the main function for automatic reconstruction of models based
-0079 %   on the ftINIT algorithm ().
-0080 %
-0081 %   NOTE: Exchange metabolites should normally not be removed from the model
-0082 %   when using this approach, since checkTasks/fitTasks rely on putting specific
-0083 %   constraints for each task. The INIT algorithm will remove exchange metabolites
-0084 %   if any are present. Use importModel(file,false) to import a model with
-0085 %   exchange metabolites remaining.
-0086 %
-0087 % Usage: [model, metProduction, addedRxnsForTasks, deletedRxnsInINIT, ...
-0088 %               fullMipRes] = ...
-0089 %               ftINIT(prepData, tissue, celltype, hpaData, transcrData, ...
-0090 %               metabolomicsData, INITSteps, removeGenes, useScoresForTasks, ...
-0091 %               paramsFT);
-0092 %
-0093 
-0094 
-0095 if nargin < 5
-0096     transcrData = [];
-0097 end
-0098 if nargin < 6
-0099     metabolomicsData = [];
-0100 end
-0101 if nargin < 7 || isempty(INITSteps)
-0102     INITSteps = getINITSteps([],'1+1');
-0103 end
-0104 if nargin < 8 || isempty(removeGenes)
-0105     removeGenes = true;
-0106 end
-0107 if nargin < 9 || isempty(useScoresForTasks)
-0108     useScoresForTasks = true;
-0109 end
-0110 if nargin < 10
-0111     paramsFT = [];
-0112 end
-0113 
-0114 if nargin < 11
-0115     verbose = false;
-0116 end
-0117 %Handle detected mets:
-0118 %Previously, this was handled by giving a bonus for secreting those metabolites,
-0119 %but that doesn't work since the metabolite secretion and uptake can be lost when
-0120 %we merge linearly dependent reactions.
-0121 %Instead, we need to figure out which reactions either produce or take up the mets.
-0122 %We then give a bonus if any of them carry flux.
-0123 %To simplify things, we focus on reactions that produce the metabolite (since there must be one such reaction).
-0124 %It is still a bit complicated though. In this step, we focus on identifying
-0125 %producer reactions. We further reason that the direction doesn't matter -
-0126 %we can force one of these reactions in any direction - if it becomes a consumer, it will
-0127 %automatically force another producer on as well (otherwise we'll have a net consumption).
-0128 
-0129 if (~isempty(metabolomicsData))
-0130     if length(unique(upper(metabolomicsData))) ~= length(metabolomicsData)
-0131         dispEM('Metabolomics contains the same metabolite multiple times');
-0132     end
-0133     metData = false(numel(metabolomicsData), length(prepData.minModel.rxns)); %one row per metabolite that is a boolean vector
-0134     for i=1:numel(metabolomicsData)
-0135         %Get the matching mets
-0136         metSel = ismember(upper(prepData.refModel.metNames),upper(metabolomicsData{i}));
-0137         prodRxnsSel = any(prepData.refModel.S(metSel,:) > 0,1) | ... %direct producers
-0138                      (any(prepData.refModel.S(metSel,:) < 0,1) & prepData.refModel.rev.'); %reversible reactions that are consumers
-0139         %convert the production rxns from refModel to minModel
-0140         prepData.groupIds;
-0141         [~,ia,ib] = intersect(prepData.minModel.rxns,prepData.refModel.rxns);
-0142         grpIdsMerged = nan(length(prepData.minModel.rxns),1);
-0143         grpIdsMerged(ia) = prepData.groupIds(ib);
-0144         
-0145         groupIdsPos = unique(prepData.groupIds(prodRxnsSel));%gets all group ids which includes a production rxn
-0146         groupIdsPos = groupIdsPos(groupIdsPos ~= 0);%remove the 0 id, it means there is no group
-0147         %the other option is that there is a direct match between the rxn id in minModel and refModel:
-0148         posRxns = prepData.refModel.rxns(prodRxnsSel);
-0149         directMatch = ismember(prepData.minModel.rxns, posRxns).';
-0150         
-0151         metData(i,:) = ismember(grpIdsMerged, groupIdsPos).' | directMatch;
-0152     end
-0153     metData = sparse(metData);
-0154 else
-0155     metData = [];
-0156 end
-0157 
-0158 % Get rxn scores and adapt them to the minimized model
-0159 origRxnScores = scoreComplexModel(prepData.refModel,hpaData,transcrData,tissue,celltype);
-0160 origRxnScores(origRxnScores > -0.1 & origRxnScores <= 0) = -0.1;%we don't want reaction scores that are exactly 0 (or close), this causes problems in the milp
-0161 origRxnScores(origRxnScores < 0.1 & origRxnScores > 0) = 0.1;
-0162 
-0163 rxnsTurnedOn = false(length(prepData.minModel.rxns),1);
-0164 fluxes = zeros(length(prepData.minModel.rxns),1);
-0165 
-0166 rxnsToIgnoreLastStep = [1;1;1;1;1;1;1;1];
-0167 
-0168 %We assume that all essential rxns are irrev - this is taken care of in
-0169 %prepINITModel. We then use an initial flux "from last run" of 0.1 for all
-0170 %reactions. This is used for knowing what flux should be forced through an
-0171 %essential rxn.
-0172 fluxes = ones(length(prepData.minModel.rxns), 1).*0.1;
-0173 
-0174 for initStep = 1:length(INITSteps)
-0175     disp(['ftINIT: Running step ' num2str(initStep)])
-0176     stp = INITSteps{initStep};
-0177     
-0178     if any ((rxnsToIgnoreLastStep - stp.RxnsToIgnoreMask) < 0)
-0179         dispEM('RxnsToIgnoreMask may not cover rxns not covered in previous steps, but the other way around is fine.');
-0180     end
-0181     rxnsToIgnoreLastStep = stp.RxnsToIgnoreMask;
-0182     
-0183     mm = prepData.minModel;
-0184     
-0185     if (~isempty(stp.MetsToIgnore))
-0186         if (~isempty(stp.MetsToIgnore.simpleMets))
-0187             %Here, we remove simple metabolites that will not really affect the milp but
-0188             %are very common in the S matrix. For example H2O, H+, etc.
-0189             %It is also possible to leave compartments untouched, for example the i compartment in the mitochondria (for H+).
-0190             metsToRem = ismember(mm.metNames,stp.MetsToIgnore.simpleMets.mets);
-0191             compsToKeep = find(ismember(mm.comps, stp.MetsToIgnore.simpleMets.compsToKeep));
-0192             metsToRem = metsToRem & ~ismember(mm.metComps, compsToKeep);
-0193             mm.S(metsToRem,:) = 0;
-0194         end    
-0195     end
-0196 
-0197     %Set up the reaction scores and essential rxns
-0198     rxnsToIgnore = getRxnsFromPattern(stp.RxnsToIgnoreMask, prepData);
-0199     rxnScores = groupRxnScores(prepData.minModel, origRxnScores, prepData.refModel.rxns, prepData.groupIds, rxnsToIgnore);
-0200 
-0201     essentialRxns = prepData.essentialRxns;
-0202     toRev = false(numel(mm.rxns),1);
-0203     %Handle the results from previous steps ('ignore', 'exclude', 'essential')
-0204     if strcmp(stp.HowToUsePrevResults, 'exclude')
-0205         rxnScores(rxnsTurnedOn) = 0; %This is not used anymore in any step setup.
-0206     elseif strcmp(stp.HowToUsePrevResults, 'essential')
-0207         %Make all reversible reactions turned on in previous steps reversible
-0208         %in the direction that they were previously carrying flux
-0209         
-0210         %first reverse the reactions that need to be reversed
-0211         rev = mm.rev == 1;
-0212         toRev = rxnsTurnedOn & rev & fluxes < 0;
-0213         mm = reverseRxns(mm, mm.rxns(toRev));
-0214         
-0215         %Then make them irreversible
-0216         mm.rev(rxnsTurnedOn) = 0;
-0217         mm.lb(rxnsTurnedOn) = 0;
-0218 
-0219         essentialRxns = unique([prepData.essentialRxns;mm.rxns(rxnsTurnedOn)]);
-0220     end
-0221 
-0222     
-0223     mipGap = 1;
-0224     first = true;
-0225     success = false;
-0226     fullMipRes = [];
-0227     for rn = 1:length(stp.MILPParams)
-0228         params = stp.MILPParams{rn};
-0229         if ~isfield(params, 'MIPGap')
-0230             params.MIPGap = 0.0004;
-0231         end
-0232         
-0233         if ~isfield(params, 'TimeLimit')
-0234             params.TimeLimit = 5000;
-0235         end
-0236 
-0237         %Default to single-threaded Gurobi MILP solving. Multi-threaded Gurobi
-0238         %can non-deterministically report the MILP as infeasible (issue #607).
-0239         %Override by setting 'Threads' in the step's MILPParams (0 = all cores).
-0240         if ~isfield(params, 'Threads')
-0241             params.Threads = 1;
-0242         end
-0243         
-0244         if ~first 
-0245             %There is sometimes a problem with that the objective function becomes close to zero,
-0246             %which leads to that a small percentage of that (which is the MIPGap sent in) is very small
-0247             %and the MILP hence takes a lot of time to finish. We also therefore use an absolute MIP gap,
-0248             %converted to a percentage using the last value of the objective function.
-0249             params.MIPGap = min(max(params.MIPGap, stp.AbsMIPGaps{rn}/abs(lastObjVal)),1);
-0250             params.seed = 1234;%use another seed, may work better
-0251 
-0252             if mipGap <= params.MIPGap
-0253                 success = true;
-0254                 break; %we're done - this will not happen the first time
-0255             else
-0256                 disp(['MipGap too high, trying with a different run. MipGap = ' num2str(mipGap) ' New MipGap Limit = ' num2str(params.MIPGap)])
-0257             end
-0258         end
-0259         
-0260         first = false;
-0261         
-0262         %now run the MILP
-0263         try
-0264             %The prodweight for metabolomics is currently set to 5 - 0.5 was default in the old version, which I deemed very small?
-0265             %There could be a need to specify this somewhere in the call at some point.
-0266             %This value has not been evaluated, but is assumed in the test cases - if changed, update the test case
-0267             startVals = [];
-0268             if ~isempty(fullMipRes)
-0269                 startVals = fullMipRes.full;
-0270             end
-0271             [deletedRxnsInINIT1, metProduction,fullMipRes,rxnsTurnedOn1,fluxes1] = ftINITInternalAlg(mm,rxnScores,metData,essentialRxns,5,stp.AllowMetSecr,stp.PosRevOff,params, startVals, fluxes, verbose);
-0272             %This is a bit tricky - since we reversed some reactions, those fluxes also need to be reversed
-0273             fluxes1(toRev) = -fluxes1(toRev);
-0274             
-0275             mipGap = fullMipRes.mipgap;
-0276             lastObjVal = fullMipRes.obj;
-0277         catch e
-0278             mipGap = Inf;
-0279             lastObjVal = Inf; %we need to set something here, Inf leads to that this doesn't come into play
-0280         end
-0281         
-0282         success = mipGap <= params.MIPGap;
-0283     end
-0284     
-0285     if ~success
-0286         dispEM(['Failed to find good enough solution within the time frame. MIPGap: ' num2str(mipGap)]);
-0287     end
-0288     
-0289     %save the reactions turned on and their fluxes for the next step
-0290     rxnsTurnedOn = rxnsTurnedOn | rxnsTurnedOn1.';
-0291     %The fluxes are a bit tricky - what if they change direction between the steps?
-0292     %The fluxes are used to determine the direction in which reactions are forced on
-0293     %(to simplify the problem it is good if they are unidirectional).
-0294     %We use the following strategy:
-0295     %1. Use the fluxes from the most recent step.
-0296     %2. If any flux is very low there (i.e. basically zero), use the flux from the previous steps
-0297     %This could in theory cause problems, but seems to work well practically
-0298     fluxesOld = fluxes;
-0299     fluxes = fluxes1;
-0300     %make sure that all reactions that are on actually has a flux - otherwise
-0301     %things could go bad, since the flux will be set to essential in a random direction
-0302     %This sometimes happens for rxns with negative score - let's just accept that.
-0303     %if (sum(abs(fluxes1) < 10^-7 & rxnsTurnedOn))
-0304     %    dispEM('There are rxns turned on without flux - this might cause problems');
-0305     %end
-0306     %fluxes(abs(fluxes1) < 10^-7) = fluxesOld(abs(fluxes1) < 10^-9);
-0307 end
-0308 
-0309 
-0310 %get the essential rxns
-0311 essential = ismember(prepData.minModel.rxns,prepData.essentialRxns);
-0312 %So, we only add reactions where the linearly merged scores are zero for all linearly dependent reactions
-0313 % (this cannot happen by chance, taken care of in the function groupRxnScores)
-0314 rxnsToIgn = rxnScores == 0; 
-0315 deletedRxnsInINITSel = ~(rxnsTurnedOn | rxnsToIgn | essential);
-0316 deletedRxnsInINIT = prepData.minModel.rxns(deletedRxnsInINITSel);
-0317 
-0318 %Here we need to figure out which original reactions (before the linear merge)
-0319 %that were removed. These are all reactions with the same group ids as the removed reactions
-0320 groupIdsRemoved = prepData.groupIds(ismember(prepData.refModel.rxns, deletedRxnsInINIT)); %can improve this slightly, use sel above
-0321 groupIdsRemoved = groupIdsRemoved(groupIdsRemoved ~= 0);%zero means that the reaction was not grouped, all with zeros are not a group!
-0322 rxnsToRem = union(prepData.refModel.rxns(ismember(prepData.groupIds,groupIdsRemoved)), deletedRxnsInINIT);%make a union here to include the ungrouped (unmerged) as well
-0323 
-0324 initModel = removeReactions(prepData.refModel,rxnsToRem,false,true);
-0325 
-0326 % remove metabolites separately to avoid removing those needed for tasks
-0327 unusedMets = initModel.mets(all(initModel.S == 0,2));
-0328 initModel = removeMets(initModel, setdiff(unusedMets, prepData.essentialMetsForTasks));
-0329 
-0330 %if printReport == true
-0331 %    printScores(initModel,'INIT model statistics',hpaData,transcrData,tissue,celltype);
-0332 %    printScores(removeReactions(cModel,setdiff(cModel.rxns,rxnsToRem),true,true),'Reactions deleted by INIT',hpaData,transcrData,tissue,celltype);
-0333 %end
-0334 
-0335 %The full model has exchange reactions in it. ftINITFillGapsForAllTasks calls
-0336 %ftINITFillGaps, which automatically removes exchange metabolites (because it
-0337 %assumes that the reactions are constrained when appropriate). In this case the
-0338 %uptakes/outputs are retrieved from the task sheet instead. To prevent
-0339 %exchange reactions being used to fill gaps, they are deleted from the
-0340 %reference model here.
-0341 initModel.id = 'INITModel';
-0342 
-0343 %If gaps in the model should be filled using a task list
-0344 if ~isempty(prepData.taskStruct)
-0345     %Remove exchange reactions and reactions already included in the INIT
-0346     %model
-0347     %We changed strategy and instead include all rxns except the exchange rxns in the ref model
-0348     %But we do keep the exchange rxns that are essential.
-0349     %Let's test to remove all, that should work
-0350     
-0351     %At this stage the model is fully connected and most of the genes with
-0352     %good scores should have been included. The final gap-filling should
-0353     %take the scores of the genes into account, so that "rather bad"
-0354     %reactions are preferred to "very bad" reactions. However, reactions
-0355     %with positive scores will be included even if they are not connected
-0356     %in the current formulation. Therefore, such reactions will have to be
-0357     %assigned a small negative score instead.
-0358     exchRxns = getExchangeRxns(prepData.refModel);
-0359     refModelNoExc = removeReactions(prepData.refModelWithBM,exchRxns,false,true);
-0360     exchRxns = getExchangeRxns(initModel);
-0361     initModelNoExc = removeReactions(closeModel(initModel),exchRxns,false,true);
-0362     
-0363     if useScoresForTasks == true
-0364         %map the rxn scores to the model without exchange rxns
-0365         [~,ia,ib] = intersect(refModelNoExc.rxns,prepData.refModel.rxns);
-0366         rxnScores2nd = NaN(length(refModelNoExc.rxns),1);
-0367         rxnScores2nd(ia) = origRxnScores(ib);
-0368         %all(rxnScores2nd == refRxnScores);%should be the same, ok!
-0369         [outModel,addedRxnMat] = ftINITFillGapsForAllTasks(initModelNoExc,refModelNoExc,[],true,min(rxnScores2nd,-0.1),prepData.taskStruct,paramsFT,verbose);
-0370     else
-0371         [outModel,addedRxnMat] = ftINITFillGapsForAllTasks(initModelNoExc,refModelNoExc,[],true,[],prepData.taskStruct,paramsFT,verbose);
-0372     end
-0373     %if printReport == true
-0374     %    printScores(outModel,'Functional model statistics',hpaData,transcrData,tissue,celltype);
-0375     %    printScores(removeReactions(outModel,intersect(outModel.rxns,initModel.rxns),true,true),'Reactions added to perform the tasks',hpaData,transcrData,tissue,celltype);
-0376     %end
-0377     
-0378     addedRxnsForTasks = refModelNoExc.rxns(any(addedRxnMat,2));
-0379 else
-0380     outModel = initModel;
-0381     addedRxnMat = [];
-0382     addedRxnsForTasks = {};
-0383 end
-0384 
-0385 % The model can now perform all the tasks defined in the task list.
-0386 model = outModel;
-0387 
-0388 
-0389 % At this stage the model will contain some exchange reactions but probably
-0390 % not all (and maybe zero). This can be inconvenient, so all exchange
-0391 % reactions from the reference model are added, except for those which
-0392 % involve metabolites that are not in the model.
-0393 
-0394 %Start from the original model, and just remove the reactions that are no longer there (and keep exchange rxns). The model we got out
-0395 %from the problem is not complete, it doesn't have GRPs etc.
-0396 %The logic below is a bit complicated. We identify the reactions that should be removed from the full model as
-0397 %reactions that have been removed in the init model except the ones that were added back. In addition, we make
-0398 %sure that no exchange rxns are removed - they can be removed in the init model if they were linearly merged with other
-0399 %reactions that were decided to be removed from the model. We want to keep all exchange rxns to make sure the tasks can
-0400 %be performed also without manipulating the b vector in the model (which is what is done in the gap-filling).
-0401 exchRxns = getExchangeRxns(prepData.refModel);
-0402 deletedRxnsInINIT = setdiff(prepData.refModel.rxns,union(union(initModel.rxns, addedRxnsForTasks), exchRxns));
-0403 outModel = removeReactions(prepData.refModel, deletedRxnsInINIT, true); %we skip removing the genes for now, I'm not sure it is desirable
-0404 
-0405 % If requested, attempt to remove negative-score genes from the model,
-0406 % depending on their role (isozyme or complex subunit) in each grRule.
-0407 % See the "removeLowScoreGenes" function more more details, and to adjust
-0408 % any default parameters therein.
-0409 if ( removeGenes )
-0410     [~, geneScores] = scoreComplexModel(outModel,hpaData,transcrData,tissue,celltype);
-0411     outModel = removeLowScoreGenes(outModel,geneScores);
-0412 end
-0413 
-0414 
-0415 model = outModel;
-0416 
-0417 end
-0418 
-0419 %This is for printing a summary of a model
-0420 function [rxnS, geneS] = printScores(model,name,hpaData,transcrData,tissue,celltype)
-0421     [a, b] = scoreComplexModel(model,hpaData,transcrData,tissue,celltype);
-0422     rxnS = mean(a);
-0423     geneS = mean(b,'omitnan');
-0424     fprintf([name ':\n']);
-0425     fprintf(['\t' num2str(numel(model.rxns)) ' reactions, ' num2str(numel(model.genes)) ' genes\n']);
-0426     fprintf(['\tMean reaction score: ' num2str(rxnS) '\n']);
-0427     fprintf(['\tMean gene score: ' num2str(geneS) '\n']);
-0428     fprintf(['\tReactions with positive scores: ' num2str(100*sum(a>0)/numel(a)) '%%\n\n']);
-0429 end
-0430 
-0431 function rxnsToIgnore = getRxnsFromPattern(rxnsToIgnorePattern, prepData)
-0432     rxnsToIgnore = false(length(prepData.toIgnoreExch),1);
-0433     if rxnsToIgnorePattern(1) rxnsToIgnore = rxnsToIgnore | prepData.toIgnoreExch; end;
-0434     if rxnsToIgnorePattern(2) rxnsToIgnore = rxnsToIgnore | prepData.toIgnoreImportRxns; end;
-0435     if rxnsToIgnorePattern(3) rxnsToIgnore = rxnsToIgnore | prepData.toIgnoreSimpleTransp; end;
-0436     if rxnsToIgnorePattern(4) rxnsToIgnore = rxnsToIgnore | prepData.toIgnoreAdvTransp; end;
-0437     if rxnsToIgnorePattern(5) rxnsToIgnore = rxnsToIgnore | prepData.toIgnoreSpont; end;
-0438     if rxnsToIgnorePattern(6) rxnsToIgnore = rxnsToIgnore | prepData.toIgnoreS; end;
-0439     if rxnsToIgnorePattern(7) rxnsToIgnore = rxnsToIgnore | prepData.toIgnoreCustomRxns; end;
-0440     if rxnsToIgnorePattern(8) rxnsToIgnore = rxnsToIgnore | prepData.toIgnoreAllWithoutGPRs; end;
-0441 end
-0442
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/INIT/ftINITFillGaps.html b/doc/INIT/ftINITFillGaps.html deleted file mode 100644 index 6a6661e79..000000000 --- a/doc/INIT/ftINITFillGaps.html +++ /dev/null @@ -1,207 +0,0 @@ - - - - Description of ftINITFillGaps - - - - - - - - - -
Home > INIT > ftINITFillGaps.m
- - - -

ftINITFillGaps -

- -

PURPOSE ^

-
ftINITFillGaps
- -

SYNOPSIS ^

-
function [addedRxns, newModel, exitFlag]=ftINITFillGaps(tModel, origModel, tRefModel,allowNetProduction,supressWarnings,rxnScores,params,verbose)
- -

DESCRIPTION ^

-
 ftINITFillGaps
-   Variant of fillGaps specially adapted to speed up generation of ftINIT models.
-
-   tModel              model that contains the task-specific rxns.
-   origModel           model without task-specific rxns.         
-   tRefModel           reference tModel - the full tModel, containing all rxns
-                       used for gap-filling of tModel + the task-specific rxns
-   allowNetProduction  true if net production of all metabolites is
-                       allowed. A reaction can be unable to carry flux because one of
-                       the reactants is unavailable or because one of the
-                       products can't be further processed. If this
-                       parameter is true, only the first type of
-                       unconnectivity is considered (optional, default false)
-   useModelConstraints true if the constraints specified in the tModel
-                       structure should be used. If false then reactions
-                       included from the template tModel(s) so that as many
-                       reactions as possible in tModel can carry flux
-                       (optional, default false)
-   supressWarnings     false if warnings should be displayed (optional, default
-                       false)
-   rxnScores           scores for each of the reactions in the
-                       reference tModel. 
-                       The solver will try to maximize the sum of the
-                       scores for the included reactions
-   params              *obsolete option*
-   verbose             if true, the MILP progression will be shown. 
-
-   addedRxns           the rxns added
-   newModel            the tModel with reactions added to fill gaps
-   exitFlag            1: optimal solution found
-                      -1: no feasible solution found
-                      -2: optimization time out
-
-   This method works by merging the tModel to the reference model and
-   checking which reactions can carry flux. All reactions that can't
-   carry flux are removed.
-   If useModelConstraints is false it then solves the MILP problem of
-   minimizing the number of active reactions from the reference model
-   that are required to have flux in all the reactions in model. This
-   requires that the input tModel has exchange reactions present for the
-   nutrients that are needed for its metabolism. If useModelConstraints is
-   true then the problem is to include as few reactions as possible from
-   the reference models in order to satisfy the tModel constraints.
-   The intended use is that the user can attempt a general gap-filling using
-   useModelConstraint=false or a more targeted gap-filling by setting
-   constraints in the model structure and then use
-   useModelConstraints=true. Say that the user want to include reactions
-   so that all biomass components can be synthesized. He/she could then
-   define a biomass equation and set the lower bound to >0. Running this
-   function with useModelConstraints=true would then give the smallest set
-   of reactions that have to be included in order for the tModel to produce
-   biomass.
-
- Usage: [newModel, exitFlag]=...
-           fillGaps(tModel,models,allowNetProduction,...
-           supressWarnings,rxnScores,params)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function [addedRxns, newModel, exitFlag]=ftINITFillGaps(tModel, origModel, tRefModel,allowNetProduction,supressWarnings,rxnScores,params,verbose)
-0002 % ftINITFillGaps
-0003 %   Variant of fillGaps specially adapted to speed up generation of ftINIT models.
-0004 %
-0005 %   tModel              model that contains the task-specific rxns.
-0006 %   origModel           model without task-specific rxns.
-0007 %   tRefModel           reference tModel - the full tModel, containing all rxns
-0008 %                       used for gap-filling of tModel + the task-specific rxns
-0009 %   allowNetProduction  true if net production of all metabolites is
-0010 %                       allowed. A reaction can be unable to carry flux because one of
-0011 %                       the reactants is unavailable or because one of the
-0012 %                       products can't be further processed. If this
-0013 %                       parameter is true, only the first type of
-0014 %                       unconnectivity is considered (optional, default false)
-0015 %   useModelConstraints true if the constraints specified in the tModel
-0016 %                       structure should be used. If false then reactions
-0017 %                       included from the template tModel(s) so that as many
-0018 %                       reactions as possible in tModel can carry flux
-0019 %                       (optional, default false)
-0020 %   supressWarnings     false if warnings should be displayed (optional, default
-0021 %                       false)
-0022 %   rxnScores           scores for each of the reactions in the
-0023 %                       reference tModel.
-0024 %                       The solver will try to maximize the sum of the
-0025 %                       scores for the included reactions
-0026 %   params              *obsolete option*
-0027 %   verbose             if true, the MILP progression will be shown.
-0028 %
-0029 %   addedRxns           the rxns added
-0030 %   newModel            the tModel with reactions added to fill gaps
-0031 %   exitFlag            1: optimal solution found
-0032 %                      -1: no feasible solution found
-0033 %                      -2: optimization time out
-0034 %
-0035 %   This method works by merging the tModel to the reference model and
-0036 %   checking which reactions can carry flux. All reactions that can't
-0037 %   carry flux are removed.
-0038 %   If useModelConstraints is false it then solves the MILP problem of
-0039 %   minimizing the number of active reactions from the reference model
-0040 %   that are required to have flux in all the reactions in model. This
-0041 %   requires that the input tModel has exchange reactions present for the
-0042 %   nutrients that are needed for its metabolism. If useModelConstraints is
-0043 %   true then the problem is to include as few reactions as possible from
-0044 %   the reference models in order to satisfy the tModel constraints.
-0045 %   The intended use is that the user can attempt a general gap-filling using
-0046 %   useModelConstraint=false or a more targeted gap-filling by setting
-0047 %   constraints in the model structure and then use
-0048 %   useModelConstraints=true. Say that the user want to include reactions
-0049 %   so that all biomass components can be synthesized. He/she could then
-0050 %   define a biomass equation and set the lower bound to >0. Running this
-0051 %   function with useModelConstraints=true would then give the smallest set
-0052 %   of reactions that have to be included in order for the tModel to produce
-0053 %   biomass.
-0054 %
-0055 % Usage: [newModel, exitFlag]=...
-0056 %           fillGaps(tModel,models,allowNetProduction,...
-0057 %           supressWarnings,rxnScores,params)
-0058 
-0059 if isempty(rxnScores)
-0060     rxnScores=cell(numel(models),1);
-0061     for i=1:numel(models)
-0062         rxnScores{i}=ones(numel(models{i}.rxns),1)*-1;
-0063     end
-0064 end
-0065 
-0066 %Simplify the template models to remove constrained rxns. At the same time,
-0067 %check that the id of the template models isn't the same as the tModel. That
-0068 %would cause an error further down
-0069 tRefModel.rxnScores=rxnScores;
-0070 tRefModel=simplifyModel(tRefModel,false,false,true);
-0071 
-0072 %This is a rather ugly solution to the issue that it's a bit tricky to keep
-0073 %track of which scores belong to which reactions. This requires that
-0074 %removeReactions and mergeModels are modified to check for the new field.
-0075 tModel.rxnScores=zeros(numel(tModel.rxns),1);
-0076 
-0077 %First merge all models into one big one
-0078 fullModel = tRefModel;%mergeModels([{tModel};models],'metNames',true);
-0079 
-0080 %Add that net production is ok
-0081 if allowNetProduction==true
-0082     %A second column in tModel.b means that the b field is lower and upper
-0083     %bound on the RHS.
-0084     tModel.b=[tModel.b(:,1) inf(numel(tModel.mets),1)];
-0085     fullModel.b=[fullModel.b(:,1) inf(numel(fullModel.mets),1)];
-0086 end
-0087 
-0088 
-0089 fullModel.c(:)=0;
-0090 
-0091 %Then minimize for the number of fluxes used. The fixed rxns doesn't need
-0092 %to participate
-0093 templateRxns = find(~ismember(fullModel.rxns, tModel.rxns)); %Check if this is slow, in that case keep track of this in fitTasksOpt and send it in
-0094 
-0095 [~, J, exitFlag]=ftINITFillGapsMILP(fullModel,templateRxns,params,fullModel.rxnScores(templateRxns),verbose);%only the scores from the template rxns are used, so the others doesn't matter
-0096 
-0097 %Remove everything except for the added ones
-0098 addedRxns = fullModel.rxns(templateRxns(J));
-0099 rxnsToAdd.rxns = addedRxns;
-0100 rxnsToAdd.equations = constructEquations(fullModel, addedRxns);
-0101 rxnsToAdd.ub = fullModel.ub(templateRxns(J));
-0102 rxnsToAdd.lb = fullModel.lb(templateRxns(J));
-0103 newModel = addRxns(origModel,rxnsToAdd, 3, [], true); %we ignore gene rules etc here, they are not needed - we regenerate the model in the end by subtracting rxns from the full model.
-0104 
-0105 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/INIT/ftINITFillGapsForAllTasks.html b/doc/INIT/ftINITFillGapsForAllTasks.html deleted file mode 100644 index ae7fdaf2f..000000000 --- a/doc/INIT/ftINITFillGapsForAllTasks.html +++ /dev/null @@ -1,462 +0,0 @@ - - - - Description of ftINITFillGapsForAllTasks - - - - - - - - - -
Home > INIT > ftINITFillGapsForAllTasks.m
- - - -

ftINITFillGapsForAllTasks -

- -

PURPOSE ^

-
ftINITFillGapsForAllTasks
- -

SYNOPSIS ^

-
function [outModel, addedRxns]=ftINITFillGapsForAllTasks(model,refModel,inputFile,printOutput,rxnScores,taskStructure,params,verbose)
- -

DESCRIPTION ^

-
 ftINITFillGapsForAllTasks
-   Fills gaps in a model by including reactions from a reference model,
-   so that the resulting model can perform all the tasks in a task list
-   This is similar to the old fitTasks function but optimized for ftINIT.
-
-   Input:
-   model           model structure
-   refModel        reference model from which to include reactions
-   inputFile       a task list in Excel format. See the function
-                   parseTaskList for details (optional if taskStructure is
-                   supplied)
-   printOutput     true if the results of the test should be displayed
-                   (optional, default true)
-   rxnScores       scores for each of the reactions in the reference
-                   model. Only negative scores are allowed. The solver will
-                   try to maximize the sum of the scores for the included
-                   reactions (optional, default is -1 for all reactions)
-   taskStructure   structure with the tasks, as from parseTaskList. If
-                   this is supplied then inputFile is ignored
-   params          *obsolete option*
-   verbose         if true, the MILP progression will be shown. 
-
-
-   Output:
-   outModel        model structure with reactions added to perform the
-                   tasks
-   addedRxns       MxN matrix with the added reactions (M) from refModel
-                   for each task (N). An element is true if the corresponding
-                   reaction is added in the corresponding task.
-                   Failed tasks and SHOULD FAIL tasks are ignored
-
-   This function fills gaps in a model by using a reference model, so
-   that the resulting model can perform a list of metabolic tasks. The
-   gap-filling is done in a task-by-task manner, rather than solving for
-   all tasks at once. This means that the order of the tasks could influence
-   the result.
-
- Usage: [outModel, addedRxns]=fitTasks(model,refModel,inputFile,printOutput,...
-           rxnScores,taskStructure,params)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function [outModel, addedRxns]=ftINITFillGapsForAllTasks(model,refModel,inputFile,printOutput,rxnScores,taskStructure,params,verbose)
-0002 % ftINITFillGapsForAllTasks
-0003 %   Fills gaps in a model by including reactions from a reference model,
-0004 %   so that the resulting model can perform all the tasks in a task list
-0005 %   This is similar to the old fitTasks function but optimized for ftINIT.
-0006 %
-0007 %   Input:
-0008 %   model           model structure
-0009 %   refModel        reference model from which to include reactions
-0010 %   inputFile       a task list in Excel format. See the function
-0011 %                   parseTaskList for details (optional if taskStructure is
-0012 %                   supplied)
-0013 %   printOutput     true if the results of the test should be displayed
-0014 %                   (optional, default true)
-0015 %   rxnScores       scores for each of the reactions in the reference
-0016 %                   model. Only negative scores are allowed. The solver will
-0017 %                   try to maximize the sum of the scores for the included
-0018 %                   reactions (optional, default is -1 for all reactions)
-0019 %   taskStructure   structure with the tasks, as from parseTaskList. If
-0020 %                   this is supplied then inputFile is ignored
-0021 %   params          *obsolete option*
-0022 %   verbose         if true, the MILP progression will be shown.
-0023 %
-0024 %
-0025 %   Output:
-0026 %   outModel        model structure with reactions added to perform the
-0027 %                   tasks
-0028 %   addedRxns       MxN matrix with the added reactions (M) from refModel
-0029 %                   for each task (N). An element is true if the corresponding
-0030 %                   reaction is added in the corresponding task.
-0031 %                   Failed tasks and SHOULD FAIL tasks are ignored
-0032 %
-0033 %   This function fills gaps in a model by using a reference model, so
-0034 %   that the resulting model can perform a list of metabolic tasks. The
-0035 %   gap-filling is done in a task-by-task manner, rather than solving for
-0036 %   all tasks at once. This means that the order of the tasks could influence
-0037 %   the result.
-0038 %
-0039 % Usage: [outModel, addedRxns]=fitTasks(model,refModel,inputFile,printOutput,...
-0040 %           rxnScores,taskStructure,params)
-0041 
-0042 if isempty(rxnScores)
-0043     rxnScores=ones(numel(refModel.rxns),1)*-1;
-0044 end
-0045 
-0046 if isempty(taskStructure) && ~isfile(inputFile)
-0047     error('Task file %s cannot be found',string(inputFile));
-0048 end
-0049 
-0050 if strcmpi(model.id,refModel.id)
-0051     fprintf('NOTE: The model and reference model have the same IDs. The ID for the reference model was set to "refModel" in order to keep track of the origin of reactions.\n');
-0052     refModel.id='refModel';
-0053 end
-0054 
-0055 if any(rxnScores>=0)
-0056     EM='Only negative values are allowed in rxnScores';
-0057     dispEM(EM);
-0058 end
-0059 
-0060 %Prepare the input models a little
-0061 model.b=zeros(numel(model.mets),2);
-0062 modelMets=upper(strcat(model.metNames,'[',model.comps(model.metComps),']'));
-0063 %This is the mets in the reference model. Used if the tasks involve
-0064 %metabolites that doesn't exist in the model
-0065 largeModelMets=upper(strcat(refModel.metNames,'[',refModel.comps(refModel.metComps),']'));
-0066 
-0067 if ~isfield(model,'unconstrained')
-0068     EM='Exchange metabolites should normally not be removed from the model when using checkTasks. Inputs and outputs are defined in the task file instead. Use importModel(file,false) to import a model with exchange metabolites remaining';
-0069     dispEM(EM,false);
-0070 end
-0071 
-0072 if isempty(taskStructure)
-0073     taskStructure=parseTaskList(inputFile);
-0074 end
-0075 
-0076 tModel=model;
-0077 addedRxns=false(numel(refModel.rxns),numel(taskStructure));
-0078 supressWarnings=false;
-0079 nAdded=0;
-0080 
-0081 for i=1:numel(taskStructure)
-0082     if ~taskStructure(i).shouldFail
-0083         
-0084         tRefModel = refModel;%we need to add stuff to this one as well...
-0085         tRxnScores = rxnScores;%these need to be extended (with zeros) when rxns are added in tasks
-0086         %Set the inputs
-0087         if ~isempty(taskStructure(i).inputs)
-0088             [I, J]=ismember(upper(taskStructure(i).inputs),modelMets);
-0089             [I2, J2]=ismember(upper(taskStructure(i).inputs),largeModelMets);
-0090             K=ismember(upper(taskStructure(i).inputs),'ALLMETS');
-0091             L=~cellfun('isempty',strfind(upper(taskStructure(i).inputs),'ALLMETSIN'));
-0092             %Check that all metabolites are either real metabolites or
-0093             %ALLMETS/ALLMETSIN
-0094             goodMets=I|K|L;
-0095             if ~all(goodMets)
-0096                 %Not all of the inputs could be found in the small model.
-0097                 %Check if they exist in the large model
-0098                 [found, metMatch]=ismember(upper(taskStructure(i).inputs(~goodMets)),largeModelMets);
-0099                 if ~all(found)
-0100                     EM=['Could not find all inputs in "[' taskStructure(i).id '] ' taskStructure(i).description '" in either model'];
-0101                     disp(EM);
-0102                 else
-0103                     %Otherwise add them to the model
-0104                     met.metNames=refModel.metNames(metMatch);
-0105                     met.compartments=refModel.comps(refModel.metComps(metMatch));
-0106                     
-0107                     %Add the metabolite both to the base model and the
-0108                     %model used in the current task
-0109                     model=addMets(model,met);
-0110                     tModel=addMets(tModel,met);
-0111                     modelMets=[modelMets;upper(taskStructure(i).inputs(~goodMets))];
-0112                 end
-0113                 
-0114                 %By now the indexes might be getting a bit confusing, but
-0115                 %this is to update the indexes of the "real" metabolites to
-0116                 %point to the newly added ones
-0117                 I(~goodMets)=true; %All the bad ones are fixed at this stage
-0118                 J(~goodMets)=numel(modelMets)-numel(metMatch)+1:numel(modelMets);
-0119             end
-0120             if numel(J(I))~=numel(unique(J(I)))
-0121                 EM=['The constraints on some input(s) in "[' taskStructure(i).id '] ' taskStructure(i).description '" are defined more than one time'];
-0122                 dispEM(EM);
-0123             end
-0124             %If all metabolites should be added
-0125             if any(K)
-0126                 %Check if ALLMETS is the first metabolite. Otherwise print
-0127                 %a warning since it will write over any other constraints
-0128                 %that are set
-0129                 if K(1)==0
-0130                     EM=['ALLMETS is used as an input in "[' taskStructure(i).id '] ' taskStructure(i).description '" but it it not the first metabolite in the list. Constraints defined for the metabolites before it will be over-written'];
-0131                     dispEM(EM,false);
-0132                 end
-0133                 %Use the first match of ALLMETS. There should only be one,
-0134                 %but still..
-0135                 tModel.b(:,1)=taskStructure(i).UBin(find(K,1))*-1;
-0136                 tRefModel.b(:,1)=taskStructure(i).UBin(find(K,1))*-1;
-0137             end
-0138             %If metabolites in a specific compartment should be used
-0139             if any(L)
-0140                 L=find(L);
-0141                 for j=1:numel(L)
-0142                     %The compartment defined
-0143                     compartment=upper(taskStructure(i).inputs{L(j)}(11:end-1));
-0144                     %Check if it exists in the model
-0145                     C=find(ismember(upper(model.comps),compartment));
-0146                     if any(C)
-0147                         %Match to metabolites
-0148                         tModel.b(model.metComps==C,1)=taskStructure(i).UBin(L(j))*-1;
-0149                     else
-0150                         EM=['The compartment defined for ALLMETSIN in "[' taskStructure(i).id '] ' taskStructure(i).description '" does not exist'];
-0151                         dispEM(EM);
-0152                     end
-0153                     %also need to do this for the t ref model
-0154                     C=find(ismember(upper(tRefModel.comps),compartment));
-0155                     if any(C)
-0156                         %Match to metabolites
-0157                         tRefModel.b(tRefModel.metComps==C,1)=taskStructure(i).UBin(L(j))*-1;
-0158                     else
-0159                         EM=['The compartment defined for ALLMETSIN in "[' taskStructure(i).id '] ' taskStructure(i).description '" does not exist'];
-0160                         dispEM(EM);
-0161                     end
-0162                 end
-0163             end
-0164             %Then add the normal constraints
-0165             if any(J(I))
-0166                 tModel.b(J(I),1)=taskStructure(i).UBin(I)*-1;
-0167                 tModel.b(J(I),2)=taskStructure(i).LBin(I)*-1;
-0168             end
-0169             %for the tRefModel as well
-0170             if any(J2(I2))
-0171                 tRefModel.b(J2(I2),1)=taskStructure(i).UBin(I2)*-1;
-0172                 tRefModel.b(J2(I2),2)=taskStructure(i).LBin(I2)*-1;
-0173             end
-0174         end
-0175         %Set the outputs
-0176         if ~isempty(taskStructure(i).outputs)
-0177             [I, J]=ismember(upper(taskStructure(i).outputs),modelMets);
-0178             [I2, J2]=ismember(upper(taskStructure(i).outputs),largeModelMets);
-0179             K=ismember(upper(taskStructure(i).outputs),'ALLMETS');
-0180             L=~cellfun('isempty',strfind(upper(taskStructure(i).outputs),'ALLMETSIN'));
-0181             %Check that all metabolites are either real metabolites or
-0182             %ALLMETS/ALLMETSIN
-0183             goodMets=I|K|L;
-0184             if ~all(goodMets)
-0185                 %Not all of the outputs could be found in the small model.
-0186                 %Check if they exist in the large model
-0187                 [found, metMatch]=ismember(upper(taskStructure(i).outputs(~goodMets)),largeModelMets);
-0188                 if ~all(found)
-0189                     EM=['Could not find all outputs in "[' taskStructure(i).id '] ' taskStructure(i).description '" in either model'];
-0190                     dispEM(EM);
-0191                 else
-0192                     %Otherwise add them to the model
-0193                     met.metNames=refModel.metNames(metMatch);
-0194                     met.compartments=refModel.comps(refModel.metComps(metMatch));
-0195                     
-0196                     %Add the metabolite both to the base model and the
-0197                     %model used in the current task
-0198                     model=addMets(model,met);
-0199                     tModel=addMets(tModel,met);
-0200                     modelMets=[modelMets;upper(taskStructure(i).outputs(~goodMets))];
-0201                 end
-0202                 
-0203                 %By now the indexes might be getting a bit confusing, but
-0204                 %this is to update the indexes of the "real" metabolites to
-0205                 %point to the newly added ones
-0206                 I(~goodMets)=true; %All the bad ones are fixed at this stage
-0207                 J(~goodMets)=numel(modelMets)-numel(metMatch)+1:numel(modelMets);
-0208             end
-0209             if numel(J(I))~=numel(unique(J(I)))
-0210                 EM=['The constraints on some output(s) in "[' taskStructure(i).id '] ' taskStructure(i).description '" are defined more than one time'];
-0211                 dispEM(EM);
-0212             end
-0213             %If all metabolites should be added
-0214             if any(K)
-0215                 %Check if ALLMETS is the first metabolite. Otherwise print
-0216                 %a warning since it will write over any other constraints
-0217                 %that are set
-0218                 if K(1)==0
-0219                     EM=['ALLMETS is used as an output in "[' taskStructure(i).id '] ' taskStructure(i).description '" but it it not the first metabolite in the list. Constraints defined for the metabolites before it will be over-written'];
-0220                     dispEM(EM,false);
-0221                 end
-0222                 %Use the first match of ALLMETS. There should only be one,
-0223                 %but still..
-0224                 tModel.b(:,2)=taskStructure(i).UBout(find(K,1));
-0225                 tRefModel.b(:,2)=taskStructure(i).UBout(find(K,1));
-0226             end
-0227             %If metabolites in a specific compartment should be used
-0228             if any(L)
-0229                 L=find(L);
-0230                 for j=1:numel(L)
-0231                     %The compartment defined
-0232                     compartment=upper(taskStructure(i).outputs{L(j)}(11:end-1));
-0233                     %Check if it exists in the model
-0234                     C=find(ismember(upper(model.comps),compartment));
-0235                     if any(C)
-0236                         %Match to metabolites
-0237                         tModel.b(model.metComps==C,2)=taskStructure(i).UBout(L(j));
-0238                     else
-0239                         EM=['The compartment defined for ALLMETSIN in "[' taskStructure(i).id '] ' taskStructure(i).description '" does not exist'];
-0240                         dispEM(EM);
-0241                     end
-0242                     %for the tRefModel as well
-0243                     C=find(ismember(upper(tRefModel.comps),compartment));
-0244                     if any(C)
-0245                         %Match to metabolites
-0246                         tRefModel.b(tRefModel.metComps==C,2)=taskStructure(i).UBout(L(j));
-0247                     else
-0248                         EM=['The compartment defined for ALLMETSIN in "[' taskStructure(i).id '] ' taskStructure(i).description '" does not exist'];
-0249                         dispEM(EM);
-0250                     end
-0251                 end
-0252             end
-0253             %Then add the normal constraints
-0254             if any(J(I))
-0255                 %Verify that IN and OUT bounds are consistent. Cannot require
-0256                 %that a metabolite is simultaneously input AND output at some
-0257                 %nonzero flux.
-0258                 J = J(I);
-0259                 I = find(I);  % otherwise indexing becomes confusing
-0260                 nonzero_LBin = tModel.b(J,2) < 0;
-0261                 nonzero_LBout = taskStructure(i).LBout(I) > 0;
-0262                 if any(nonzero_LBin & nonzero_LBout)
-0263                     EM=['The IN LB and OUT LB in "[' taskStructure(i).id '] ' taskStructure(i).description '" cannot be nonzero for the same metabolite'];
-0264                     dispEM(EM);
-0265                 end
-0266                 tModel.b(J(nonzero_LBout),1)=taskStructure(i).LBout(I(nonzero_LBout));
-0267                 tModel.b(J,2)=taskStructure(i).UBout(I);
-0268             end
-0269             %and for the ref model
-0270             if any(J2(I2))
-0271                 %Verify that IN and OUT bounds are consistent. Cannot require
-0272                 %that a metabolite is simultaneously input AND output at some
-0273                 %nonzero flux.
-0274                 J2 = J2(I2);
-0275                 I2 = find(I2);  % otherwise indexing becomes confusing
-0276                 nonzero_LBin = tRefModel.b(J2,2) < 0;
-0277                 nonzero_LBout = taskStructure(i).LBout(I2) > 0;
-0278                 if any(nonzero_LBin & nonzero_LBout)
-0279                     EM=['The IN LB and OUT LB in "[' taskStructure(i).id '] ' taskStructure(i).description '" cannot be nonzero for the same metabolite'];
-0280                     dispEM(EM);
-0281                 end
-0282                 tRefModel.b(J2(nonzero_LBout),1)=taskStructure(i).LBout(I2(nonzero_LBout));
-0283                 tRefModel.b(J2,2)=taskStructure(i).UBout(I2);
-0284             end
-0285         end
-0286         
-0287         %Add new rxns
-0288         if ~isempty(taskStructure(i).equations)
-0289             rxn.equations=taskStructure(i).equations;
-0290             rxn.lb=taskStructure(i).LBequ;
-0291             rxn.ub=taskStructure(i).UBequ;
-0292             rxn.rxns=strcat({'TEMPORARY_'},num2str((1:numel(taskStructure(i).equations))'));
-0293             tModel=addRxns(tModel,rxn,3);
-0294             tRefModel=addRxns(tRefModel,rxn,3);
-0295             tRxnScores = [tRxnScores;zeros(length(rxn.lb),1)];
-0296         end
-0297         %Add changed bounds
-0298         if ~isempty(taskStructure(i).changed)
-0299             tModel=setParam(tModel,'lb',taskStructure(i).changed,taskStructure(i).LBrxn);
-0300             tModel=setParam(tModel,'ub',taskStructure(i).changed,taskStructure(i).UBrxn);
-0301             tRefModel=setParam(tRefModel,'lb',taskStructure(i).changed,taskStructure(i).LBrxn);
-0302             tRefModel=setParam(tRefModel,'ub',taskStructure(i).changed,taskStructure(i).UBrxn);
-0303         end
-0304         
-0305         %Solve and print. Display a warning if the problem is not solveable
-0306         sol=solveLP(tModel);
-0307         if isempty(sol.x)
-0308             %Only do gap-filling if it cannot be solved
-0309             failed=false;
-0310             try
-0311                 [newRxns, newModel, exitFlag]=ftINITFillGaps(tModel,model,tRefModel,false,supressWarnings,tRxnScores,params,verbose);
-0312                 if exitFlag==-2
-0313                     EM=['"[' taskStructure(i).id '] ' taskStructure(i).description '" was aborted before reaching optimality. Consider increasing params.maxTime\n'];
-0314                     dispEM(EM,false);
-0315                 end
-0316             catch e
-0317                 EM=['"[' taskStructure(i).id '] ' taskStructure(i).description '" could not be performed for any set of reactions\n'];
-0318                 dispEM(EM,false);
-0319                 failed=true;
-0320             end
-0321             if failed==false
-0322                 if ~isempty(newRxns)
-0323                     nAdded=nAdded+numel(newRxns);
-0324                     
-0325                     disp(['task: ' num2str(i)])
-0326                     for iii = 1:numel(newRxns)
-0327                         disp(newRxns{iii})
-0328                     end
-0329                     
-0330                     %Add the reactions to the base model. It is not correct
-0331                     %to use newModel directly, as it may contain
-0332                     %reactions/constraints that are specific to this task
-0333                     %model=mergeModels({model,removeReactions(newModel,setdiff(newModel.rxns,newRxns),true,true)},'metNames',true);
-0334                     model = newModel;
-0335                     
-0336                     %Keep track of the added reactions
-0337                     addedRxns(ismember(refModel.rxns,newRxns),i)=true;
-0338                 end
-0339                 if printOutput==true
-0340                     fprintf(['[' taskStructure(i).id '] ' taskStructure(i).description ': Added ' num2str(numel(newRxns)) ' reaction(s), ' num2str(nAdded) ' reactions added in total\n']);
-0341                 end
-0342             end
-0343         else
-0344             if printOutput==true
-0345                 fprintf(['[' taskStructure(i).id '] ' taskStructure(i).description ': Added 0 reaction(s), ' num2str(nAdded) ' reactions added in total\n']);
-0346             end
-0347         end
-0348         supressWarnings=true;
-0349         
-0350         %Print the output if chosen
-0351         if taskStructure(i).printFluxes && printOutput
-0352             if ~isempty(sol.x)
-0353                 sol=solveLP(tModel,1);
-0354                 printFluxes(tModel,sol.x,false,10^-5,[],'%rxnID (%eqn):%flux\n');
-0355                 fprintf('\n');
-0356             else
-0357                 %If the problem wasn't solveable then the gap-filled model
-0358                 %should be used
-0359                 if failed==false
-0360                     sol=solveLP(newModel,1);
-0361                     printFluxes(newModel,sol.x,false,10^-5,[],'%rxnID (%eqn):%flux\n');
-0362                     fprintf('\n');
-0363                 end
-0364             end
-0365         end
-0366         
-0367         tModel=model;
-0368         %Since new mets are added by merging the new reactions and not only
-0369         %from the task sheet
-0370         modelMets=upper(strcat(model.metNames,'[',model.comps(model.metComps),']'));
-0371     else
-0372         EM=['"[' taskStructure(i).id '] ' taskStructure(i).description '" is set as SHOULD FAIL. Such tasks cannot be modelled using this approach and the task is therefore ignored\n'];
-0373         dispEM(EM,false);
-0374     end
-0375 end
-0376 outModel=model;
-0377 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/INIT/ftINITFillGapsMILP.html b/doc/INIT/ftINITFillGapsMILP.html deleted file mode 100644 index 888479a1e..000000000 --- a/doc/INIT/ftINITFillGapsMILP.html +++ /dev/null @@ -1,312 +0,0 @@ - - - - Description of ftINITFillGapsMILP - - - - - - - - - -
Home > INIT > ftINITFillGapsMILP.m
- - - -

ftINITFillGapsMILP -

- -

PURPOSE ^

-
ftINITFillGapsMILP
- -

SYNOPSIS ^

-
function [x,I,exitFlag]=ftINITFillGapsMILP(model, toMinimize, params, scores, verbose)
- -

DESCRIPTION ^

-
 ftINITFillGapsMILP
-   Returns the minimal set of fluxes that satisfy the model using
-   mixed integer linear programming. This is an optimized variant of the
-   old function "getMinNrFluxes" that is adapted to ftINIT.
-   It does not need to make an irrev model, which takes time. The problem 
-   also becomes smaller (fewer integers but larger matrix). Only tested with 
-   Gurobi.
-
-    model         a model structure
-   toMinimize    either a cell array of reaction IDs, a logical vector
-                 with the same number of elements as reactions in the model,
-                 of a vector of indexes for the reactions that should be
-                 minimized (optional, default model.rxns)
-   params        *obsolete option*
-   scores        vector of weights for the reactions. Negative scores
-                 should not have flux. Positive scores are not possible in this
-                 implementation, and they are changed to max(scores(scores<0)).
-                 Must have the same dimension as toMinimize (find(toMinimize)
-                 if it is a logical vector) (optional, default -1 for all reactions)
-   verbose       if true, the MILP progression will be shown. 
-
-   x             the corresponding fluxes for the full model
-   I             the indexes of the reactions in toMinimize that were used
-                 in the solution
-   exitFlag      1: optimal solution found
-                -1: no feasible solution found
-                -2: optimization time out
-
-   NOTE: Uses 1000 mmol/gDW/h as an arbitary large flux. Could possibly
-   cause problems if the fluxes in the model are larger than that.
-
- Usage: [x,I,exitFlag]=getMinNrFluxes(model, toMinimize, params, scores)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function [x,I,exitFlag]=ftINITFillGapsMILP(model, toMinimize, params, scores, verbose)
-0002 % ftINITFillGapsMILP
-0003 %   Returns the minimal set of fluxes that satisfy the model using
-0004 %   mixed integer linear programming. This is an optimized variant of the
-0005 %   old function "getMinNrFluxes" that is adapted to ftINIT.
-0006 %   It does not need to make an irrev model, which takes time. The problem
-0007 %   also becomes smaller (fewer integers but larger matrix). Only tested with
-0008 %   Gurobi.
-0009 %
-0010 %    model         a model structure
-0011 %   toMinimize    either a cell array of reaction IDs, a logical vector
-0012 %                 with the same number of elements as reactions in the model,
-0013 %                 of a vector of indexes for the reactions that should be
-0014 %                 minimized (optional, default model.rxns)
-0015 %   params        *obsolete option*
-0016 %   scores        vector of weights for the reactions. Negative scores
-0017 %                 should not have flux. Positive scores are not possible in this
-0018 %                 implementation, and they are changed to max(scores(scores<0)).
-0019 %                 Must have the same dimension as toMinimize (find(toMinimize)
-0020 %                 if it is a logical vector) (optional, default -1 for all reactions)
-0021 %   verbose       if true, the MILP progression will be shown.
-0022 %
-0023 %   x             the corresponding fluxes for the full model
-0024 %   I             the indexes of the reactions in toMinimize that were used
-0025 %                 in the solution
-0026 %   exitFlag      1: optimal solution found
-0027 %                -1: no feasible solution found
-0028 %                -2: optimization time out
-0029 %
-0030 %   NOTE: Uses 1000 mmol/gDW/h as an arbitary large flux. Could possibly
-0031 %   cause problems if the fluxes in the model are larger than that.
-0032 %
-0033 % Usage: [x,I,exitFlag]=getMinNrFluxes(model, toMinimize, params, scores)
-0034 
-0035 % glpk solver as implemented by COBRA does not work well for MILP.
-0036 global CBT_MILP_SOLVER
-0037 if strcmp(getpref('RAVEN','solver'),'cobra') && strcmp(CBT_MILP_SOLVER,'glpk')
-0038     dispEM('The current solver is set to ''cobra'', while in COBRA the MILP solver has been set to ''glpk''. The COBRA implementation of glpk is not well suitable for solving MILPs. Please install the Gurobi or an alternative MILP solver.',true);
-0039 end
-0040 
-0041 exitFlag=1;
-0042 
-0043 if nargin<2
-0044     toMinimize=model.rxns;
-0045 else
-0046     if ~iscell(toMinimize)
-0047         toMinimize=model.rxns(toMinimize);
-0048     end
-0049 end
-0050 
-0051 %For passing parameters to the solver
-0052 if nargin<3
-0053     params=struct();
-0054 end
-0055 
-0056 if nargin<4
-0057     %It says that the default is -1, but that is to fit with other code
-0058     scores=ones(numel(toMinimize),1)*1;
-0059 else
-0060     if numel(scores)~=numel(toMinimize)
-0061         EM='The number of scores must be the same as the number of reactions to minimize';
-0062         dispEM(EM);
-0063     end
-0064     
-0065     %Change positive scores to have a small negative weight. This is a
-0066     %temporary solution.
-0067     scores(scores>=0)=max(scores(scores<0));
-0068     
-0069     %It says that the default is -1, but that is to fit with other code
-0070     scores=scores*-1;
-0071 end
-0072 
-0073 %The trick to make this possible using a reversible model is that for
-0074 %reversible reactions, we do the following. Set the flux Vi == Vipos - Vineg.
-0075 %What happens then is that if the flux is positive, Vipos will have a nonzero value,
-0076 %and when the flux is negative, Vineg will have a positive value. In addition
-0077 %we can add an arbitrary constant to both Vipos and Vineg. For example, if the
-0078 %flux Vi is -1, Vineg can be 4 and Vipos 3. This is however not a problem,
-0079 %because we can be sure that Vineg + Vipos >= abs(Vi). Since we are interested
-0080 %in forcing the ints to be on when there is a flux, it doesn't matter if we overestimate
-0081 %the flux! So, we can simply constrain the boolean Yi to Yi*Maxflux >= Vineg + Vipos.
-0082 
-0083 %The matrix then becomes as this:
-0084 %         S       p n int b     var
-0085 %         SSSSSSSS        -
-0086 %         SSSSSSSS         -
-0087 %         SSSSSSSS          -
-0088 %         SSSSSSSS           -
-0089 %         SSSSSSSS            -
-0090 %         SSSSSSSS             -
-0091 %         -       1 -
-0092 %               -  1 -
-0093 %           -          M         -
-0094 %             -         M         -
-0095 %                 - - M         -
-0096 %                  - -   M         -
-0097 % An example with 8 rxns and 6 metabolites. - means -1, M max flux, and S is the S matrix.
-0098 % 4 rxns are to be minimized(1,3,5,7) and 1,7 are reversible. The p and n
-0099 % are the Vipos and Vineg variables (2 rxns of each). The ints are the Yi for
-0100 % the variables that are to be minimized (the rest of the rxns doesn't have any).
-0101 % The mets here are the constraints, so right under the S matrix, you have
-0102 % Vi == Vipos - Vineg for the reactions 1 and 7 while the two next rows represent
-0103 % the non-reversible rxns 3 and 5, where we simply say that yi*M >= Vi. The last
-0104 % 2 rows are the reactions yi*M >= Vipos + Vineg. To the right, we first have a
-0105 % -I matrix for setting the b constraints, and under that we have rxns that are
-0106 % just variables (rxns) between 0 and Inf to complete the constraints mentioned above.
-0107 %Ex: yi*M >= Vipos + Vineg is impl. as yi*M - Vipos - Vineg - var == 0, 0 <= var <= Inf.
-0108 %
-0109 %All rows should be equal to zero, so we don't set the b vector in the problem
-0110 %The reactions should be constrained as follows
-0111 %S - as given in model.lb and model.ub
-0112 %pos and neg - between 0 and inf
-0113 %ints - between 0 and 1
-0114 %b - as stated in the model.b vector - if this has one column, that is lb and ub (fixed value), if two columns, that is lb and ub
-0115 %var - between zero and inf
-0116 
-0117 [minLog, I]=ismember(model.rxns,toMinimize);
-0118 indexes=find(minLog);
-0119 revIndexes = find(minLog & (model.rev == 1));
-0120 irrevIndexes = find(minLog & (model.rev == 0));
-0121 revIndexesInInd = find(model.rev(indexes) == 1);
-0122 irrevIndexesInInd = find(model.rev(indexes) == 0);
-0123 
-0124 %Add binary constraints in the following manner: -  Add one unique
-0125 %"metabolite" for each integer reaction as a substrate.
-0126 %   These metabolites can have net production
-0127 %-  Add reactions for the production of each of those metabolites. The
-0128 %   amount produced in one reaction unit must be larger than the largest
-0129 %   possible flux in the model (but not too large to avoid bad scaling)
-0130 
-0131 maxFlux=1000;
-0132 %we build the total matrix as blocks: [S pos neg int b var]
-0133 
-0134 %s block
-0135 intArray=speye(numel(model.rxns))*-1;
-0136 intArrayRev=intArray(revIndexes,:);
-0137 intArrayIrrev = intArray(irrevIndexes,:);
-0138 sBlock=[model.S;intArrayRev;intArrayIrrev;sparse(numel(revIndexes), numel(model.rxns))]; %the S matrix and what is below
-0139 
-0140 %pos/neg blocks
-0141 revposorneg1 = sparse(numel(model.mets), numel(revIndexes));
-0142 revpos2 = speye(numel(revIndexes));
-0143 revneg2 = -revpos2;
-0144 revposneg3 = sparse(numel(irrevIndexes), numel(revIndexes));
-0145 revposneg4 = revneg2;
-0146 posBlock = [revposorneg1;revpos2;revposneg3;revposneg4];
-0147 negBlock = [revposorneg1;revneg2;revposneg3;revposneg4];
-0148 
-0149 %int block
-0150 int1 = sparse(numel(model.mets), numel(indexes));
-0151 int2 = sparse(numel(revIndexes), numel(indexes));
-0152 tmpEye = speye(numel(indexes))*maxFlux;
-0153 int3 = tmpEye(irrevIndexesInInd,:);%we here select only the irrev indexes from the indexes
-0154 int4 = tmpEye(revIndexesInInd,:);
-0155 intBlock = [int1;int2;int3;int4];
-0156 
-0157 %b block
-0158 b1 = speye(numel(model.mets))*-1;
-0159 b2 = sparse(numel(indexes) + numel(revIndexes), numel(model.mets));
-0160 bBlock = [b1;b2];
-0161 
-0162 %var block
-0163 var1 = sparse(numel(model.mets), numel(indexes));
-0164 var2 = sparse(numel(revIndexes), numel(indexes));
-0165 tmpEye = speye(numel(indexes))*-1;
-0166 var3 = tmpEye(irrevIndexesInInd,:);
-0167 var4 = tmpEye(revIndexesInInd,:);
-0168 varBlock = [var1;var2;var3;var4];
-0169 
-0170 prob.A = [sBlock posBlock negBlock intBlock bBlock varBlock];
-0171 prob.a = prob.A;%I think this is needed as well
-0172 
-0173 prob.c=[zeros(numel(model.rxns),1);zeros(numel(revIndexes)*2,1); scores(:);zeros(numel(model.mets) + numel(indexes),1)]; %Minimize the sum of reaction scores for reactions that are on
-0174 
-0175 %ub and lb, text copied from above
-0176 %S - as given in model.lb and model.ub
-0177 %pos and neg - between 0 and inf
-0178 %ints - between 0 and 1
-0179 %b - as stated in the model.b vector - if this has one column, that is lb and ub (fixed value), if two columns, that is lb and ub
-0180 %var - between zero and inf
-0181 
-0182 if size(model.b,2)==2
-0183     bub = model.b(:,2);
-0184 else
-0185     bub = model.b(:,1);
-0186 end
-0187 
-0188 prob.lb = [model.lb;zeros(numel(revIndexes)*2,1);zeros(numel(indexes),1);model.b(:,1);zeros(numel(indexes),1)];
-0189 prob.ub = [model.ub;inf(numel(revIndexes)*2,1);ones(numel(indexes),1);bub;inf(numel(indexes),1)];
-0190 
-0191 prob.b=zeros(size(prob.a,1), 1);
-0192 
-0193 %Use the output from the linear solution as starting point. Only the values
-0194 %for the integer variables will be used, but all are supplied.
-0195 intsIndexes = find(prob.c ~= 0);
-0196 %The start point is not important (solved quickly anyway), so just skip it.
-0197 %prob.sol.int.xx=zeros(numel(prob.c),1);
-0198 %prob.sol.int.xx(intsIndexes(sol.x(indexes)>10^-3))=1;%these doesn't work for gurobi anyways...
-0199 prob.x0=[];
-0200 prob.vartype=repmat('C', 1, size(prob.A,2));
-0201 prob.vartype(intsIndexes) = 'B';
-0202 prob.csense = repmat('E', 1, size(prob.A,1));
-0203 prob.osense=1; %minimize the objective
-0204 
-0205 %prob=rmfield(prob,{'blx','bux','blc','buc'});
-0206 params.intTol = 10^-9; %experment with this value
-0207 params.TimeLimit = 300;
-0208 params.Seed = 26;%This is weird - although it says "optimal solution found", we can get different results with different
-0209                  %values of the objective function, where one is more optimal than the other (pretty big difference...)
-0210 params.Threads = 1; %single-threaded Gurobi MILP for determinism, see issue #607
-0211 %params.CSClientLog = 3;%generates a warning in gurobi, but may be of interest for other solvers
-0212 
-0213 % Optimize the problem
-0214 res = optimizeProb(prob,params,verbose);
-0215 isFeasible=checkSolution(res);
-0216 
-0217 if ~isFeasible
-0218     x=[];
-0219     I=[];
-0220     exitFlag=-1;
-0221     return;
-0222 end
-0223 
-0224 x=res.full(1:numel(model.rxns));%the fluxes
-0225 I=res.full(intsIndexes) > 10^-3;%The margin for integers in gurobi is 10^-5, not 10^-12 that was previously used! Use 10^-3 to have some margin!
-0226 
-0227 tmp = res.full(intsIndexes);
-0228 sel = (tmp > 10^-12) & (tmp < 0.5);
-0229 if sum(sel) > 0
-0230     %This may indicate that there is a problem with the tolerances in the solver
-0231     disp(['ftINITFillGapsMILP: Some variables meant to be boolean in the MILP have intermediate values. Num vars: ' num2str(sum(sel))])
-0232 end
-0233 
-0234 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/INIT/ftINITInternalAlg.html b/doc/INIT/ftINITInternalAlg.html deleted file mode 100644 index d03684e08..000000000 --- a/doc/INIT/ftINITInternalAlg.html +++ /dev/null @@ -1,551 +0,0 @@ - - - - Description of ftINITInternalAlg - - - - - - - - - -
Home > INIT > ftINITInternalAlg.m
- - - -

ftINITInternalAlg -

- -

PURPOSE ^

-
ftINITInternalAlg
- -

SYNOPSIS ^

-
function [deletedRxns,metProduction,res,turnedOnRxns,fluxes]=ftINITInternalAlg(model,rxnScores,metData,essentialRxns,prodWeight,allowExcretion,remPosRev,params,startVals,fluxes,verbose)
- -

DESCRIPTION ^

-
 ftINITInternalAlg
-    This function runs the MILP for a step in ftINIT.
-
-   model           a reference model structure
-   rxnScores       a vector of scores for the reactions in the model.
-                   Positive scores are reactions to keep and negative
-                   scores are reactions to exclude. Rxns set to 0 are excluded
-                   from the problem.
-   metData         boolean matrix with mets as rows and rxns as columns
-                   saying which reaction produces each detected met (optional, default [])
-   essentialRxns   cell array of reactions that are essential and that
-                   have to be in the resulting model. This is normally
-                   used when fitting a model to task (see fitTasks)
-   prodWeight      a score that determines the value of having
-                   net-production of metabolites. This is a way of having
-                   a more functional network as it provides a reason for
-                   including bad reactions for connectivity reasons. This
-                   score is for each metabolite, and the sum of these weights
-                   and the scores for the reactions is what is optimized
-   allowExcretion  true if excretion of all metabolites should be allowed.
-                   This results in fewer reactions being considered
-                   dead-ends, but all reactions in the resulting model may
-                   not be able to carry flux. If this is "false" then the
-                   equality constraints are taken from model.b. If the
-                   input model lacks exchange reactions then this should
-                   probably be "true", or a large proportion of the model
-                   would be excluded for connectivity reasons
-   remPosRev       If true, the positive reversible reactions are removed from the problem.
-                   This is used in step 1 of ftINIT
-   params          parameters for the MILP, for example MIPGap and TimeLimit
-   startVals       Start values for the MILP, typically used when rerunning
-                   with a higher MIPGap, to use the results from the previous
-                   run
-   fluxes          Fluxes from the last run.
-   verbose         If true, the MILP progression will be shown. 
-
-   deletedRxns     reactions which were deleted by the algorithm (only 
-                   rxns included in the problem)
-   metProduction   array that indicates which of the
-                   metabolites in presentMets that could be
-                   produced
-                   0: metabolite could not be produced
-                   1: metabolite could be produced
-   res             The result from the MILP
-   turnedOnRxns    The reactions determined to be present (only 
-                   rxns included in the problem) 
-   fluxes          The fluxes from the MILP
-
-   This function is the actual implementation of the algorithm. See
-   ftINIT for a higher-level function for model reconstruction. 
-
- Usage: [deletedRxns,metProduction,res,turnedOnRxns,fluxes]=runINIT9(model,...
-           rxnScores,presentMets,essentialRxns,prodWeight,allowExcretion,...
-           remPosRev,params)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function [deletedRxns,metProduction,res,turnedOnRxns,fluxes]=ftINITInternalAlg(model,rxnScores,metData,essentialRxns,prodWeight,allowExcretion,remPosRev,params,startVals,fluxes,verbose)
-0002 % ftINITInternalAlg
-0003 %    This function runs the MILP for a step in ftINIT.
-0004 %
-0005 %   model           a reference model structure
-0006 %   rxnScores       a vector of scores for the reactions in the model.
-0007 %                   Positive scores are reactions to keep and negative
-0008 %                   scores are reactions to exclude. Rxns set to 0 are excluded
-0009 %                   from the problem.
-0010 %   metData         boolean matrix with mets as rows and rxns as columns
-0011 %                   saying which reaction produces each detected met (optional, default [])
-0012 %   essentialRxns   cell array of reactions that are essential and that
-0013 %                   have to be in the resulting model. This is normally
-0014 %                   used when fitting a model to task (see fitTasks)
-0015 %   prodWeight      a score that determines the value of having
-0016 %                   net-production of metabolites. This is a way of having
-0017 %                   a more functional network as it provides a reason for
-0018 %                   including bad reactions for connectivity reasons. This
-0019 %                   score is for each metabolite, and the sum of these weights
-0020 %                   and the scores for the reactions is what is optimized
-0021 %   allowExcretion  true if excretion of all metabolites should be allowed.
-0022 %                   This results in fewer reactions being considered
-0023 %                   dead-ends, but all reactions in the resulting model may
-0024 %                   not be able to carry flux. If this is "false" then the
-0025 %                   equality constraints are taken from model.b. If the
-0026 %                   input model lacks exchange reactions then this should
-0027 %                   probably be "true", or a large proportion of the model
-0028 %                   would be excluded for connectivity reasons
-0029 %   remPosRev       If true, the positive reversible reactions are removed from the problem.
-0030 %                   This is used in step 1 of ftINIT
-0031 %   params          parameters for the MILP, for example MIPGap and TimeLimit
-0032 %   startVals       Start values for the MILP, typically used when rerunning
-0033 %                   with a higher MIPGap, to use the results from the previous
-0034 %                   run
-0035 %   fluxes          Fluxes from the last run.
-0036 %   verbose         If true, the MILP progression will be shown.
-0037 %
-0038 %   deletedRxns     reactions which were deleted by the algorithm (only
-0039 %                   rxns included in the problem)
-0040 %   metProduction   array that indicates which of the
-0041 %                   metabolites in presentMets that could be
-0042 %                   produced
-0043 %                   0: metabolite could not be produced
-0044 %                   1: metabolite could be produced
-0045 %   res             The result from the MILP
-0046 %   turnedOnRxns    The reactions determined to be present (only
-0047 %                   rxns included in the problem)
-0048 %   fluxes          The fluxes from the MILP
-0049 %
-0050 %   This function is the actual implementation of the algorithm. See
-0051 %   ftINIT for a higher-level function for model reconstruction.
-0052 %
-0053 % Usage: [deletedRxns,metProduction,res,turnedOnRxns,fluxes]=runINIT9(model,...
-0054 %           rxnScores,presentMets,essentialRxns,prodWeight,allowExcretion,...
-0055 %           remPosRev,params)
-0056 
-0057 if isempty(essentialRxns)
-0058     essentialRxns={};
-0059 end
-0060 essentialRxns=essentialRxns(:);
-0061 if isempty(prodWeight)
-0062     prodWeight=0.5;
-0063 end
-0064 
-0065 
-0066 %The model should be in the reversible format and all relevant exchange
-0067 %reactions should be open
-0068 if isfield(model,'unconstrained')
-0069     EM='Exchange metabolites are still present in the model. Use simplifyModel if this is not intended';
-0070     dispEM(EM,false);
-0071 end
-0072 
-0073 
-0074 essential = ismember(model.rxns,essentialRxns);
-0075 
-0076 %Some nice to have numbers
-0077 nMets=numel(model.mets);
-0078 nRxns=numel(model.rxns);
-0079 nRxnsWithOnOff = nRxns;
-0080 
-0081 %Reactions with score 0 will just be left in the model, and will not be part of the problem (but can carry flux).
-0082 %It is possible to set score = 0 for e.g. spontaneous reactions, exchange rxns, etc., which may not be that interesting
-0083 %to remove.
-0084 
-0085 %if makeIrrev is on, we can just as well skip all positive reversible rxns - they will be turned on without carrying any flux
-0086 %since they can form a loop within themself (fwd-rev)
-0087 if remPosRev
-0088     rxnScores(rxnScores > 0 & model.rev~=0) = 0;
-0089 end
-0090 
-0091 %Handle metabolomics
-0092 %A problem with the metabolomics is that some of the producer reactions
-0093 %for a metabolite could be excluded from the problem. We solve this by
-0094 %adding them with score 0. They can still be seen as positive, since they
-0095 %either don't matter (there is another producer) or they can contribute to an
-0096 %increased score.
-0097 revRxns=model.rev~=0; 
-0098 essRevRxns = find(revRxns & essential);
-0099 essIrrevRxns = find(~revRxns & essential);
-0100 
-0101 if ~isempty(metData)
-0102     %remove any metData rows that is connected to an essential rxn -
-0103     %these will be on regardless and will cause problems below.
-0104     containsEssential = any(metData(:,essential),2);
-0105     metData = metData(~containsEssential,:);
-0106 end
-0107 
-0108 if ~isempty(metData)
-0109     metRxns = any(metData,1).';
-0110     posRxns = rxnScores > 0 | ((rxnScores == 0) & metRxns);
-0111 else
-0112     posRxns = rxnScores > 0;
-0113 end
-0114 negRxns = rxnScores < 0;
-0115 
-0116 posRevRxns = find(posRxns & revRxns & ~essential);
-0117 negRevRxns = find(negRxns & revRxns & ~essential);
-0118 posIrrevRxns = find(posRxns & ~revRxns & ~essential);
-0119 negIrrevRxns = find(negRxns & ~revRxns & ~essential);
-0120 nPosRev = numel(posRevRxns);
-0121 nNegRev = numel(negRevRxns);
-0122 nPosIrrev = numel(posIrrevRxns);
-0123 nNegIrrev = numel(negIrrevRxns);
-0124 nEssRev = numel(essRevRxns);
-0125 nEssIrrev = numel(essIrrevRxns); %not used, but left for symmetry
-0126 nMetabolMets = size(metData,1);
-0127 
-0128 if ~isempty(metData)
-0129     metNegRev = negRxns & revRxns & ~essential & metRxns;
-0130     metNegIrrev = negRxns & ~revRxns & ~essential & metRxns;
-0131     nMetNegRev = sum(metNegRev);
-0132     nMetNegIrrev = sum(metNegIrrev);
-0133 end
-0134 
-0135 
-0136 milpModel = model;
-0137 
-0138 %These six categories need to be handled separately:
-0139 %
-0140 %PosIrrev (positive reaction score, irreversible):
-0141 %flux >= 0.1*Yi, flux - 0.1*Yi - VPI == 0, 0 <= Yi(onoff) <= 1, 0 <= VPI <= Inf
-0142 %The nice thing with rxns with positive score is that they do not require a boolean. The optimizer will
-0143 %strive for maximizing the Yi here, so it can be a continuous variable, where we just force a flux if
-0144 %the variable is on.
-0145 %PosRev:
-0146 % 1: Split up the flux into positive and negative: flux - vnrp + vnrn == 0, 0 <= vprp,vprn <= Inf.
-0147 % 2. Force one of the fluxes on: vprp + vprn >= 0.1*Yi, vprp + vprn - 0.1*Yi - vprv1 == 0. 0 <= Yi(onoff) <= 1, vprv1 >= 0
-0148 % 3. We need a bool to make sure that one of vprp and vprn are always zero:
-0149 %    vprb E {0,1}:  vprp <= 100*vprb (if bool is 0, vprp is zero): vprp - 100*vprb + vprv2 == 0, vprv2 >= 0
-0150 %    vprn <= (1-vprb)*100 (if bool is one, vprn is zero): vprn + 100*vprb + vprv3 == 0, -100 <= vprv3 <= inf
-0151 %Neg Irrev:
-0152 %For negative scores, we need to use an integer, I see no way around that.
-0153 % flux < 100*Yi, Yi E {0,1}. Flux - 100*Yi + vni == 0
-0154 %Neg Rev:
-0155 %Two cases:
-0156 %A: Without irrev model
-0157 % 1: Split up the flux into positive and negative: flux - vnrp + vnrn == 0, 0 <= vprp,vprn <= Inf.
-0158 % 2: Force the Yi (on/off) var on if the flux is on: vnrp + vnrn <= 0.1 * Yi, Yi E {0,1}: vnrp + vnrn - 0.1 * Yi + vnrv1 == 0, vnrv1 >= 0.
-0159 %B: Irrev model (Not used for now)
-0160 % 1. We now have two reactions, but still just boolean variable. We know that
-0161 %    the flux can only be positive, so we just say that flux1 + flux2 <= 0.1 * Yi, Yi E {0,1}: flux1 + flux2 - 0.1 * Yi + vnrv1 == 0, vnrv1 >= 0.
-0162 %    We don't care if there is any loop - there is just no benefit for the objective to generate one, and it doesn't matter.
-0163 %Ess Irrev (essential rxn, i.e. forced to carry flux, irreversible):
-0164 %flux >= 0.1 - solved with lb = 0.1.
-0165 %Ess Rev (these are not really used):
-0166 % 1: Split up the flux into positive and negative: flux - verp + vern == 0, 0 <= verp,vern <= Inf.
-0167 % 2. Force one of the fluxes on: verp + vern >= 0.1, verp + vern - verv1 == 0. verv1 >= 0.1
-0168 % 3. We need a bool to make sure that one of verp and vern are always zero:
-0169 %    verb E {0,1}:  verp <= 100*verb (if bool is 0, verp is zero): verp - 100*verb + verv2 == 0, verv2 >= 0
-0170 %    vern <= (1-verb)*100 (if bool is one, vern is zero): vern + 100*verb + verv3 == 0, -100 <= verv3 <= inf
-0171 
-0172 % Now metabolomics
-0173 % The basic idea is that the bonus is gotten if any of the producer reactions are on. We can
-0174 % therefore use the "on" variables directly for the reactions that are included. We therefore add one variable per met, mon, which can be
-0175 % continuous and between 0 and 1. We then say that mon <= v1 + v2 + ... + vn, i.e. that
-0176 % mon + mv1 - v1 - v2 ... - vn == 0, 0 <= mon <= 1, 0 <= mv1 <= inf
-0177 % mon gets -prodWeight in the c vector (i.e. objective function)
-0178 % A tricky part is that some of the reactions producing a metabolite are left outside the problem
-0179 % This is solved by moving them into the problem, but with the score 0. They can still be treated as positive
-0180 % reactions. In the end, we are not interested if they are on though, but they may
-0181 % allow for production of a metabolite, giving no benefit of turning on another producer reaction.
-0182 % Another tricky thing is that some metabolite producers have negative score. There is
-0183 % no automatic mechanism for forcing flux on if the variable is on - this is simply
-0184 % not needed for negative variables - unless they are a metabolite producer. We therefore need
-0185 % to add an extra constraint there, similar to the case of positive. It gets a bit complicated.
-0186 % For reversible, we need a bool to make sure that one of vnrp and vnrn stays zero:
-0187 %    vnrbm E {0,1}:  vnrp <= 100*vnrbm (if bool is 0, vnrp is zero): vnrp - 100*vnrbm + vnrvm1 == 0, vnrvm1 >= 0
-0188 %    vnrn <= (1-vnrbm)*100 (if bool is one, vnrn is zero): vnrn + 100*vnrbm + vnrvm2 == 0, -100 <= vnrvm2 <= inf
-0189 % We then also say that vnrp + vnrn >= 0.1*Yi, vnrp + vnrn - 0.1*Yi - vnrvm3 == 0, vnrvm3 >= 0
-0190 % For irreversible, it is fairly straight-forward. We just say that flux >= 0.1*Yi, i.e. flux - 0.1*Yi - vnim == 0, 0 <= vnim <= Inf.
-0191 
-0192 
-0193 %The total matrix then looks like this. Note that we have ordered the categories, two reactions each,
-0194 %in the S matrix to make it easier to follow the figure. In practice, they come in random order, which
-0195 %is why the SEye variable is used further down.
-0196 %all categories below have two columns - the two column starts where label starts
-0197 %since the label cannot fit in two chars, they are on multiple lines
-0198 %
-0199 %The met variables and constraints are not in this figure for practical reasons.
-0200 %
-0201 %                           vprb  vprv3 vnrn  vern  verv2 mv1
-0202 % pi  ni  ei  Ypi Yni vpi vprn  vprv2 vnrp  verp  verb  mon
-0203 %   pr  nr  er  Ypr Ynr vprp  vprv1 vni   vnrv1 verv1 verv3
-0204 % SSSSSSSSSSSS0000000000000000000000000000000000000000000000
-0205 % SSSSSSSSSSSS0000000000000000000000000000000000000000000000 S block
-0206 % SSSSSSSSSSSS0000000000000000000000000000000000000000000000
-0207 % 1           N       -                                      Pos irrev block
-0208 %  1           N       -
-0209 %   1                   - 1                                  Pos rev block 1
-0210 %    1                   - 1
-0211 %               N       1 1   -                              Pos rev block 2
-0212 %                N       1 1   -
-0213 %                       1   M   1                            Pos rev block 3
-0214 %                        1   M   1
-0215 %                         1 C     1                          Pos rev block 4
-0216 %                          1 C     1
-0217 %     1           M                 1                        Neg irrev block
-0218 %      1           M                 1
-0219 %       1                             - 1                    Neg rev block 1
-0220 %        1                             - 1
-0221 %                   M                 1 1 1                  Neg rev block 2
-0222 %                    M                 1 1 1
-0223 %           1                               - 1              Ess rev block 1
-0224 %            1                               - 1
-0225 %                                           1 1 -            Ess rev block 2
-0226 %                                            1 1 -
-0227 %                                           1     M 1        Ess rev block 3
-0228 %                                            1     M 1
-0229 %                                             1   C   1      Ess rev block 4
-0230 %                                              1   C   1
-0231 %             --------                                  1 1  Met block - Here, we assume that all variables support each met.
-0232 %             --------                                   1 1             In practice, fewer of the "on" variables with -1 should be included
-0233 %
-0234 %
-0235 %M = -100
-0236 %N = -0.1
-0237 %D = 0.1
-0238 %C = 100
-0239 %- = -1
-0240 %
-0241 %It looks a bit different for the irrev model, but still quite similar
-0242 
-0243 %build the A matrix
-0244 %S row
-0245 %When forcing on essential rxns, use the flux value of the previous run (set to 0.1 the first time)
-0246 %Don't set it above 0.1, may starve something else out. Leave a margin of 1% from the last run.
-0247 forceOnLim = 0.1;
-0248 forceOnLimEss=min(abs(fluxes)*0.99,0.1);
-0249 
-0250 varsPerNegRev = 3;
-0251 
-0252 
-0253 %Figure out the number of variables needed for metabolomics
-0254 if ~isempty(metData)
-0255     nMetVars = 2*size(metData,1) + 4*nMetNegRev + nMetNegIrrev; %mon,mv1; vnrbm,vnrvm1,vnrvm2,vnrvm3; vnim
-0256 else
-0257     nMetVars = 0;
-0258 end
-0259 
-0260 
-0261 sRow = [milpModel.S sparse(nMets, nPosIrrev*2+nPosRev*7+nNegIrrev*2+nNegRev*(1+varsPerNegRev)+nEssRev*6 + nMetVars)];
-0262 sEye = speye(nRxns);
-0263 nYBlock = nPosIrrev+nPosRev+nNegIrrev+nNegRev;
-0264 piRows = [sEye(posIrrevRxns,:) speye(nPosIrrev)*-forceOnLim sparse(nPosIrrev,nPosRev+nNegIrrev+nNegRev) speye(nPosIrrev)*-1 sparse(nPosIrrev,nPosRev*6+nNegIrrev+nNegRev*varsPerNegRev+nEssRev*6+nMetVars)];
-0265 
-0266 prRows1 = [sEye(posRevRxns,:) sparse(nPosRev,nYBlock + nPosIrrev) speye(nPosRev)*-1 speye(nPosRev) sparse(nPosRev,nPosRev*4+nNegIrrev+nNegRev*varsPerNegRev+nEssRev*6+nMetVars)];
-0267 prRows2 = [sparse(nPosRev,nRxns + nPosIrrev) speye(nPosRev)*-forceOnLim sparse(nPosRev,nNegIrrev + nNegRev + nPosIrrev) speye(nPosRev) speye(nPosRev) sparse(nPosRev,nPosRev) speye(nPosRev)*-1 sparse(nPosRev,nPosRev*2+nNegIrrev+nNegRev*varsPerNegRev+nEssRev*6+nMetVars)];
-0268 prRows3 = [sparse(nPosRev,nRxns + nYBlock + nPosIrrev) speye(nPosRev) sparse(nPosRev,nPosRev) speye(nPosRev)*-100 sparse(nPosRev,nPosRev) speye(nPosRev) sparse(nPosRev,nPosRev+nNegIrrev+nNegRev*varsPerNegRev+nEssRev*6+nMetVars)];
-0269 prRows4 = [sparse(nPosRev,nRxns + nYBlock + nPosIrrev + nPosRev) speye(nPosRev) speye(nPosRev)*100 sparse(nPosRev,nPosRev*2) speye(nPosRev) sparse(nPosRev, nNegIrrev+nNegRev*varsPerNegRev+nEssRev*6+nMetVars)];
-0270 
-0271 niRows = [sEye(negIrrevRxns,:) sparse(nNegIrrev,nPosIrrev + nPosRev) speye(nNegIrrev)*-100 sparse(nNegIrrev,nNegRev + nPosIrrev + nPosRev*6) speye(nNegIrrev) sparse(nNegIrrev,nNegRev*varsPerNegRev + nEssRev*6+nMetVars)];
-0272 
-0273 nrRows1 = [sEye(negRevRxns,:) sparse(nNegRev,nYBlock + nPosIrrev + nPosRev*6 + nNegIrrev) speye(nNegRev)*-1 speye(nNegRev) sparse(nNegRev,nNegRev + nEssRev*6+nMetVars)];
-0274 nrRows2 = [sparse(nNegRev,nRxns + nPosIrrev + nPosRev + nNegIrrev) speye(nNegRev)*-100 sparse(nNegRev,nPosIrrev + nPosRev*6 + nNegIrrev) speye(nNegRev) speye(nNegRev) speye(nNegRev) sparse(nNegRev,nEssRev*6+nMetVars)];
-0275 nrRows = [nrRows1;nrRows2];
-0276 
-0277 erRows1 = [sEye(essRevRxns,:) sparse(nEssRev,nYBlock + nPosIrrev + nPosRev*6 + nNegIrrev + nNegRev*varsPerNegRev) speye(nEssRev)*-1 speye(nEssRev) sparse(nEssRev, nEssRev*4+nMetVars)];
-0278 erRows2 = [sparse(nEssRev,nRxns + nYBlock + nPosIrrev + nPosRev*6 + nNegIrrev + nNegRev*varsPerNegRev) speye(nEssRev) speye(nEssRev) speye(nEssRev)*-1 sparse(nEssRev, nEssRev*3+nMetVars)];
-0279 erRows3 = [sparse(nEssRev,nRxns + nYBlock + nPosIrrev + nPosRev*6 + nNegIrrev + nNegRev*varsPerNegRev) speye(nEssRev) sparse(nEssRev, nEssRev*2) speye(nEssRev)*-100 speye(nEssRev) sparse(nEssRev, nEssRev+nMetVars)];
-0280 erRows4 = [sparse(nEssRev,nRxns + nYBlock + nPosIrrev + nPosRev*6 + nNegIrrev + nNegRev*varsPerNegRev + nEssRev) speye(nEssRev) sparse(nEssRev, nEssRev) speye(nEssRev)*100 sparse(nEssRev, nEssRev) speye(nEssRev) sparse(nEssRev, nMetVars)];
-0281 
-0282 %now the mets
-0283 if ~isempty(metData)
-0284     %Order of rxn "on" vars: Ypi Ypr Yni Ynr. This is a bit messy, since they are not in the
-0285     %same order as the reactions in the S matrix or metData. We therefore resort the vars in
-0286     %metData to match the order of the vars.
-0287     srtMetData = sparse([metData(:,posIrrevRxns) metData(:,posRevRxns) metData(:,negIrrevRxns) metData(:,negRevRxns)]);
-0288     
-0289     %First the setup for giving bonus if the met is included.
-0290     %The mon vars come first followed by the mv1 vars
-0291     metRows1 = [sparse(nMetabolMets,nRxns) -srtMetData sparse(nMetabolMets,  nPosIrrev + nPosRev*6 + nNegIrrev + nNegRev*varsPerNegRev + nEssRev*6) speye(nMetabolMets) speye(nMetabolMets) sparse(nMetabolMets, 4*nMetNegRev + nMetNegIrrev)];
-0292     %Then negative rev:
-0293     % Variable order: eye(vnrbm),eye(vnrvm1),eye(vnrvm2),eye(vnrvm3)
-0294     % vnrp,vnrn are the two first variables among the neg rev vars.
-0295     % For reversible, we need a bool to make sure that one of vnrp and vnrn stays zero:
-0296     %    vnrbm E {0,1}:  vnrp <= 100*vnrbm (if bool is 0, vnrp is zero): vnrp - 100*vnrbm + vnrvm1 == 0, vnrvm1 >= 0 (metRows2)
-0297     %    vnrn <= (1-vnrbm)*100 (if bool is one, vnrn is zero): vnrn + 100*vnrbm + vnrvm2 == 0, -100 <= vnrvm2 <= inf (metRows3)
-0298     % We then also say that vnrp + vnrn >= 0.1*Yi, -0.1*Yi + vnrp + vnrn - vnrvm3 == 0, vnrvm3 >= 0 (metRows4)
-0299     nrEye = speye(nNegRev);
-0300     %vnrp - 100*vnrbm + vnrvm1 == 0
-0301     metRows2 = [sparse(nMetNegRev,nRxns + nYBlock + nPosIrrev + nPosRev*6 + nNegIrrev) ... %zeros up to vnrp
-0302                 nrEye(metNegRev(negRevRxns),:) ... %vnrp 
-0303                 sparse(nMetNegRev, nNegRev*(varsPerNegRev-1) + nEssRev*6 + nMetabolMets*2) ... %zeros up to vnrbm
-0304                 speye(nMetNegRev)*-100 ... %vnrbm
-0305                 speye(nMetNegRev) ... % vnrvm1
-0306                 sparse(nMetNegRev, nMetNegRev*2 + nMetNegIrrev)];%fill up the rest with zeros
-0307     %vnrn + 100*vnrbm + vnrvm2 == 0
-0308     metRows3 = [sparse(nMetNegRev,nRxns + nYBlock + nPosIrrev + nPosRev*6 + nNegIrrev + nNegRev) ... %zeros up to vnrn
-0309                 nrEye(metNegRev(negRevRxns),:) ... %vnrp 
-0310                 sparse(nMetNegRev, nNegRev*(varsPerNegRev-2) + nEssRev*6 + nMetabolMets*2) ... %zeros up to vnrbm
-0311                 speye(nMetNegRev)*100 ... %vnrbm
-0312                 sparse(nMetNegRev, nMetNegRev) ... %zeros up to vnrvm2
-0313                 speye(nMetNegRev) ... % vnrvm2
-0314                 sparse(nMetNegRev, nMetNegRev + nMetNegIrrev)];%fill up the rest with zeros
-0315     %-0.1*Yi + vnrp + vnrn - vnrvm3 == 0
-0316     metRows4 = [sparse(nMetNegRev,nRxns + nPosIrrev + nPosRev + nNegIrrev) ... %zeros up to Yi for neg rev
-0317                 nrEye(metNegRev(negRevRxns),:)*-0.1 ... %Yi for met neg rev
-0318                 sparse(nMetNegRev, nPosIrrev + nPosRev*6 + nNegIrrev) ... %zeros up to vnrp
-0319                 nrEye(metNegRev(negRevRxns),:) ... %vnrp
-0320                 nrEye(metNegRev(negRevRxns),:) ... %vnrn
-0321                 sparse(nMetNegRev, nNegRev*(varsPerNegRev-2) + nEssRev*6 + nMetabolMets*2 + nMetNegRev*3) ...%zeros up to vnrvm3
-0322                 speye(nMetNegRev)*-1 ... % vnrvm3
-0323                 sparse(nMetNegRev, nMetNegIrrev)];%fill up the rest with zeros
-0324     
-0325     %Then negative irrev, i.e. flux - 0.1*Yi - vnim == 0
-0326     niEye = speye(nNegIrrev);
-0327     metRows5 = [sEye(metNegIrrev,:) ... %flux
-0328                 sparse(nMetNegIrrev, nPosIrrev + nPosRev) ... % zeros up to Yi for neg irrev
-0329                 niEye(metNegIrrev(negIrrevRxns),:)*-0.1 ... %Yi for met neg irrev
-0330                 sparse(nMetNegIrrev, nNegRev + nPosIrrev + nPosRev*6 + nNegIrrev + nNegRev*varsPerNegRev + nEssRev*6 + nMetabolMets*2 + 4*nMetNegRev) ... %zeros up to vnim
-0331                 -speye(nMetNegIrrev) ]; %vnim
-0332     metRows = [metRows1;metRows2;metRows3;metRows4;metRows5];
-0333     metVarC = [ones(nMetabolMets,1)*-prodWeight;zeros(nMetVars - nMetabolMets,1)];
-0334     %vnrbm is boolean, so between 0 and 1
-0335     %vnrvm1 >= 0
-0336     %-100 <= vnrvm2 <= inf
-0337     % vnrvm3 >= 0
-0338     %0 <= vnim <= Inf
-0339     metLb = [zeros(nMetabolMets*2 + 2*nMetNegRev,1);ones(nMetNegRev,1)*-100;zeros(nMetNegRev + nMetNegIrrev,1)];
-0340     metUb = [ones(nMetabolMets,1);inf(nMetabolMets,1);ones(nMetNegRev,1);inf(3*nMetNegRev + nMetNegIrrev,1)];
-0341     metVartype = [repmat('C', 1, nMetabolMets*2), ...
-0342                   repmat('B', 1, nMetNegRev), ...
-0343                   repmat('C', 1, 3*nMetNegRev + nMetNegIrrev)];
-0344 
-0345 else
-0346     metRows = [];
-0347     metVarC = [];
-0348     metLb = [];
-0349     metUb = [];
-0350     metVartype = [];
-0351 end
-0352 
-0353 prob.a = [sRow;piRows;prRows1;prRows2;prRows3;prRows4;niRows;nrRows;erRows1;erRows2;erRows3;erRows4;metRows];
-0354 prob.A = prob.a;
-0355 prob.b = zeros(size(prob.A,1),1);
-0356 prob.c = [zeros(nRxns,1);rxnScores(posIrrevRxns)*-1;rxnScores(posRevRxns)*-1;rxnScores(negIrrevRxns)*-1;rxnScores(negRevRxns)*-1;zeros(nPosIrrev + nPosRev*6 + nNegIrrev + nNegRev*varsPerNegRev + nEssRev*6,1);metVarC];
-0357 prob.lb = [milpModel.lb;zeros(nYBlock + nPosIrrev + 5*nPosRev,1);ones(nPosRev,1)*-100;zeros(nNegIrrev+nNegRev*varsPerNegRev+nEssRev*2,1);ones(nEssRev,1)*forceOnLim;zeros(nEssRev*2,1);ones(nEssRev,1)*-100;metLb];
-0358 prob.lb(essIrrevRxns) = forceOnLimEss(essIrrevRxns);%force flux for the ess irrev rxns - this is the only way these are handled
-0359 prob.ub = [milpModel.ub;ones(nYBlock,1);inf(nPosIrrev+nPosRev*2,1);ones(nPosRev,1);inf(3*nPosRev+nNegIrrev+varsPerNegRev*nNegRev+3*nEssRev,1);ones(nEssRev,1);inf(2*nEssRev,1);metUb];
-0360 
-0361 prob.vartype = [repmat('C', 1, nRxns + nPosIrrev + nPosRev), ...
-0362                 repmat('B', 1, nNegIrrev + nNegRev), ...
-0363                 repmat('C', 1, nPosIrrev + 2*nPosRev), ... 
-0364                 repmat('B', 1, nPosRev), ...
-0365                 repmat('C', 1, 3*nPosRev + nNegIrrev + varsPerNegRev*nNegRev + 3*nEssRev), ...
-0366                 repmat('B', 1, nEssRev), ...
-0367                 repmat('C', 1, 2*nEssRev), ...
-0368                 metVartype];
-0369             
-0370 onoffVarInd = (1:(nPosIrrev + nPosRev + nNegIrrev + nNegRev)) + nRxns;
-0371 onoffPosIrrev = onoffVarInd(1:nPosIrrev);
-0372 onoffPosRev = onoffVarInd((1:nPosRev)+nPosIrrev);
-0373 onoffNegIrrev = onoffVarInd((1:nNegIrrev)+nPosIrrev+nPosRev);
-0374 onoffNegRev = onoffVarInd((1:nNegRev)+nPosIrrev+nPosRev+nNegIrrev);
-0375 
-0376 metVarInd = (1:nMetabolMets) + (length(prob.vartype) - nMetVars);
-0377 
-0378 if allowExcretion
-0379     prob.csense = [repmat('L', 1, length(milpModel.mets)), ...
-0380                   repmat('E', 1, length(prob.b) - length(milpModel.mets))];
-0381 else
-0382     prob.csense = '=';
-0383 end
-0384 
-0385 params.intTol = 10^-7; %This value is very important. If set too low
-0386                        %there is a risk that gurobi fails due to numerical
-0387                        %issues - this happened for Gurobi v. 10.0 with TestModelL.
-0388                        %On the other hand, it shouldn't be too large
-0389                        %either. With this value, fluxes of 10-7 can slip
-0390                        %through, which should be fine. Another option if
-0391                        %this becomes a problem is to set NumericFocus=2,
-0392                        %which makes the solver slower but fixes the issue
-0393                        %with TestModelL.
-0394 
-0395 prob.osense = 1; %minimize
-0396 
-0397 if ~isempty(startVals)
-0398      prob.start = startVals; %This doesn't work...
-0399 end
-0400 
-0401 res=optimizeProb(prob,params,verbose);
-0402 
-0403 
-0404 if ~checkSolution(res)
-0405     if strcmp(res.origStat, 'TIME_LIMIT')
-0406         EM='Time limit reached without finding a solution. Try increasing the TimeLimit parameter.';
-0407     else
-0408         EM='The problem is infeasible';
-0409     end
-0410     dispEM(EM);
-0411 end
-0412 
-0413 %get the on/off vals
-0414 onoff = ones(nRxnsWithOnOff,1);%standard is on, i.e. all reactions not included in the problem + ess is on
-0415 onoff(posIrrevRxns) = res.full(onoffPosIrrev);
-0416 onoff(posRevRxns) = res.full(onoffPosRev);
-0417 onoff(negIrrevRxns) = res.full(onoffNegIrrev);
-0418 onoff(negRevRxns) = res.full(onoffNegRev);
-0419 
-0420 onoff2 = zeros(nRxnsWithOnOff,1);%standard is off, i.e. all reactions not included in the problem + ess is off
-0421 onoff2(posIrrevRxns) = res.full(onoffPosIrrev);
-0422 onoff2(posRevRxns) = res.full(onoffPosRev);
-0423 onoff2(negIrrevRxns) = res.full(onoffNegIrrev);
-0424 onoff2(negRevRxns) = res.full(onoffNegRev);
-0425 
-0426 
-0427 %investigate a bit - this code could be used for fault finding. We have
-0428 %this code commented out, but it is definitely worth testing this if for example
-0429 %the solver is changed.
-0430 %problematic = onoff < 0.99 & onoff > 0.01 & (rxnScores ~= 0).';
-0431 %if sum(problematic) > 0
-0432 %    disp('There are reactions that are in between on and off in the MILP. This may be due to the MILP parameter settings, the tolerances may be too large.')
-0433 %    disp(['No problematic reactions: ', num2str(sum(problematic))])
-0434 %end
-0435 
-0436 %so, it is only positive that are problematic. Likely because the 0.1 is too large. Test to change to 0.01
-0437 %unique(onoff(onoff < 0.99 & onoff > 0.01))
-0438 
-0439 %Get all reactions used in the irreversible model
-0440 %The reaction score check is for metabolomics - we add those reactions as
-0441 %positive even though the score is 0. And, we don't want them included in the
-0442 %results.
-0443 deletedRxns=(onoff < 0.5).' & (rxnScores ~= 0).'; 
-0444 turnedOnRxns=(onoff2 >= 0.5).' & (rxnScores ~= 0).';
-0445 
-0446 fluxes = res.full(1:nRxns);
-0447 
-0448 %extract the met data
-0449 metProduction = logical(round(res.full(metVarInd)));
-0450 
-0451 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/INIT/getExprForRxnScore.html b/doc/INIT/getExprForRxnScore.html deleted file mode 100644 index e97beb72a..000000000 --- a/doc/INIT/getExprForRxnScore.html +++ /dev/null @@ -1,85 +0,0 @@ - - - - Description of getExprForRxnScore - - - - - - - - - -
Home > INIT > getExprForRxnScore.m
- - - -

getExprForRxnScore -

- -

PURPOSE ^

-
getExprForRxnScore
- -

SYNOPSIS ^

-
function expr = getExprForRxnScore(scores, threshold)
- -

DESCRIPTION ^

-
 getExprForRxnScore
-   Converts a reaction score to the gene expression (CPM or TPM) required 
-   to get that reaction score, if the GPR is only a single gene.
-   Useful function primarily in test cases, where you want to be able to
-   define the reaction scores of rxns, but need to send in gene expression.
-
-   scores        Vector of scores to convert
-   threshold     Gene threshold (optional, default 1)
-
-   expr          The resulting gene expression vector.
-
- Usage: expr = getExprForRxnScore(scores, threshold)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function expr = getExprForRxnScore(scores, threshold)
-0002 % getExprForRxnScore
-0003 %   Converts a reaction score to the gene expression (CPM or TPM) required
-0004 %   to get that reaction score, if the GPR is only a single gene.
-0005 %   Useful function primarily in test cases, where you want to be able to
-0006 %   define the reaction scores of rxns, but need to send in gene expression.
-0007 %
-0008 %   scores        Vector of scores to convert
-0009 %   threshold     Gene threshold (optional, default 1)
-0010 %
-0011 %   expr          The resulting gene expression vector.
-0012 %
-0013 % Usage: expr = getExprForRxnScore(scores, threshold)
-0014 
-0015 if nargin < 2
-0016     threshold = 1;
-0017 end
-0018 
-0019 %This is how the score is calculated: 5*log(expression./threshold)
-0020 %expression = threshold*10.^(scores/5)
-0021 %This is a bit confusing - it seems that it is threshold*e.^(scores/5)
-0022 %This is probably what is being used in scoreComplexModel, this code
-0023 %negates that perfectly, see the T0009 test case.
-0024 
-0025 expr = threshold*exp(scores/5);
-0026 
-0027 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/INIT/getINITModel.html b/doc/INIT/getINITModel.html deleted file mode 100644 index d09135107..000000000 --- a/doc/INIT/getINITModel.html +++ /dev/null @@ -1,609 +0,0 @@ - - - - Description of getINITModel - - - - - - - - - -
Home > INIT > getINITModel.m
- - - -

getINITModel -

- -

PURPOSE ^

-
getINITModel_legacy
- -

SYNOPSIS ^

-
function [model, metProduction, essentialRxnsForTasks, addedRxnsForTasks, deletedDeadEndRxns, deletedRxnsInINIT, taskReport]=getINITModel(refModel, tissue, celltype, hpaData, arrayData, metabolomicsData, taskFile, useScoresForTasks, printReport, taskStructure)
- -

DESCRIPTION ^

-
 getINITModel_legacy
-   Generates a model using the INIT algorithm, based on proteomics and/or
-   transcriptomics and/or metabolomics and/or metabolic tasks. This is the original 
-   implementation of tINIT, which is replaced by ftINIT.
-
- Input:
-   refModel            a model structure. The model should be in the
-                       closed form (no exchange reactions open). Import
-                       using import(filename,false). If the model is not
-                       loaded using importModel, it might be that there
-                       is no "unconstrained" field. In that case,
-                       manually add the field like:
-                       model.unconstrained=false(numel(model.mets),1);
-   tissue              tissue to score for. Should exist in either
-                       hpaData.tissues or arrayData.tissues
-   celltype            cell type to score for. Should exist in either
-                       hpaData.celltypes or arrayData.celltypes for this
-                       tissue (optional, default is to use the best values
-                       among all the cell types for the tissue. Use [] if
-                       you want to supply more arguments)
-   hpaData             HPA data structure from parseHPA (optional if arrayData is
-                       supplied, default [])
-   arrayData           gene expression data structure (optional if hpaData is
-                       supplied, default [])
-       genes           cell array with the unique gene names
-       tissues         cell array with the tissue names. The list may not be
-                       unique, as there can be multiple cell types per tissue
-       celltypes       cell array with the cell type names for each tissue
-       levels          GENESxTISSUES array with the expression level for
-                       each gene in each tissue/celltype. NaN should be
-                       used when no measurement was performed
-       threshold       a single value or a vector of gene expression 
-                       thresholds, above which genes are considered to be
-                       "expressed". (optional, by default, the mean expression
-                       levels of each gene across all tissues in arrayData
-                       will be used as the threshold values)
-       singleCells     binary value selecting whether to use the
-                       single-cell algorithm to identify expressed genes.
-                       If used, specify cell subpopulations in CELLTYPES
-                       (optional, default [])
-       plotResults     true if single cell probability distributions
-                       should be plotted (optional, default = False)
-   metabolomicsData    cell array with metabolite names that the model
-                       should produce (optional, default [])
-   taskFile            a task list in Excel format. See parseTaskList for
-                       details (optional, default [])
-   useScoresForTasks   true if the calculated reaction scored should be used as
-                       weights in the fitting to tasks (optional, default true)
-   printReport         true if a report should be printed to the screen
-                       (optional, default true)
-   taskStructure       task structure as from parseTaskList. Can be used
-                       as an alternative way to define tasks when Excel
-                       sheets are not suitable. Overrides taskFile (optional,
-                       default [])
-
- Output:
-   model                   the resulting model structure
-   metProduction           array that indicates which of the
-                           metabolites in metabolomicsData that could be
-                           produced. Note that this is before the
-                           gap-filling process to enable defined tasks. To
-                           see which metabolites that can be produced in
-                           the final model, use canProduce.
-                           -2: metabolite name not found in model
-                           -1: metabolite found, but it could not be produced
-                           1: metabolite could be produced
-   essentialRxnsForTasks   cell array of the reactions which were
-                           essential to perform the tasks
-   addedRxnsForTasks       cell array of the reactions which were added in
-                           order to perform the tasks
-   deletedDeadEndRxns      cell array of reactions deleted because they
-                           could not carry flux (INIT requires a
-                           functional input model)
-   deletedRxnsInINIT       cell array of the reactions which were deleted by
-                           the INIT algorithm
-   taskReport              structure with the results for each task
-       id                  cell array with the id of the task
-       description         cell array with the description of the task
-       ok                  boolean array with true if the task was successful
-       essential           cell array with cell arrays of essential
-                           reactions for the task
-       gapfill             cell array of cell arrays of reactions included
-                           in the gap-filling for the task
-
-   This is the main function for automatic reconstruction of models based
-   on the (t)INIT algorithm (PLoS Comput Biol. 2012;8(5):e1002518, 
-   Mol Syst Biol. 2014;10:721). Not all settings are possible using this
-   function, and you may want to call the functions scoreModel, runINIT
-   and fitTasks individually instead.
-
-   NOTE: Exchange metabolites should normally not be removed from the model
-   when using this approach, since checkTasks/fitTasks rely on putting specific
-   constraints for each task. The INIT algorithm will remove exchange metabolites
-   if any are present. Use importModel(file,false) to import a model with
-   exchange metabolites remaining.
-
- Usage: [model, metProduction, essentialRxnsForTasks, addedRxnsForTasks,...
-               deletedDeadEndRxns, deletedRxnsInINIT, taskReport]=...
-               getINITModel(refModel, tissue, celltype, hpaData, arrayData,...
-               metabolomicsData, taskFile, useScoresForTasks, printReport,...
-               taskStructure, params, paramsFT)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 function [model, metProduction, essentialRxnsForTasks, addedRxnsForTasks, deletedDeadEndRxns, deletedRxnsInINIT, taskReport]=getINITModel(refModel, tissue, celltype, hpaData, arrayData, metabolomicsData, taskFile, useScoresForTasks, printReport, taskStructure)
-0002 % getINITModel_legacy
-0003 %   Generates a model using the INIT algorithm, based on proteomics and/or
-0004 %   transcriptomics and/or metabolomics and/or metabolic tasks. This is the original
-0005 %   implementation of tINIT, which is replaced by ftINIT.
-0006 %
-0007 % Input:
-0008 %   refModel            a model structure. The model should be in the
-0009 %                       closed form (no exchange reactions open). Import
-0010 %                       using import(filename,false). If the model is not
-0011 %                       loaded using importModel, it might be that there
-0012 %                       is no "unconstrained" field. In that case,
-0013 %                       manually add the field like:
-0014 %                       model.unconstrained=false(numel(model.mets),1);
-0015 %   tissue              tissue to score for. Should exist in either
-0016 %                       hpaData.tissues or arrayData.tissues
-0017 %   celltype            cell type to score for. Should exist in either
-0018 %                       hpaData.celltypes or arrayData.celltypes for this
-0019 %                       tissue (optional, default is to use the best values
-0020 %                       among all the cell types for the tissue. Use [] if
-0021 %                       you want to supply more arguments)
-0022 %   hpaData             HPA data structure from parseHPA (optional if arrayData is
-0023 %                       supplied, default [])
-0024 %   arrayData           gene expression data structure (optional if hpaData is
-0025 %                       supplied, default [])
-0026 %       genes           cell array with the unique gene names
-0027 %       tissues         cell array with the tissue names. The list may not be
-0028 %                       unique, as there can be multiple cell types per tissue
-0029 %       celltypes       cell array with the cell type names for each tissue
-0030 %       levels          GENESxTISSUES array with the expression level for
-0031 %                       each gene in each tissue/celltype. NaN should be
-0032 %                       used when no measurement was performed
-0033 %       threshold       a single value or a vector of gene expression
-0034 %                       thresholds, above which genes are considered to be
-0035 %                       "expressed". (optional, by default, the mean expression
-0036 %                       levels of each gene across all tissues in arrayData
-0037 %                       will be used as the threshold values)
-0038 %       singleCells     binary value selecting whether to use the
-0039 %                       single-cell algorithm to identify expressed genes.
-0040 %                       If used, specify cell subpopulations in CELLTYPES
-0041 %                       (optional, default [])
-0042 %       plotResults     true if single cell probability distributions
-0043 %                       should be plotted (optional, default = False)
-0044 %   metabolomicsData    cell array with metabolite names that the model
-0045 %                       should produce (optional, default [])
-0046 %   taskFile            a task list in Excel format. See parseTaskList for
-0047 %                       details (optional, default [])
-0048 %   useScoresForTasks   true if the calculated reaction scored should be used as
-0049 %                       weights in the fitting to tasks (optional, default true)
-0050 %   printReport         true if a report should be printed to the screen
-0051 %                       (optional, default true)
-0052 %   taskStructure       task structure as from parseTaskList. Can be used
-0053 %                       as an alternative way to define tasks when Excel
-0054 %                       sheets are not suitable. Overrides taskFile (optional,
-0055 %                       default [])
-0056 %
-0057 % Output:
-0058 %   model                   the resulting model structure
-0059 %   metProduction           array that indicates which of the
-0060 %                           metabolites in metabolomicsData that could be
-0061 %                           produced. Note that this is before the
-0062 %                           gap-filling process to enable defined tasks. To
-0063 %                           see which metabolites that can be produced in
-0064 %                           the final model, use canProduce.
-0065 %                           -2: metabolite name not found in model
-0066 %                           -1: metabolite found, but it could not be produced
-0067 %                           1: metabolite could be produced
-0068 %   essentialRxnsForTasks   cell array of the reactions which were
-0069 %                           essential to perform the tasks
-0070 %   addedRxnsForTasks       cell array of the reactions which were added in
-0071 %                           order to perform the tasks
-0072 %   deletedDeadEndRxns      cell array of reactions deleted because they
-0073 %                           could not carry flux (INIT requires a
-0074 %                           functional input model)
-0075 %   deletedRxnsInINIT       cell array of the reactions which were deleted by
-0076 %                           the INIT algorithm
-0077 %   taskReport              structure with the results for each task
-0078 %       id                  cell array with the id of the task
-0079 %       description         cell array with the description of the task
-0080 %       ok                  boolean array with true if the task was successful
-0081 %       essential           cell array with cell arrays of essential
-0082 %                           reactions for the task
-0083 %       gapfill             cell array of cell arrays of reactions included
-0084 %                           in the gap-filling for the task
-0085 %
-0086 %   This is the main function for automatic reconstruction of models based
-0087 %   on the (t)INIT algorithm (PLoS Comput Biol. 2012;8(5):e1002518,
-0088 %   Mol Syst Biol. 2014;10:721). Not all settings are possible using this
-0089 %   function, and you may want to call the functions scoreModel, runINIT
-0090 %   and fitTasks individually instead.
-0091 %
-0092 %   NOTE: Exchange metabolites should normally not be removed from the model
-0093 %   when using this approach, since checkTasks/fitTasks rely on putting specific
-0094 %   constraints for each task. The INIT algorithm will remove exchange metabolites
-0095 %   if any are present. Use importModel(file,false) to import a model with
-0096 %   exchange metabolites remaining.
-0097 %
-0098 % Usage: [model, metProduction, essentialRxnsForTasks, addedRxnsForTasks,...
-0099 %               deletedDeadEndRxns, deletedRxnsInINIT, taskReport]=...
-0100 %               getINITModel(refModel, tissue, celltype, hpaData, arrayData,...
-0101 %               metabolomicsData, taskFile, useScoresForTasks, printReport,...
-0102 %               taskStructure, params, paramsFT)
-0103 
-0104 if nargin<3
-0105     celltype=[];
-0106 else
-0107     celltype=char(celltype);
-0108 end
-0109 if nargin<4
-0110     hpaData=[];
-0111 end
-0112 if nargin<5
-0113     arrayData=[];
-0114 end
-0115 if nargin<6
-0116     metabolomicsData=[];
-0117 end
-0118 if nargin<7
-0119     taskFile=[];
-0120 else
-0121     taskFile=char(taskFile);
-0122 end
-0123 if nargin<8 || isempty(useScoresForTasks)
-0124     useScoresForTasks=true;
-0125 end
-0126 if nargin<9 || isempty(printReport)
-0127     printReport=true;
-0128 end
-0129 if nargin<10
-0130     taskStructure=[];
-0131 end
-0132 if nargin<11
-0133     params=[];
-0134 end
-0135 if nargin<12
-0136     paramsFT=[];
-0137 end
-0138 
-0139 %Check that the model is in the closed form
-0140 if ~isfield(refModel,'unconstrained')
-0141     EM='Exchange metabolites should normally not be removed from the model when using getINITModel. Use importModel(file,false) to import a model with exchange metabolites remaining (see the documentation for details)';
-0142     dispEM(EM);
-0143 end
-0144 
-0145 %Create the task structure if not supplied
-0146 if any(taskFile) && isempty(taskStructure)
-0147     taskStructure=parseTaskList(taskFile);
-0148 end
-0149 
-0150 
-0151 % sc-tINIT to identify confidence levels of gene expression
-0152 if ~isempty(arrayData) && isfield(arrayData,'singleCells')
-0153     if arrayData.singleCells == 1
-0154         % Check to ensure cell type is defined
-0155         if ~isfield(arrayData,'celltypes')
-0156             dispEM('arrayData must contain cell type information if sc-tINIT is to be used','false');   
-0157         end
-0158         if ~ismember(upper(celltype),upper(arrayData.celltypes))
-0159             dispEM('The cell type name does not match');   
-0160         end
-0161         
-0162         % Analyze only cell type of interest
-0163         J= strcmpi(arrayData.celltypes,celltype);
-0164         
-0165         % Analyze only genes included in the reference model
-0166         I=ismember(arrayData.genes,refModel.genes);
-0167         
-0168         % Convert expression data to population fractions
-0169         binary_levels = arrayData.levels(I,J)~=0; % Classify each gene as detected (1) or not (0) in each cell
-0170         cell_count_levels = sum(binary_levels,2); % Number of cells expressing each transcript
-0171         cell_frac_levels = cell_count_levels/size(binary_levels,2); % Number of cells expressing each transcript
-0172 
-0173         % Bin cell_frac_counts manually
-0174         x = 0:.01:1;
-0175         for(i = 1:length(x))
-0176             cell_frac_count(i) = sum(round(cell_frac_levels,2)==x(i));
-0177         end
-0178         
-0179         % Fit four beta distributions
-0180         cell_frac_count(cell_frac_count==0) = NaN; % Remove zeros from optimization
-0181         cell_frac_count(1) = NaN; % Remove non-expressed genes from optimization
-0182         x_lim = 1; % Somewhat arbitrary parameter to fit left tail of distr.
-0183         myfun = @(par) nansum((cell_frac_count(1:find(x>=x_lim,1)) - ...
-0184             abs(par(1))*betapdf(x(1:find(x>=x_lim,1)),abs(par(2)),abs(par(3))) - ...
-0185             abs(par(4))*betapdf(x(1:find(x>=x_lim,1)),abs(par(5)),abs(par(6))) - ...
-0186             abs(par(7))*betapdf(x(1:find(x>=x_lim,1)),abs(par(8)),abs(par(9))) - ...
-0187             abs(par(10))*betapdf(x(1:find(x>=x_lim,1)),abs(par(11)),abs(par(12)))).^2);
-0188         
-0189         par0 = [4,2,100,7,2,30,7,5,20,5,15,20];
-0190         opts = optimset('Display','off');
-0191         [par,f_val] = fminsearch(myfun,par0,opts);
-0192         par = abs(par);
-0193         
-0194         % Plot results
-0195         if (isfield(arrayData,'plotResults'))
-0196             if arrayData.plotResults == true
-0197                 figure(); hold on; plot(x,cell_frac_count,'ko','MarkerSize',5);
-0198                 plot(x,abs(par(1))*betapdf(x,abs(par(2)),abs(par(3))),'b-','LineWidth',1)
-0199                 plot(x,abs(par(4))*betapdf(x,abs(par(5)),abs(par(6))),'b-','LineWidth',1)
-0200                 plot(x,abs(par(7))*betapdf(x,abs(par(8)),abs(par(9))),'b-','LineWidth',1)
-0201                 plot(x,abs(par(10))*betapdf(x,abs(par(11)),abs(par(12))),'b-','LineWidth',1)
-0202                 plot(x,abs(par(1))*betapdf(x,abs(par(2)),abs(par(3))) + ...
-0203                     abs(par(4))*betapdf(x,abs(par(5)),abs(par(6))) + ...
-0204                     abs(par(7))*betapdf(x,abs(par(8)),abs(par(9))) + ...
-0205                     abs(par(10))*betapdf(x,abs(par(11)),abs(par(12))),'-','Color',[.5 .5 .5],'LineWidth',2)
-0206                 xlabel('Expression Probability');ylabel('# of genes');set(gca,'FontSize',14,'LineWidth',1.25);
-0207                 title('Expression prediction','FontSize',18,'FontWeight','bold')
-0208             end
-0209         end
-0210         
-0211         % Score genes based on population expression (p = .05)
-0212         exprs_cutoff_1 = find(cdf('beta',x,par(2),par(3)) >.95,1)-1; % Find index of no confidence genes
-0213         exprs_cutoff_2 = find(cdf('beta',x,par(5),par(6)) >.95,1)-1; % Find index of low confidence genes
-0214         exprs_cutoff_3 = find(cdf('beta',x,par(8),par(9)) >.95,1)-1; % Find index of low confidence genes
-0215         exprs_cutoffs = sort([exprs_cutoff_1,exprs_cutoff_2,exprs_cutoff_3]);
-0216         gene_scores = cell_frac_levels*0;
-0217         gene_scores(cell_frac_levels <= x(exprs_cutoffs(1))) = 4; % Not detected
-0218         gene_scores(logical((cell_frac_levels >= x(exprs_cutoffs(1))).*(cell_frac_levels < x(exprs_cutoffs(2))))) = 3; % Low detection
-0219         gene_scores(logical((cell_frac_levels >= x(exprs_cutoffs(2))).*(cell_frac_levels < x(exprs_cutoffs(3))))) = 2; % Medium detection
-0220         gene_scores(cell_frac_levels > x(exprs_cutoffs(3))) = 1; % High detection
-0221 
-0222         % Replace hpaData with singleCellData
-0223         if printReport==true
-0224             dispEM('Single cell data is not currently compatible with HPA data. \n         Replacing hpaData with single cell-based scoring.',false);
-0225         end
-0226         hpaData.genes = arrayData.genes;
-0227         hpaData.tissues = arrayData.tissues;
-0228         hpaData.celltypes = arrayData.celltypes;
-0229         hpaData.levels = [{'High'},{'Medium'},{'Low'},{'None'}];
-0230         hpaData.gene2Level = zeros(length(arrayData.genes),length(arrayData.celltypes));
-0231         for i = 1:length(find(J))
-0232             find_var = find(J,i);
-0233             hpaData.gene2Level(I,find_var(end)) = gene_scores;
-0234         end
-0235         
-0236         % Remove arrayData from the analysis (Might be a bad idea)
-0237         clear arrayData
-0238         arrayData=[];
-0239     end
-0240 end
-0241 
-0242 
-0243 if printReport==true
-0244     if any(celltype)
-0245         fprintf(['***Generating model for: ' tissue ' - ' celltype '\n']);
-0246     else
-0247         fprintf(['***Generating model for: ' tissue '\n']);
-0248     end
-0249     if ~isempty(hpaData)
-0250         fprintf('-Using HPA data\n');
-0251     end
-0252     if ~isempty(arrayData)
-0253         fprintf('-Using array data\n');
-0254     end
-0255     if ~isempty(metabolomicsData)
-0256         fprintf('-Using metabolomics data\n');
-0257     end
-0258     if ~isempty(taskFile) || ~isempty(taskStructure)
-0259         fprintf('-Using metabolic tasks\n');
-0260     end
-0261     fprintf('\n');
-0262     
-0263     printScores(refModel,'Reference model statistics',hpaData,arrayData,tissue,celltype);
-0264 end
-0265 
-0266 %Remove dead-end reactions to speed up the optimization and to
-0267 %differentiate between reactions removed by INIT and those that are
-0268 %dead-end
-0269 [~, deletedDeadEndRxns]=simplifyModel(refModel,true,false,true,true,true);
-0270 cModel=removeReactions(refModel,deletedDeadEndRxns,false,true);
-0271 
-0272 %Store the connected model like this to keep track of stuff
-0273 if printReport==true
-0274     printScores(cModel,'Pruned model statistics',hpaData,arrayData,tissue,celltype);
-0275 end
-0276 
-0277 %If tasks have been defined, then go through them and get essential
-0278 %reactions
-0279 if ~isempty(taskStructure)
-0280     [taskReport, essentialRxnMat]=checkTasks(cModel,[],printReport,true,true,taskStructure);
-0281     
-0282     essentialRxnsForTasks=cModel.rxns(any(essentialRxnMat,2));
-0283     
-0284     %Remove tasks that cannot be performed
-0285     taskStructure(taskReport.ok==false)=[];
-0286     if printReport==true
-0287         printScores(removeReactions(cModel,setdiff(cModel.rxns,essentialRxnsForTasks),true,true),'Reactions essential for tasks',hpaData,arrayData,tissue,celltype);
-0288     end
-0289 else
-0290     essentialRxnsForTasks={};
-0291 end
-0292 
-0293 %Score the connected model
-0294 [rxnScores, geneScores]=scoreModel(cModel,hpaData,arrayData,tissue,celltype);
-0295 
-0296 %Run the INIT algorithm. The exchange reactions that are used in the final
-0297 %reactions will be open, which doesn't fit with the last step. Therefore
-0298 %delete reactions from the original model instead of taking the output. The
-0299 %default implementation does not constrain reversible reactions to only
-0300 %carry flux in one direction. Runs without the constraints on reversibility
-0301 %and with all output allowed. This is to reduce the complexity of the
-0302 %problem.
-0303 [~, deletedRxnsInINIT, metProduction]=runINIT(simplifyModel(cModel),rxnScores,metabolomicsData,essentialRxnsForTasks,0,true,false,params);
-0304 initModel=removeReactions(cModel,deletedRxnsInINIT,true,true);
-0305 if printReport==true
-0306     printScores(initModel,'INIT model statistics',hpaData,arrayData,tissue,celltype);
-0307     printScores(removeReactions(cModel,setdiff(cModel.rxns,deletedRxnsInINIT),true,true),'Reactions deleted by INIT',hpaData,arrayData,tissue,celltype);
-0308 end
-0309 
-0310 %The full model has exchange reactions in it. fitTasks calls on fillGaps,
-0311 %which automatically removes exchange metabolites (because it assumes that
-0312 %the reactions are constrained when appropriate). In this case the
-0313 %uptakes/outputs are retrieved from the task sheet instead. To prevent
-0314 %exchange reactions being used to fill gaps, they are delete from the
-0315 %reference model here.
-0316 initModel.id='INITModel';
-0317 
-0318 %If gaps in the model should be filled using a task list
-0319 if ~isempty(taskStructure)
-0320     %Remove exchange reactions and reactions already included in the INIT
-0321     %model
-0322     refModelNoExc=removeReactions(refModel,union(initModel.rxns,getExchangeRxns(refModel)),true,true);
-0323     
-0324     %At this stage the model is fully connected and most of the genes with
-0325     %good scores should have been included. The final gap-filling should
-0326     %take the scores of the genes into account, so that "rather bad"
-0327     %reactions are preferred to "very bad" reactions. However, reactions
-0328     %with positive scores will be included even if they are not connected
-0329     %in the current formulation. Therefore, such reactions will have to be
-0330     %assigned a small negative score instead.
-0331     if useScoresForTasks==true
-0332         refRxnScores=scoreModel(refModelNoExc,hpaData,arrayData,tissue,celltype);
-0333         [outModel, addedRxnMat]=fitTasks(initModel,refModelNoExc,[],true,min(refRxnScores,-0.1),taskStructure,paramsFT);
-0334     else
-0335         [outModel, addedRxnMat]=fitTasks(initModel,refModelNoExc,[],true,[],taskStructure,paramsFT);
-0336     end
-0337     if printReport==true
-0338         printScores(outModel,'Functional model statistics',hpaData,arrayData,tissue,celltype);
-0339         printScores(removeReactions(outModel,intersect(outModel.rxns,initModel.rxns),true,true),'Reactions added to perform the tasks',hpaData,arrayData,tissue,celltype);
-0340     end
-0341     
-0342     addedRxnsForTasks=refModelNoExc.rxns(any(addedRxnMat,2));
-0343 else
-0344     outModel=initModel;
-0345     addedRxnMat=[];
-0346     addedRxnsForTasks={};
-0347 end
-0348 
-0349 %The model can now perform all the tasks defined in the task list. The
-0350 %algorithm cannot deal with gene-complexes at the moment. It is therefore
-0351 %ok to remove bad genes from a reaction (as long as at least one gene is
-0352 %kept)
-0353 model=outModel;
-0354 
-0355 [~, I]=ismember(model.genes,cModel.genes); %All should be found
-0356 %This is a little weird way to make sure that only one bad gene is included
-0357 %if there are no good ones (since all -Inf==max(-Inf))
-0358 geneScores(isinf(geneScores))=-1000+rand(sum(isinf(geneScores)),1);
-0359 
-0360 model.grRules(:)={''};
-0361 for i=1:numel(model.rxns)
-0362     ids=find(model.rxnGeneMat(i,:));
-0363     if numel(ids)>1
-0364         scores=geneScores(I(ids));
-0365         %Only keep the positive ones if possible
-0366         model.rxnGeneMat(i,ids(~(scores>0 | scores==max(scores))))=0;
-0367     end
-0368     %Rewrite the grRules to be only OR
-0369     if isfield(model,'grRules')
-0370         J=find(model.rxnGeneMat(i,:));
-0371         for j=1:numel(J)
-0372             model.grRules{i}=[model.grRules{i} '(' model.genes{J(j)} ')'];
-0373             if j<numel(J)
-0374                 model.grRules{i}=[model.grRules{i} ' or '];
-0375             end
-0376         end
-0377     end
-0378 end
-0379 
-0380 %Find all genes that are not used and delete them
-0381 I=sum(model.rxnGeneMat)==0;
-0382 model.genes(I)=[];
-0383 model.rxnGeneMat(:,I)=[];
-0384 if isfield(model,'geneShortNames')
-0385     model.geneShortNames(I)=[];
-0386 end
-0387 if isfield(model,'proteins')
-0388     model.proteins(I)=[];
-0389 end
-0390 if isfield(model,'geneMiriams')
-0391     model.geneMiriams(I)=[];
-0392 end
-0393 if isfield(model,'geneFrom')
-0394     model.geneFrom(I)=[];
-0395 end
-0396 if isfield(model,'geneComps')
-0397     model.geneComps(I)=[];
-0398 end
-0399 
-0400 %At this stage the model will contain some exchange reactions but probably
-0401 %not all (and maybe zero). This can be inconvenient, so all exchange
-0402 %reactions from the reference model are added, except for those which
-0403 %involve metabolites that are not in the model.
-0404 
-0405 %First delete and included exchange reactions in order to prevent the order
-0406 %from changing
-0407 model=removeReactions(model,getExchangeRxns(model));
-0408 
-0409 %Create a model with only the exchange reactions in refModel
-0410 excModel=removeReactions(refModel,setdiff(refModel.rxns,getExchangeRxns(refModel)),true,true);
-0411 
-0412 %Find the metabolites there which are not exchange metabolites and which do
-0413 %not exist in the output model
-0414 I=~ismember(excModel.mets,model.mets) & excModel.unconstrained==0;
-0415 
-0416 %Then find those reactions and delete them
-0417 [~, J]=find(excModel.S(I,:));
-0418 excModel=removeReactions(excModel,J,true,true);
-0419 
-0420 %Merge with the output model
-0421 model=mergeModels({model;excModel},'metNames');
-0422 model.id='INITModel';
-0423 model.name=['Automatically generated model for ' tissue];
-0424 if any(celltype)
-0425     model.name=[model.name ' - ' celltype];
-0426 end
-0427 
-0428 if printReport==true
-0429     printScores(model,'Final model statistics',hpaData,arrayData,tissue,celltype);
-0430 end
-0431 
-0432 %Add information about essential reactions and reactions included for
-0433 %gap-filling and return a taskReport
-0434 if ~isempty(taskStructure)
-0435     I=find(taskReport.ok); %Ignore failed tasks
-0436     for i=1:numel(I)
-0437         taskReport.essential{I(i),1}=cModel.rxns(essentialRxnMat(:,I(i)));
-0438         taskReport.gapfill{I(i),1}=refModelNoExc.rxns(addedRxnMat(:,i));
-0439     end
-0440 else
-0441     taskReport=[];
-0442 end
-0443 
-0444 %Fix grRules and reconstruct rxnGeneMat
-0445 [grRules,rxnGeneMat] = standardizeGrRules(model,true);
-0446 model.grRules = grRules;
-0447 model.rxnGeneMat = rxnGeneMat;
-0448 end
-0449 
-0450 %This is for printing a summary of a model
-0451 function [rxnS, geneS]=printScores(model,name,hpaData,arrayData,tissue,celltype)
-0452 [a, b]=scoreModel(model,hpaData,arrayData,tissue,celltype);
-0453 rxnS=mean(a);
-0454 geneS=mean(b(~isinf(b)));
-0455 fprintf([name ':\n']);
-0456 fprintf(['\t' num2str(numel(model.rxns)) ' reactions, ' num2str(numel(model.genes)) ' genes\n']);
-0457 fprintf(['\tMean reaction score: ' num2str(rxnS) '\n']);
-0458 fprintf(['\tMean gene score: ' num2str(geneS) '\n']);
-0459 fprintf(['\tReactions with positive scores: ' num2str(100*sum(a>0)/numel(a)) '%%\n\n']);
-0460 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/INIT/getINITSteps.html b/doc/INIT/getINITSteps.html deleted file mode 100644 index 65be54794..000000000 --- a/doc/INIT/getINITSteps.html +++ /dev/null @@ -1,210 +0,0 @@ - - - - Description of getINITSteps - - - - - - - - - -
Home > INIT > getINITSteps.m
- - - -

getINITSteps -

- -

PURPOSE ^

-
getINITSteps
- -

SYNOPSIS ^

-
function steps = getINITSteps(metsToIgnore, series)
- -

DESCRIPTION ^

-
 getINITSteps
-   Converts a reaction score to the gene expression (CPM or TPM) required 
-   to get that reaction score, if the GPR is only a single gene.
-   Useful function primarily in test cases, where you want to be able to
-   define the reaction scores of rxns, but need to send in gene expression.
-   Note that all combinations of steps will not work. In general, avoid 'exclude'
-   if you want to define new ways to run the algorithm.
-
-   metsToIgnore  Structure describing mets that can be removed from the model
-                 before running ftINIT, such as water etc.
-                 (optional, default [])
-       simpleMets
-           mets  Names of metabolites to remove
-           compsToKeep Compartments for which metabolites should be kept.
-   series        Describes the way to run ftINIT: 
-                 '1+1'          Standard behavior. Step 1 and 2 described in
-                                the paper are merged into 1.
-                 '2+1'          The 3-step procedure described in the paper.
-                                Faster and slightly less accurate than '1+1 steps'
-                 '1+0'          Same as '1+1 steps', but skips step 3 in described 
-                                in the paper. This will result in a model including 
-                                a lot of reactions without GPRs. It is particularly 
-                                useful for structural comparison, since the reactions 
-                                removed in step 3 may be a bit random and doesn't 
-                                really add any extra information. Faster than
-                                '1+1 steps'
-                 '2+0'          Same as '2+1 steps', but skips step 3 in described 
-                                in the paper. Faster and slightly less accurate 
-                                than '1+0 steps', but will yield similar results.
-                 'full'         1-step run - similar to the old tINIT version but 
-                                without simplifications. Accurate, but very slow.
-                                This is mainly used for testing purposes.
-                 (optional, default '1+1')
-
-   steps         Cell array of steps, used as input to ftINIT
-
- Usage: steps = getINITSteps(metsToIgnore, series)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function steps = getINITSteps(metsToIgnore, series)
-0002 % getINITSteps
-0003 %   Converts a reaction score to the gene expression (CPM or TPM) required
-0004 %   to get that reaction score, if the GPR is only a single gene.
-0005 %   Useful function primarily in test cases, where you want to be able to
-0006 %   define the reaction scores of rxns, but need to send in gene expression.
-0007 %   Note that all combinations of steps will not work. In general, avoid 'exclude'
-0008 %   if you want to define new ways to run the algorithm.
-0009 %
-0010 %   metsToIgnore  Structure describing mets that can be removed from the model
-0011 %                 before running ftINIT, such as water etc.
-0012 %                 (optional, default [])
-0013 %       simpleMets
-0014 %           mets  Names of metabolites to remove
-0015 %           compsToKeep Compartments for which metabolites should be kept.
-0016 %   series        Describes the way to run ftINIT:
-0017 %                 '1+1'          Standard behavior. Step 1 and 2 described in
-0018 %                                the paper are merged into 1.
-0019 %                 '2+1'          The 3-step procedure described in the paper.
-0020 %                                Faster and slightly less accurate than '1+1 steps'
-0021 %                 '1+0'          Same as '1+1 steps', but skips step 3 in described
-0022 %                                in the paper. This will result in a model including
-0023 %                                a lot of reactions without GPRs. It is particularly
-0024 %                                useful for structural comparison, since the reactions
-0025 %                                removed in step 3 may be a bit random and doesn't
-0026 %                                really add any extra information. Faster than
-0027 %                                '1+1 steps'
-0028 %                 '2+0'          Same as '2+1 steps', but skips step 3 in described
-0029 %                                in the paper. Faster and slightly less accurate
-0030 %                                than '1+0 steps', but will yield similar results.
-0031 %                 'full'         1-step run - similar to the old tINIT version but
-0032 %                                without simplifications. Accurate, but very slow.
-0033 %                                This is mainly used for testing purposes.
-0034 %                 (optional, default '1+1')
-0035 %
-0036 %   steps         Cell array of steps, used as input to ftINIT
-0037 %
-0038 % Usage: steps = getINITSteps(metsToIgnore, series)
-0039 if nargin < 1
-0040     metsToIgnore = [];
-0041 end
-0042 
-0043 if nargin < 2
-0044     series = '1+1';
-0045 end
-0046 
-0047 if strcmp(series,'1+1') %step 1 and 2 are joined
-0048     params1 = struct();
-0049     params1.MIPGap = 0.0004;
-0050     params1.TimeLimit = 120;
-0051     params2 = struct();
-0052     params2.MIPGap = 0.0030;
-0053     params2.TimeLimit = 5000;
-0054     params = {params1;params2};
-0055     params3 = struct();
-0056     params3.MIPGap = 0.0004;
-0057     params3.TimeLimit = 5;
-0058     paramsStep3 = {params3;params1;params2};
-0059     %The paramsStep3 involves a quick first run. The objective value is often
-0060     %small in the third step (~800), and 0.0004 of that is a very small number
-0061     %With this first step, the rough value of the objective function will be
-0062     %estimated, which will generate an absolute MIPGap limit that is much larger
-0063     %for the second iteration.
-0064     
-0065     steps = { ...
-0066         INITStepDesc(false, false, 'ignore', [1,1,1,1,1,1,1,0], metsToIgnore, params, {10;20}); ...
-0067         INITStepDesc(false, false, 'essential', [1,0,0,0,1,0,0,0], metsToIgnore, paramsStep3, {10;10;20}); ...
-0068         };
-0069 elseif strcmp(series,'2+1') %the 3 step process described in the ftINIT paper
-0070     params1 = struct();
-0071     params1.MIPGap = 0.0004;
-0072     params1.TimeLimit = 120;
-0073     params2 = struct();
-0074     params2.MIPGap = 0.0030;
-0075     params2.TimeLimit = 5000;
-0076     params = {params1;params2};
-0077     params3 = struct();
-0078     params3.MIPGap = 0.0004;
-0079     params3.TimeLimit = 5;
-0080     paramsStep3 = {params3;params1;params2};
-0081     %The paramsStep3 involves a quick first run. The objective value is often
-0082     %small in the third step (~800), and 0.0004 of that is a very small number
-0083     %With this first step, the rough value of the objective function will be
-0084     %estimated, which will generate an absolute MIPGap limit that is much larger
-0085     %for the second iteration.
-0086     
-0087     steps = { ...
-0088         INITStepDesc(true, true, 'ignore', [1,1,1,1,1,1,1,0], metsToIgnore, params, {10;20}); ...
-0089         INITStepDesc(false, false, 'essential', [1,1,1,1,1,1,1,0], metsToIgnore, params, {10;20}); ...
-0090         INITStepDesc(false, false, 'essential', [1,0,0,0,1,0,0,0], metsToIgnore, paramsStep3, {10;10;20}); ...
-0091         };
-0092 elseif strcmp(series,'1+0') %Joins step 1 and 2, skips step 3
-0093     params1 = struct();
-0094     params1.MIPGap = 0.0004;
-0095     params1.TimeLimit = 120;
-0096     params2 = struct();
-0097     params2.MIPGap = 0.0030;
-0098     params2.TimeLimit = 5000;
-0099     params = {params1;params2};
-0100     steps = { ...
-0101         INITStepDesc(false, false, 'ignore', [1,1,1,1,1,1,1,0], metsToIgnore, params, {10;20}); ...
-0102         };
-0103 elseif strcmp(series,'2+0') %Skips step 3
-0104     params1 = struct();
-0105     params1.MIPGap = 0.0004;
-0106     params1.TimeLimit = 120;
-0107     params2 = struct();
-0108     params2.MIPGap = 0.0030;
-0109     params2.TimeLimit = 5000;
-0110     params = {params1;params2};
-0111     steps = { ...
-0112         INITStepDesc(true, true, 'ignore', [1,1,1,1,1,1,1,0], metsToIgnore, params, {10;20}); ...
-0113         INITStepDesc(false, false, 'essential', [1,1,1,1,1,1,1,0], metsToIgnore, params, {10;20}); ...
-0114         };
-0115 elseif strcmp(series,'full') %Just one run, slow on large models, but this is the 'perfect' setup
-0116     params1 = struct();
-0117     params1.MIPGap = 0.0004;
-0118     params1.TimeLimit = 10000;
-0119     params = {params1};
-0120     steps = { ...
-0121         INITStepDesc(false, false, 'ignore', [0,0,0,0,0,0,0,0], [], params) ...
-0122         };
-0123 else
-0124     dispEM(['Invalid series in getINITSteps: ' series])
-0125 end
-0126 
-0127 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/INIT/groupRxnScores.html b/doc/INIT/groupRxnScores.html deleted file mode 100644 index 8d1887151..000000000 --- a/doc/INIT/groupRxnScores.html +++ /dev/null @@ -1,124 +0,0 @@ - - - - Description of groupRxnScores - - - - - - - - - -
Home > INIT > groupRxnScores.m
- - - -

groupRxnScores -

- -

PURPOSE ^

-
groupRxnScores
- -

SYNOPSIS ^

-
function newRxnScores = groupRxnScores(model, origRxnScores, origRxnIds, groupIds, origRxnsToZero)
- -

DESCRIPTION ^

-
 groupRxnScores
- This function sums up the reaction scores for all reactions that were merged 
- into one by the linear merge.
- 
- model          The model with linearly merged rxns.
- origRxnScores  The rxnScores from the model before the linear merge.
- origRxnIds     The rxn ids of the model before the linear merge.
- groupIds       The groupIds vector output from linearMerge.
-                There is one integer for each rxn in origRxnIds. 0 means
-                the reaction was merged. A non-zero integer means that the
-                reaction was merged with all other rxns having the same integer.
- origRxnsToZero A logical vector saying which of the original rxns that should not
-                be part of the problem. The way this is solved is that all 
-                such reactions have a rxnScore of 0. If any original rxnScore 
-                value should be zero (which is very unlikely) it is changed to 0.01.
-                If the sum of the rxnScores for a merged rxn becomes zero 
-                while some of them are nonzero, the new value will also be 0.01, 
-                to distinguish the rxn from rxns with only rxns to zero.
-                There are two reasons why we don't want zeros in the reaction 
-                scores unless these reactions should be ignored:
-                  1) we want to be able to separate those
-                  2) it is difficult to handle a zero value in the MILP - 
-                     the on/off of such a reaction can be random, so better 
-                     to fix it in one direction.
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function newRxnScores = groupRxnScores(model, origRxnScores, origRxnIds, groupIds, origRxnsToZero)
-0002 % groupRxnScores
-0003 % This function sums up the reaction scores for all reactions that were merged
-0004 % into one by the linear merge.
-0005 %
-0006 % model          The model with linearly merged rxns.
-0007 % origRxnScores  The rxnScores from the model before the linear merge.
-0008 % origRxnIds     The rxn ids of the model before the linear merge.
-0009 % groupIds       The groupIds vector output from linearMerge.
-0010 %                There is one integer for each rxn in origRxnIds. 0 means
-0011 %                the reaction was merged. A non-zero integer means that the
-0012 %                reaction was merged with all other rxns having the same integer.
-0013 % origRxnsToZero A logical vector saying which of the original rxns that should not
-0014 %                be part of the problem. The way this is solved is that all
-0015 %                such reactions have a rxnScore of 0. If any original rxnScore
-0016 %                value should be zero (which is very unlikely) it is changed to 0.01.
-0017 %                If the sum of the rxnScores for a merged rxn becomes zero
-0018 %                while some of them are nonzero, the new value will also be 0.01,
-0019 %                to distinguish the rxn from rxns with only rxns to zero.
-0020 %                There are two reasons why we don't want zeros in the reaction
-0021 %                scores unless these reactions should be ignored:
-0022 %                  1) we want to be able to separate those
-0023 %                  2) it is difficult to handle a zero value in the MILP -
-0024 %                     the on/off of such a reaction can be random, so better
-0025 %                     to fix it in one direction.
-0026 
-0027 
-0028 newRxnScores = zeros(length(model.rxns),1);
-0029 [~,ia,ib] = intersect(model.rxns,origRxnIds);
-0030 grpIdsMerged = nan(length(model.rxns),1);
-0031 grpIdsMerged(ia) = groupIds(ib);
-0032 %check if any of the original scores are 0, in that case change them to 0.01 (unlikely)
-0033 origRxnScores(origRxnScores == 0) = 0.01;
-0034 %Then set the rxn scores for rxns to zero to 0
-0035 origRxnScores(origRxnsToZero) = 0;
-0036 
-0037 %fill in original scores
-0038 newRxnScores(ia) = origRxnScores(ib);
-0039 
-0040 for i = 1:length(model.rxns)
-0041     %for reactions that are not merged with anything, just keep score as it is
-0042     if grpIdsMerged(i) ~= 0
-0043         %find all original rxns in the group
-0044         sel = groupIds == grpIdsMerged(i);
-0045         newRxnScores(i) = sum(origRxnScores(sel));
-0046         if (newRxnScores(i) == 0 && any(origRxnScores(sel) ~= 0))
-0047            %special unfortunate case, where the reactions happen to sum to 0 while some of them are nonzero
-0048            %set to 0.01 in this case (proabably pretty unusual)
-0049            newRxnScores(i) = 0.01;
-0050         end
-0051     end
-0052 end
-0053 
-0054 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/INIT/index.html b/doc/INIT/index.html deleted file mode 100644 index 86204bee2..000000000 --- a/doc/INIT/index.html +++ /dev/null @@ -1,29 +0,0 @@ - - - - Index for Directory INIT - - - - - - - - - - -
< Master indexIndex for INIT >
- -

Index for INIT

- -

Matlab files in this directory:

- -
 INITStepDesc
 ftINITftINIT
 ftINITFillGapsftINITFillGaps
 ftINITFillGapsForAllTasksftINITFillGapsForAllTasks
 ftINITFillGapsMILPftINITFillGapsMILP
 ftINITInternalAlgftINITInternalAlg
 getExprForRxnScoregetExprForRxnScore
 getINITModelgetINITModel_legacy
 getINITStepsgetINITSteps
 groupRxnScoresgroupRxnScores
 mergeLinearmergeLinear
 prepINITModelprepINITModel
 removeLowScoreGenesremoveLowScoreGenes Remove low-scoring genes from model.
 rescaleModelForINITrescaleModelForINIT
 reverseRxnsreverseRxns
 runINITrunINIT
 scoreComplexModelscoreComplexModel
- - - - -
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/INIT/mergeLinear.html b/doc/INIT/mergeLinear.html deleted file mode 100644 index 16467e80e..000000000 --- a/doc/INIT/mergeLinear.html +++ /dev/null @@ -1,281 +0,0 @@ - - - - Description of mergeLinear - - - - - - - - - -
Home > INIT > mergeLinear.m
- - - -

mergeLinear -

- -

PURPOSE ^

-
mergeLinear
- -

SYNOPSIS ^

-
function [reducedModel,origRxnIds,groupIds,reversedRxns]=mergeLinear(model, noMergeRxns)
- -

DESCRIPTION ^

-
 mergeLinear
-   Simplifies a model by merging rxns with linear dependencies. There are two
-   differences from the function in simplifyModel:
-   1) Here we return which reactions were merged
-   2) Here we allow reversible reactions to be merged as well, which will 
-      probably reduce the size of the model more.
-
-   model                 a model structure
-   noMergeRxns           Cell array with reaction IDs that are not allowed to be
-                         merged
-
-   reducedModel          an updated model structure
-   origRxnIds            Cell array: original rxn ids, used together with the groupIds variable
-   groupIds              Vector of ids: merged rxns have the same id, same length as origRxnIds
-                         0 means a reaction was not merged.
-   reversedRxns          Vector of booleans, saying for each rxn if it is reversed in the combined rxns.
-
- Usage: [reducedModel,origRxnIds,groupIds]=mergeLinear(model,noMergeRxns)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 function [reducedModel,origRxnIds,groupIds,reversedRxns]=mergeLinear(model, noMergeRxns)
-0002 % mergeLinear
-0003 %   Simplifies a model by merging rxns with linear dependencies. There are two
-0004 %   differences from the function in simplifyModel:
-0005 %   1) Here we return which reactions were merged
-0006 %   2) Here we allow reversible reactions to be merged as well, which will
-0007 %      probably reduce the size of the model more.
-0008 %
-0009 %   model                 a model structure
-0010 %   noMergeRxns           Cell array with reaction IDs that are not allowed to be
-0011 %                         merged
-0012 %
-0013 %   reducedModel          an updated model structure
-0014 %   origRxnIds            Cell array: original rxn ids, used together with the groupIds variable
-0015 %   groupIds              Vector of ids: merged rxns have the same id, same length as origRxnIds
-0016 %                         0 means a reaction was not merged.
-0017 %   reversedRxns          Vector of booleans, saying for each rxn if it is reversed in the combined rxns.
-0018 %
-0019 % Usage: [reducedModel,origRxnIds,groupIds]=mergeLinear(model,noMergeRxns)
-0020 
-0021 
-0022 reducedModel=model;
-0023 
-0024 
-0025 reducedModel.genes={};
-0026 reducedModel.rxnGeneMat=sparse(numel(reducedModel.rxns),0);
-0027 reducedModel.grRules(:)={''};
-0028 
-0029 if isfield(reducedModel,'geneShortNames')
-0030     reducedModel.geneShortNames={};
-0031 end
-0032 if isfield(reducedModel,'proteins')
-0033     reducedModel.proteins={};
-0034 end
-0035 if isfield(reducedModel,'geneMiriams')
-0036     reducedModel.geneMiriams={};
-0037 end
-0038 if isfield(reducedModel,'geneComps')
-0039     reducedModel.geneComps=[];
-0040 end
-0041 
-0042 nextGroupId = 1;
-0043 origRxnIds = reducedModel.rxns;
-0044 groupIds = zeros(numel(reducedModel.rxns),1);
-0045 reversedRxns = false(numel(reducedModel.rxns),1);
-0046 
-0047 %Loop through and iteratively group linear reactions
-0048 while 1
-0049     %Get the banned reaction indexes. Note that the indexes will change
-0050     %in each iteration, but the names will not as they won't be merged
-0051     %with any other reaction
-0052     bannedIndexes=getIndexes(reducedModel,noMergeRxns,'rxns');
-0053 
-0054     %Select all metabolites that are only present as reactants/products
-0055     %in one reaction
-0056     twoNonZero = find(sum(reducedModel.S ~= 0, 2) == 2);
-0057 
-0058     mergedSome=false;
-0059 
-0060     %Loop through each of them and see if the reactions should be
-0061     %merged
-0062     for i=1:numel(twoNonZero)
-0063         involvedRxns=find(reducedModel.S(twoNonZero(i),:));
-0064         %Check that we can have one positive and one negative
-0065         pos = sum(reducedModel.S(twoNonZero(i),involvedRxns).' > 0 | reducedModel.rev(involvedRxns));
-0066         neg = sum(reducedModel.S(twoNonZero(i),involvedRxns).' < 0 | reducedModel.rev(involvedRxns));
-0067         
-0068                 
-0069         %Check so that one or both of the reactions haven't been merged
-0070         %already
-0071         if numel(involvedRxns)==2 && isempty(intersect(bannedIndexes,involvedRxns)) && pos >= 1 && neg >= 1
-0072             %first, take care of a special case: If the first reaction is producing the metabolite and if it is reversible,
-0073             %and the second is also producing it and is not reversible, change the order - the code below will not work otherwise
-0074             if reducedModel.rev(involvedRxns(1)) && (~reducedModel.rev(involvedRxns(2))) && ...
-0075                (reducedModel.S(twoNonZero(i),involvedRxns(1)) > 0) && (reducedModel.S(twoNonZero(i),involvedRxns(2)) > 0)
-0076                 involvedRxns = flip(involvedRxns);
-0077             end
-0078             
-0079             %first make sure the first reaction is producing the metabolite
-0080             if reducedModel.S(twoNonZero(i),involvedRxns(1)) < 0
-0081                 %it is not producing the metabolite - fix that
-0082                 %first choice: use the second reaction as producer if it is producing
-0083                 if reducedModel.S(twoNonZero(i),involvedRxns(2)) > 0
-0084                     involvedRxns = flip(involvedRxns);%make the second the first
-0085                 else
-0086                     %now we know that the second reaction is not producing, so we can safely try to make the first a producer
-0087                     if reducedModel.rev(involvedRxns(1)) == 1
-0088                         [reducedModel,reversedRxns] = flipRxn(reducedModel, involvedRxns(1), groupIds, reversedRxns);
-0089                     else %ok, finally try to flip the second reaction
-0090                         if reducedModel.rev(involvedRxns(2)) == 1
-0091                             [reducedModel,reversedRxns] = flipRxn(reducedModel, involvedRxns(2), groupIds, reversedRxns);
-0092                             involvedRxns = flip(involvedRxns);%make the second the first
-0093                         else
-0094                             error('We should never end up here!');
-0095                         end
-0096                     end
-0097                 end
-0098             end
-0099             %Now, make sure the second rxn is a consumer
-0100             if reducedModel.S(twoNonZero(i),involvedRxns(2)) > 0
-0101                 if reducedModel.rev(involvedRxns(2)) == 1
-0102                     [reducedModel,reversedRxns] = flipRxn(reducedModel, involvedRxns(2), groupIds, reversedRxns);
-0103                 else
-0104                     error('We should never end up here!');
-0105                 end
-0106             end
-0107 
-0108             %Calculate how many times the second reaction has to be
-0109             %multiplied before being merged with the first
-0110             stoichRatio=abs(reducedModel.S(twoNonZero(i),involvedRxns(1))/reducedModel.S(twoNonZero(i),involvedRxns(2)));
-0111 
-0112             %Add the second to the first
-0113             reducedModel.S(:,involvedRxns(1))=reducedModel.S(:,involvedRxns(1))+reducedModel.S(:,involvedRxns(2))*stoichRatio;
-0114 
-0115             %Clear the second reaction
-0116             reducedModel.S(:,involvedRxns(2))=0;
-0117 
-0118             %This is to prevent numerical issues. It should be 0
-0119             %already
-0120             reducedModel.S(twoNonZero(i),involvedRxns(1))=0;
-0121 
-0122             %At this point the second reaction is certain to be deleted
-0123             %in a later step and can therefore be ignored
-0124 
-0125             %Recalculate the bounds for the new reaction. This can be
-0126             %problematic since the scale of the bounds may change
-0127             %dramatically. Let the most constraining reaction determine
-0128             %the new bound
-0129             lb1=reducedModel.lb(involvedRxns(1));
-0130             lb2=reducedModel.lb(involvedRxns(2));
-0131             ub1=reducedModel.ub(involvedRxns(1));
-0132             ub2=reducedModel.ub(involvedRxns(2));
-0133 
-0134             if lb2~=-inf
-0135                 reducedModel.lb(involvedRxns(1))=max(lb1,lb2/stoichRatio);
-0136             end
-0137             if ub2~=inf
-0138                 reducedModel.ub(involvedRxns(1))=min(ub1,ub2/stoichRatio);
-0139             end
-0140             
-0141             %take care of the .rev flag - it could be that the combined rxn changes from rev to irrev
-0142             reducedModel.rev(involvedRxns(1)) = reducedModel.rev(involvedRxns(1))*reducedModel.rev(involvedRxns(2));%this is a way to do an "and" operation with 0 and 1 numbers
-0143 
-0144             %Then recalculate the objective coefficient. The resulting
-0145             %coefficient is the weighted sum of the previous
-0146             reducedModel.c(involvedRxns(1))=reducedModel.c(involvedRxns(1))+reducedModel.c(involvedRxns(2))*stoichRatio;
-0147 
-0148             %store which reactions that have been merged
-0149             rxnInd1 = find(strcmp(origRxnIds, reducedModel.rxns(involvedRxns(1))));
-0150             rxnInd2 = find(strcmp(origRxnIds, reducedModel.rxns(involvedRxns(2))));
-0151             grpId = max(groupIds(rxnInd1),groupIds(rxnInd2));
-0152             if grpId == 0
-0153                grpId = nextGroupId;
-0154                nextGroupId = nextGroupId + 1;
-0155             end
-0156 
-0157             if groupIds(rxnInd1) ~= grpId
-0158                if groupIds(rxnInd1) == 0
-0159                    %not merged before, just set the group id
-0160                    groupIds(rxnInd1) = grpId;
-0161                else
-0162                    %merged before - all rxns with the same group id should be changed
-0163                    groupIds(groupIds == groupIds(rxnInd1)) = grpId;
-0164                end
-0165             end
-0166             if groupIds(rxnInd2) ~= grpId
-0167                if groupIds(rxnInd2) == 0
-0168                    %not merged before, just set the group id
-0169                    groupIds(rxnInd2) = grpId;
-0170                else
-0171                    %merged before - all rxns with the same group id should be changed
-0172                    groupIds(groupIds == groupIds(rxnInd2)) = grpId;
-0173                end
-0174             end
-0175 
-0176             %Iterate again
-0177             mergedSome=true;
-0178         end
-0179     end
-0180 
-0181     %All possible reactions merged
-0182     if mergedSome==false
-0183         break;
-0184     end
-0185 
-0186     %Now delete all reactions that involve no metabolites
-0187     I=find(sum(reducedModel.S~=0,1)==0);
-0188 
-0189     %Remove reactions
-0190     reducedModel=removeReactions(reducedModel,I);
-0191 
-0192     %Remove metabolites
-0193     notInUse=sum(reducedModel.S~=0,2)==0;
-0194     reducedModel=removeMets(reducedModel,notInUse);
-0195 end
-0196     
-0197 function [model1,reversedRxns1] = flipRxn(model1, rxnInd, groupIds1, reversedRxns1)
-0198     model1.S(:,rxnInd) = model1.S(:,rxnInd)*-1;
-0199     %swap the bounds
-0200     ub = model1.ub(rxnInd);
-0201     model1.ub(rxnInd) = -model1.lb(rxnInd);
-0202     model1.lb(rxnInd) = -ub;
-0203     %flip the objective
-0204     model1.c(rxnInd) = -model1.c(rxnInd);
-0205     
-0206     %now take care of the reversedRxns - if this is a group, reverse all of the
-0207     %reactions in the group in the reversedRxns index - they will all be reversed at the
-0208     %same time since they are the same rxn.
-0209     rxnIndices = rxnInd;
-0210     if groupIds1(rxnInd) > 0
-0211         rxnIndices = find(groupIds1 == groupIds1(rxnInd));
-0212     end
-0213     reversedRxns1(rxnIndices) = ~reversedRxns1(rxnIndices);
-0214 end
-0215 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/INIT/prepINITModel.html b/doc/INIT/prepINITModel.html deleted file mode 100644 index 5b70f0cd6..000000000 --- a/doc/INIT/prepINITModel.html +++ /dev/null @@ -1,407 +0,0 @@ - - - - Description of prepINITModel - - - - - - - - - -
Home > INIT > prepINITModel.m
- - - -

prepINITModel -

- -

PURPOSE ^

-
prepINITModel
- -

SYNOPSIS ^

-
function prepData = prepINITModel(origRefModel, taskStruct, spontRxnNames, convertGenes, customRxnsToIgnore, extComp, skipScaling)
- -

DESCRIPTION ^

-
 prepINITModel
-
- The purpose of this function is to run time-consuming calculation steps that are not
- dependent on the RNA-Seq data.
-
- origRefModel      The model to use. Expected to be something such as Human-GEM, 
-                   Mouse-GEM, etc.
- taskStruct        The essential tasks. Can be loaded with for example
-                   taskStruct = parseTaskList('../data/metabolicTasks_Essential.txt');
- spontRxnNames     The spontaneous rxns. (optional, default {})
- convertGenes      If true the genes are converted to gene names (from 
-                   ENSEMBL) (optional, default false)
- customRxnsToIgnore These reactions can be ignored in the ignore mask 
-                   (specifying b7=1) (optional, default = {})
- extComp           Name of the external compartment, typically 's' or 'e'. This
-                   is used for identifying exch and import rxns (optional, default = 'e')
- prepData          The resulting prepData structure which is used as input to ftINIT
- skipScaling       If true the scaling step is not run on the minimal model. The 
-                   scaling is there to remove large differences between the 
-                   stoichiometric coefficients within a reaction, since such
-                   differences creates numerical issues in the ftINIT algorithm 
-                   due to limitations in solver resolution. However,
-                   the current scaling step is also risky and may lead to that
-                   some reactions cannot carry flux, since it changes the stoichiometry
-                   of the reactions with large differences. If you experience problems
-                   where the solution is infeasible, it may be worth trying to turn off
-                   the scaling. Note that it is only the minModel that is scaled,
-                   the scaling will not be present in the final model.
-                   Default: (optional, default = false)
- 
- Usage: prepData = prepINITModel(origRefModel, taskStruct, spontRxnNames, convertGenes, customRxnsToIgnore, extComp)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function prepData = prepINITModel(origRefModel, taskStruct, spontRxnNames, convertGenes, customRxnsToIgnore, extComp, skipScaling)
-0002 % prepINITModel
-0003 %
-0004 % The purpose of this function is to run time-consuming calculation steps that are not
-0005 % dependent on the RNA-Seq data.
-0006 %
-0007 % origRefModel      The model to use. Expected to be something such as Human-GEM,
-0008 %                   Mouse-GEM, etc.
-0009 % taskStruct        The essential tasks. Can be loaded with for example
-0010 %                   taskStruct = parseTaskList('../data/metabolicTasks_Essential.txt');
-0011 % spontRxnNames     The spontaneous rxns. (optional, default {})
-0012 % convertGenes      If true the genes are converted to gene names (from
-0013 %                   ENSEMBL) (optional, default false)
-0014 % customRxnsToIgnore These reactions can be ignored in the ignore mask
-0015 %                   (specifying b7=1) (optional, default = {})
-0016 % extComp           Name of the external compartment, typically 's' or 'e'. This
-0017 %                   is used for identifying exch and import rxns (optional, default = 'e')
-0018 % prepData          The resulting prepData structure which is used as input to ftINIT
-0019 % skipScaling       If true the scaling step is not run on the minimal model. The
-0020 %                   scaling is there to remove large differences between the
-0021 %                   stoichiometric coefficients within a reaction, since such
-0022 %                   differences creates numerical issues in the ftINIT algorithm
-0023 %                   due to limitations in solver resolution. However,
-0024 %                   the current scaling step is also risky and may lead to that
-0025 %                   some reactions cannot carry flux, since it changes the stoichiometry
-0026 %                   of the reactions with large differences. If you experience problems
-0027 %                   where the solution is infeasible, it may be worth trying to turn off
-0028 %                   the scaling. Note that it is only the minModel that is scaled,
-0029 %                   the scaling will not be present in the final model.
-0030 %                   Default: (optional, default = false)
-0031 %
-0032 % Usage: prepData = prepINITModel(origRefModel, taskStruct, spontRxnNames, convertGenes, customRxnsToIgnore, extComp)
-0033 
-0034 
-0035 if nargin < 3
-0036     spontRxnNames = {}; 
-0037 end
-0038 
-0039 if nargin < 4
-0040     convertGenes = false; 
-0041 end
-0042 
-0043 if nargin < 5
-0044     customRxnsToIgnore = {}; 
-0045 end
-0046 
-0047 if nargin < 6
-0048     extComp = 'e';
-0049 end
-0050 
-0051 if nargin < 7
-0052     skipScaling = false;
-0053 end
-0054 disp('Step 1: Gene rules')
-0055 [origRefModel.grRules, origRefModel.rxnGeneMat] = standardizeGrRules(origRefModel, true);
-0056 
-0057 if convertGenes %For mouse we might want to translate in the opposite direction - this has to be done before calling this function in that case.
-0058     [origRefModel.grRules, origRefModel.genes, origRefModel.rxnGeneMat] = translateGrRules(origRefModel.grRules, 'Name');
-0059 end
-0060 
-0061 
-0062 % Get list of all dead-end/inacessible/constrained reactions in the model.
-0063 % We don't merge linear dependent reactions here, that will happen later.
-0064 % We also don't remove reversibility here, we don't want that in the final
-0065 % models produced. Therefore, this is done as a separate step.
-0066 % This takes quite some time to run
-0067 disp('Step 2: First simplification')
-0068 [~,deletedDeadEndRxns] = simplifyModel(origRefModel,true,false,true,true,true);
-0069 
-0070 % get reduced model
-0071 cModel = removeReactions(origRefModel,deletedDeadEndRxns,false,true);
-0072 
-0073 
-0074 %Then, run the tasks to find out which reactions are essential. These rxns
-0075 %will be forced to carry flux in the optimization later
-0076 
-0077 % determine reactions essential for tasks - takes ~10 min
-0078 % need to add boundary mets first - but only to a temporary model, we don't
-0079 % want those for further processing
-0080 disp('Step 3: Check tasks (~10 min)')
-0081 if ~isempty(taskStruct)
-0082     bModel = closeModel(cModel);
-0083     [taskReport, essentialRxnMat, ~, essentialFluxes] = checkTasks(bModel,[],true,false,true,taskStruct);
-0084 
-0085     %extract the essential rxns:
-0086     sel = sum(essentialRxnMat,2) > 0;
-0087     selInd = find(sel);
-0088     essentialRxns = bModel.rxns(selInd);%382 rxns for human-GEM
-0089 
-0090     %Find metabolites present in taskStruct. We want to avoid removing
-0091     %these metabolites from the final model (even though they may no longer
-0092     %participate in any reacitons) so that the final model is still able to
-0093     %complete all of the tasks without any errors.
-0094     taskMets = union(vertcat(taskStruct.inputs),vertcat(taskStruct.outputs));
-0095     taskMets = union(taskMets, parseRxnEqu(vertcat(taskStruct.equations)));
-0096     modelMets = strcat(cModel.metNames,'[',cModel.comps(cModel.metComps),']');
-0097     [inModel,metInd] = ismember(taskMets,modelMets);
-0098     essentialMetsForTasks = cModel.mets(metInd(inModel));%118 mets
-0099 
-0100     %Remove tasks that cannot be performed
-0101     taskStruct(taskReport.ok == false) = [];
-0102 
-0103 else
-0104     essentialRxns = {};
-0105     essentialMetsForTasks = {};
-0106     taskReport = {};
-0107 end
-0108 
-0109 
-0110 % remove metabolites separately to avoid removing those needed for tasks
-0111 unusedMets = cModel.mets(all(cModel.S == 0,2));%1248 in Human-GEM
-0112 cModel = removeMets(cModel, setdiff(unusedMets,essentialMetsForTasks));
-0113 
-0114 if ~isempty(taskStruct)
-0115 
-0116     %Here, we decide on a direction in which the essential reactions should be forced.
-0117     essentialRevDir = false(length(essentialRxns),1);
-0118     pp = zeros(length(essentialRxns),1);
-0119     nn = zeros(length(essentialRxns),1);
-0120     for i = 1:length(selInd)
-0121         pos = sum(essentialFluxes(selInd(i),essentialRxnMat(selInd(i),:)) > 0);
-0122         neg = sum(essentialFluxes(selInd(i),essentialRxnMat(selInd(i),:)) < 0);
-0123         essentialRevDir(i) = pos < neg;
-0124         pp(i) = pos;
-0125         nn(i) = neg;
-0126     end
-0127 
-0128     %sum(pp>0 & nn>0) %0, so it is not a big problem that different tasks share essential
-0129     %reactions but in different directions, at least no such cases exist now, so we ignore this for now.
-0130 
-0131     %Now create a minimal model for the MILP - we want to make this as small as we can, but we
-0132     %don't want to use this later when we create the final models - just for the first MILP.
-0133     %We don't want boundary metabolites in here either.
-0134 
-0135     %We do a trick with the essential rxns here:
-0136     %What we want is to get rid of the reversibility of the reactions, because reversible reactions require
-0137     %an integer each in the MILP, and we can also get the case that it may be cheaper to force flux in the wrong direction, which
-0138     %will probably not give the gap-filling of reactions that we want.
-0139     %So, we simply change the reversible reactions to irreversible, and flip their direction if the direction
-0140     %to force flux in is negative. We don't need to do anything else, runINIT will then handle all essential rxns
-0141     %as irreversible (and will not add any integers etc. for them).
-0142 
-0143     minModel1 = cModel;
-0144     %for the essential rxns where we should force flux in the positive direction, just make them irreversible
-0145     %for the negative direction, we do the same, but also flip the direction of the reaction
-0146 
-0147     %first flip the reactions with negative direction
-0148     %constructEquations(minModel1,minModel1.rxns(selInd(essentialRevDir))) %looks good
-0149     minModel1 = reverseRxns(minModel1, minModel1.rxns(selInd(essentialRevDir)));
-0150     %constructEquations(minModel2,minModel2.rxns(selInd(essentialRevDir))) %looks good
-0151 
-0152     %Then make them irreversible
-0153     minModel1.rev(selInd) = 0;
-0154     minModel1.lb(selInd) = 0;
-0155 else
-0156     minModel1 = cModel;
-0157 end
-0158 %Now, remove reversibility on any reactions that can only be run in one direction - that simplifies the problem
-0159 %This takes a long time to run (at least an hour or so).
-0160 %This is an important step, we go from 5533 to 3734 reversible rxns, which reduces the size of the MILP,
-0161 %since irreversible rxns are easier to handle.
-0162 disp('Step 4: Second simplification (~1 hour)')
-0163 minModel2 = simplifyModel(minModel1,false,false,false,false,false,false,true);
-0164 
-0165 disp('Step 5: Final work')
-0166 
-0167 %Now, merge all linear dependent rxns - this reduces the size of the model a lot.
-0168 %Size goes from 11888 rxns to 7922 rxns for human-GEM, so this is an important step
-0169 [minModel3,origRxnIds,groupIds]=mergeLinear(minModel2, {});
-0170 
-0171 %we now need to figure out what happened to the essential rxns in the merge step above.
-0172 %Note that it would be ideal to run checkTasks on the result from mergeLinear, but that doesn't work.
-0173 %The exchange rxns have in many cases been merged with other reactions, making it difficult to run
-0174 %the tasks. So, instead we run checkTasks before, and figure out which merged reactions the
-0175 %essential reactions belong to now
-0176 
-0177 %It may be possible to create a minModel2b, run mergeLinear on that (which is quick), and
-0178 %then run checkTasks on the minimized model. Would be good to check if this gives the
-0179 %same result, I'm not sure. The code would get less complicated.
-0180 
-0181 
-0182 if ~isempty(taskStruct)
-0183 
-0184     %find all potential rxns
-0185     rxnIndOrig = ismember(origRxnIds, essentialRxns);
-0186     ids = unique(groupIds(rxnIndOrig));
-0187     ids = ids(ids > 0);%0 means it has not been merged
-0188     rxnCandidates = unique([essentialRxns;origRxnIds(ismember(groupIds, ids))]);%388, essentialRxns is 382
-0189     newEssentialRxns = minModel3.rxns(ismember(minModel3.rxns,rxnCandidates));%196 in Human-GEM
-0190     %setdiff(newEssentialRxns, essentialRxns)%only 2, that is very few
-0191     %setdiff(essentialRxns, newEssentialRxns)%188, that is very many
-0192     %It is probably the case that many essential reactions are linearly dependent on one another, which makes sense.
-0193 else
-0194     newEssentialRxns = {};
-0195 end
-0196 %What is left now is to remove some rxns from the problem, such as exchange rxns and spontaneous rxns.
-0197 %We set the rxn scores of these to exactly 0, and make sure no other scores are zero.
-0198 %runINIT will then handle this, we do >0 and <0 to get positive and negative scores, the rest
-0199 %are not included in the problem.
-0200 %But, this has to happen in the scoring - we identify the reactions in the origrxns here, and then fix this
-0201 %in the scoring for each sample (the function groupRxnScores handles this and is run for each sample).
-0202 
-0203 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-0204 %identify the reactions to ignore in the minModel2
-0205 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-0206 
-0207 %Identify reactions that should be ignored by tINIT, i.e. tINIT will not remove these regardless of score
-0208 
-0209 
-0210 [~,exchRxnInd] = getExchangeRxns(minModel2);
-0211 toIgnoreExch = false(numel(minModel2.rxns),1);
-0212 toIgnoreExch(exchRxnInd) = true;
-0213 toIgnoreImportRxns = false(numel(minModel2.rxns),1);
-0214 toIgnoreSimpleTransp = false(numel(minModel2.rxns),1);
-0215 toIgnoreAdvTransp = false(numel(minModel2.rxns),1);
-0216 toIgnoreS = false(numel(minModel2.rxns),1);
-0217 
-0218 
-0219 
-0220 %sum(toIgnore) %1500 for Human-GEM
-0221 %find simple transport reactions with no GPRs:
-0222 %We really only skip the reactions with two metabolites
-0223 %where they are the same but different compartments - only skip the transport into the cell for now
-0224 numMets = sum(minModel2.S ~= 0, 1);
-0225 scomp = find(strcmp(minModel2.comps,extComp));
-0226 for i = 1:length(minModel2.rxns)
-0227     %check that it has no GPR and that the rxn has two metabolites
-0228     if strcmp(minModel2.grRules(i),'') && (numMets(i) == 2)
-0229       metsComps = minModel2.metComps(minModel2.S(:,i) ~= 0);
-0230       metNames = minModel2.metNames(minModel2.S(:,i) ~= 0);
-0231       if metsComps(1) ~= metsComps(2) && (metsComps(1) == scomp || metsComps(2) == scomp) %different compartments, one is the extComp
-0232           if strcmp(metNames{1}, metNames{2}) %the same metabolite, it is a transport reaction
-0233               toIgnoreImportRxns(i) = true;
-0234           end
-0235       elseif metsComps(1) ~= metsComps(2) %different compartments, no check for extComp
-0236           if strcmp(metNames{1}, metNames{2}) %the same metabolite, it is a transport reaction
-0237               toIgnoreSimpleTransp(i) = true;
-0238           end
-0239       end
-0240     else %check for advanced
-0241         metsInd = find(minModel2.S(:,i) ~= 0);
-0242         %check that we have an even number of mets that is larger than 2 and that we don't have a GPR
-0243         if rem(length(metsInd),2) == 0 && length(metsInd) > 2 && isempty(minModel2.grRules{i})
-0244             %Now check that we have pairs of metabolites that are transported
-0245             SVals = full(minModel2.S(metsInd,i));
-0246             metNames = minModel2.metNames(metsInd);
-0247             comps = minModel2.metComps(metsInd);
-0248             success = true;
-0249             while ~isempty(metNames)
-0250                 if length(metNames) < 2 %this should not happen
-0251                    error('We should never arrive here!');
-0252                 end
-0253                 metMatch = find(strcmp(metNames(2:length(metNames)),metNames{1})) + 1;
-0254                 if length(metMatch) ~= 1 %we want a match, and only one (if there is some other complex transport rxn, we skip that)
-0255                    success = false;
-0256                    break;
-0257                 end
-0258                 if (SVals(1) + SVals(metMatch)) ~= 0 %the stoichiometry is not right
-0259                    success = false;
-0260                    break;
-0261                 end
-0262                 if comps(1) == comps(metMatch) %they must be in different compartments (maybe this need not to be checked)
-0263                    success = false;
-0264                    break;
-0265                 end
-0266                 %now remove the pair and continue with the next
-0267                 SVals([1;metMatch]) = [];
-0268                 metNames([1;metMatch]) = [];
-0269                 comps([1;metMatch]) = [];
-0270             end
-0271             toIgnoreAdvTransp(i) = success;
-0272         end          
-0273     end
-0274 end
-0275 
-0276 %Spontaneous reactions:
-0277 toIgnoreSpont = ismember(minModel2.rxns, spontRxnNames);%only 10 rxns in human-GEM
-0278 
-0279 %rxns without GPRs in the s compartment (outside the cell)
-0280 sCompInd = find(strcmp(minModel2.comps, extComp));
-0281 for i = 1:length(minModel2.rxns)
-0282     metsInd = find(minModel2.S(:,i) ~= 0);
-0283     %check that it has more than 1 metabolite (not exch rxn) and no GPR
-0284     if length(metsInd) > 1 && isempty(minModel2.grRules{i})
-0285         if  all(minModel2.metComps(metsInd) == sCompInd)
-0286             toIgnoreS(i) = true;
-0287         end
-0288     end
-0289 end
-0290 
-0291 toIgnoreAllWithoutGPRs = cellfun(@isempty,minModel2.grRules);
-0292 
-0293 
-0294 %sum(toIgnore)%in total 2375 rxns in human-GEM
-0295 %sum(toIgnoreAllTransp)%in total 3337 rxns in human-GEM, so 1,000 more
-0296 
-0297 %Now, try to scale the model to become more favorable for the solver.
-0298 %In general, we try to make all fluxes as similar as possible.
-0299 %      There is room for improvement here, this function is pretty simple.
-0300 %      It only rescales reactions, while it would be possible to rescale
-0301 %      metabolites as well (ROS => kROS, albumin => millialbumin, etc., but
-0302 %      scaled freely with a mathematical method). It could potentially open up
-0303 %      for using less strict margins in the MILP, and make it run faster.
-0304 if (skipScaling)
-0305     scaledMinModel = minModel3;
-0306 else
-0307     scaledMinModel = rescaleModelForINIT(minModel3);
-0308     scaledMinModel.ub(scaledMinModel.ub > 0) = 1000;
-0309     scaledMinModel.lb(scaledMinModel.lb < 0) = -1000;
-0310 end
-0311 % create data structure with pre-processing results
-0312 prepData.taskReport = taskReport;
-0313 prepData.essentialRxns = newEssentialRxns; %essential rxns in the minModel
-0314 prepData.taskStruct = taskStruct;
-0315 prepData.refModel = cModel;
-0316 prepData.minModel = scaledMinModel;
-0317 prepData.refModelWithBM = closeModel(cModel); %do this here so we don't have to do this for each sample
-0318 prepData.groupIds = groupIds;
-0319 prepData.essentialMetsForTasks = essentialMetsForTasks;
-0320 
-0321 prepData.toIgnoreExch = toIgnoreExch;
-0322 prepData.toIgnoreImportRxns = toIgnoreImportRxns;
-0323 prepData.toIgnoreSimpleTransp = toIgnoreSimpleTransp;
-0324 prepData.toIgnoreAdvTransp = toIgnoreAdvTransp;
-0325 prepData.toIgnoreSpont = toIgnoreSpont;
-0326 prepData.toIgnoreS = toIgnoreS;
-0327 prepData.toIgnoreCustomRxns = ismember(minModel2.rxns, customRxnsToIgnore);
-0328 prepData.toIgnoreAllWithoutGPRs = toIgnoreAllWithoutGPRs;
-0329 
-0330 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/INIT/removeLowScoreGenes.html b/doc/INIT/removeLowScoreGenes.html deleted file mode 100644 index 06ff5320b..000000000 --- a/doc/INIT/removeLowScoreGenes.html +++ /dev/null @@ -1,372 +0,0 @@ - - - - Description of removeLowScoreGenes - - - - - - - - - -
Home > INIT > removeLowScoreGenes.m
- - - -

removeLowScoreGenes -

- -

PURPOSE ^

-
removeLowScoreGenes Remove low-scoring genes from model.
- -

SYNOPSIS ^

-
function [newModel,remGenes] = removeLowScoreGenes(model,geneScores,isozymeScoring,complexScoring)
- -

DESCRIPTION ^

-
removeLowScoreGenes  Remove low-scoring genes from model.
-
-   This function removes genes from a model based on their scores, a step
-   used by the tINIT package. The function recognizes and differentiates
-   between isozymes and subunits of an enzyme complex. Genes are removed
-   from each grRule, subject to the following conditions:
-       1) At least one gene must remain associated with the reaction
-       2) Genes involved in a complex (joined by ANDs) are not removed
-
- Usage:
-
-   [newModel,remGenes] = removeLowScoreGenes(model,geneScores,complexScoring);
-
- Inputs:
-
-   model           Model structure from which genes are to be removed.
-
-   geneScores      A vector of scores associated with the model genes.
-                   Genes with a positive score will remain in the model,
-                   whereas genes with a negative score will try to be
-                   removed.
-                   
-                   If all genes associated with a reaction have a negative
-                   score, then the least-negative gene will remain; if 
-                   there is a tie, one will be selected at random.
-
-                   If a negative-scoring gene is a subunit in a complex, 
-                   it will not be removed; however, the entire complex may
-                   be removed. See the following example cases:
-
-                    Original: G1 or (G2 and G3 and G4)
-                    Negative: G1, G2
-                         New: G2 and G3 and G4
-
-                    Original: G1 or (G2 and G3) or (G4 and G5)
-                    Negative: G1, G2
-                         New: G4 and G5     [using default complexScoring]
-
-                    Original: (G1 and (G2 or G3) and G4)
-                    Negative: G2
-                         New: (G1 and G3 and G4)
-
-   isozymeScoring  Method used to combine the scores of multiple isozymes;
-                   'min', 'max', 'median', or 'average'. 
-                   (optional, default 'max')
-
-   complexScoring  Method used to combine the scores of enzyme complex
-                   subunits: 'min', 'max', 'median', or 'average'. 
-                   (optional, default 'min')
-
- Outputs:
-
-   newModel        Model with updated gene, grRules, and rxnGeneMat fields
-                   after attemping to remove negative-score genes.
-
-   remGenes        A list of negative-score genes that were fully removed
-                   from the model. Negative-score genes that were removed
-                   from some grRules but not all will not be included in
-                   this list.
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 function [newModel,remGenes] = removeLowScoreGenes(model,geneScores,isozymeScoring,complexScoring)
-0002 %removeLowScoreGenes  Remove low-scoring genes from model.
-0003 %
-0004 %   This function removes genes from a model based on their scores, a step
-0005 %   used by the tINIT package. The function recognizes and differentiates
-0006 %   between isozymes and subunits of an enzyme complex. Genes are removed
-0007 %   from each grRule, subject to the following conditions:
-0008 %       1) At least one gene must remain associated with the reaction
-0009 %       2) Genes involved in a complex (joined by ANDs) are not removed
-0010 %
-0011 % Usage:
-0012 %
-0013 %   [newModel,remGenes] = removeLowScoreGenes(model,geneScores,complexScoring);
-0014 %
-0015 % Inputs:
-0016 %
-0017 %   model           Model structure from which genes are to be removed.
-0018 %
-0019 %   geneScores      A vector of scores associated with the model genes.
-0020 %                   Genes with a positive score will remain in the model,
-0021 %                   whereas genes with a negative score will try to be
-0022 %                   removed.
-0023 %
-0024 %                   If all genes associated with a reaction have a negative
-0025 %                   score, then the least-negative gene will remain; if
-0026 %                   there is a tie, one will be selected at random.
-0027 %
-0028 %                   If a negative-scoring gene is a subunit in a complex,
-0029 %                   it will not be removed; however, the entire complex may
-0030 %                   be removed. See the following example cases:
-0031 %
-0032 %                    Original: G1 or (G2 and G3 and G4)
-0033 %                    Negative: G1, G2
-0034 %                         New: G2 and G3 and G4
-0035 %
-0036 %                    Original: G1 or (G2 and G3) or (G4 and G5)
-0037 %                    Negative: G1, G2
-0038 %                         New: G4 and G5     [using default complexScoring]
-0039 %
-0040 %                    Original: (G1 and (G2 or G3) and G4)
-0041 %                    Negative: G2
-0042 %                         New: (G1 and G3 and G4)
-0043 %
-0044 %   isozymeScoring  Method used to combine the scores of multiple isozymes;
-0045 %                   'min', 'max', 'median', or 'average'.
-0046 %                   (optional, default 'max')
-0047 %
-0048 %   complexScoring  Method used to combine the scores of enzyme complex
-0049 %                   subunits: 'min', 'max', 'median', or 'average'.
-0050 %                   (optional, default 'min')
-0051 %
-0052 % Outputs:
-0053 %
-0054 %   newModel        Model with updated gene, grRules, and rxnGeneMat fields
-0055 %                   after attemping to remove negative-score genes.
-0056 %
-0057 %   remGenes        A list of negative-score genes that were fully removed
-0058 %                   from the model. Negative-score genes that were removed
-0059 %                   from some grRules but not all will not be included in
-0060 %                   this list.
-0061 %
-0062 
-0063 
-0064 if nargin < 3 || isempty(isozymeScoring)
-0065     isozymeScoring = 'max';
-0066 end
-0067 if nargin < 4
-0068     complexScoring = 'min';
-0069 end
-0070 
-0071 if ~isequal(size(model.genes),size(geneScores))
-0072     error('The dimensions of model genes and geneScores do not match.');
-0073 end
-0074 
-0075 % convert logical operators to symbols
-0076 grRules = model.grRules;
-0077 if any(contains(grRules,{'&','|'}))
-0078     symbolicRules = true;
-0079 else
-0080     symbolicRules = false;
-0081 end
-0082 grRules = regexprep(grRules,' and ',' & ');
-0083 grRules = regexprep(grRules,' or ',' | ');
-0084 
-0085 % get unique list of grRules
-0086 [uRules,~,rule_ind] = unique(grRules);
-0087 
-0088 % iterate through each rule
-0089 newRules = uRules;  %initialize newRules
-0090 for i = 1:numel(uRules)
-0091     if isempty(uRules{i}) || ~contains(uRules{i},'|')
-0092         continue
-0093     elseif contains(uRules{i},'&')
-0094         newRules{i} = processComplexRule(uRules{i},model.genes,geneScores,isozymeScoring,complexScoring);
-0095     else
-0096         newRules{i} = processSimpleRule(uRules{i},model.genes,geneScores,isozymeScoring,complexScoring);
-0097     end
-0098 end
-0099 
-0100 % re-map unique rules to model
-0101 newModel = model;
-0102 newModel.grRules = newRules(rule_ind);
-0103 
-0104 % restore original logical operator formatting if it was changed
-0105 if ~symbolicRules
-0106     newModel.grRules = regexprep(newModel.grRules, ' \| ', ' or ');
-0107     newModel.grRules = regexprep(newModel.grRules, ' & ', ' and ');
-0108 end
-0109 
-0110 % regenerate "genes" and "rxnGeneMat" model fields
-0111 [genes,rxnGeneMat] = getGenesFromGrRules(newModel.grRules);
-0112 
-0113 % determine which of the original genes were removed
-0114 remInd = ~ismember(model.genes,genes);
-0115 remGenes = model.genes(remInd);
-0116 
-0117 % Keep the retained genes in their original order rather than the sorted
-0118 % order returned by getGenesFromGrRules. Gene removal never introduces new
-0119 % genes, so the remaining genes are model.genes(~remInd). Preserving this
-0120 % order ensures the gene-associated fields trimmed below (geneShortNames,
-0121 % proteins, etc.), which are indexed by remInd, stay aligned with genes.
-0122 newModel.genes = model.genes(~remInd);
-0123 [~,reorderInd] = ismember(newModel.genes,genes);
-0124 newModel.rxnGeneMat = rxnGeneMat(:,reorderInd);
-0125 
-0126 if isfield(newModel,'geneShortNames')
-0127     newModel.geneShortNames(remInd) = [];
-0128 end
-0129 if isfield(newModel,'proteins')
-0130     newModel.proteins(remInd) = [];
-0131 end
-0132 if isfield(newModel,'geneMiriams')
-0133     newModel.geneMiriams(remInd) = [];
-0134 end
-0135 if isfield(newModel,'geneFrom')
-0136     newModel.geneFrom(remInd) = [];
-0137 end
-0138 if isfield(newModel,'geneComps')
-0139     newModel.geneComps(remInd) = [];
-0140 end
-0141 
-0142 
-0143 end
-0144 
-0145 
-0146 
-0147 function [updatedRule,rScore] = processSimpleRule(rule,genes,gScores,isozymeScoring,complexScoring)
-0148 % Either score or modify a reaction gene rule containig only ANDs or ORs.
-0149 %
-0150 % If the rule contains an enzyme complex (all ANDs), the complex will be
-0151 % scored based on the score of its subunits. Subunits without a score (NaN)
-0152 % will be excluded from the score calculation.
-0153 %
-0154 % If the rule contains only isozymes (all ORs), the negative-score genes
-0155 % will be removed from the rule. Isozymes without a score (NaN) will not be
-0156 % removed from the rule. The resuling rule will then be scored.
-0157 
-0158 
-0159 % get IDs and indices of genes involved in rule
-0160 ruleGenes = unique(regexp(rule,'[^&|\(\) ]+','match'));
-0161 [~,geneInd] = ismember(ruleGenes,genes);
-0162 
-0163 % rules with one or no genes remain unchanged
-0164 if numel(ruleGenes) < 2
-0165     rScore = gScores(geneInd);
-0166     updatedRule = rule;
-0167     return
-0168 end
-0169 
-0170 if ~contains(rule,'&')  % rule contains isozymes
-0171     
-0172     scoreMethod = isozymeScoring;
-0173     negInd = gScores(geneInd) < 0;  % NaNs will return false here
-0174     if all(negInd)
-0175         % get the least negative gene, adding a small random value to avoid a tie
-0176         [~,maxInd] = max(gScores(geneInd) + rand(size(geneInd))*(1e-8));
-0177         updatedRule = ruleGenes{maxInd};
-0178     elseif sum(~negInd) == 1
-0179         updatedRule = ruleGenes{~negInd};
-0180     else
-0181         updatedRule = strjoin(ruleGenes(~negInd),' | ');
-0182         if startsWith(rule,'(')
-0183             updatedRule = ['(',updatedRule,')'];
-0184         end
-0185     end
-0186     
-0187     % update ruleGenes and their indices
-0188     ruleGenes = unique(regexp(updatedRule,'[^&|\(\) ]+','match'));
-0189     [~,geneInd] = ismember(ruleGenes,genes);
-0190     
-0191 elseif ~contains(rule,'|')  % rule contains enzyme complex
-0192     scoreMethod = complexScoring;
-0193     updatedRule = rule;
-0194 else
-0195     error('This function cannot handle rules with both "OR" and "AND" expressions.');
-0196 end
-0197 
-0198 % score rule
-0199 switch lower(scoreMethod)
-0200     case 'min'
-0201         rScore = min(gScores(geneInd),[],'omitnan');
-0202     case 'max'
-0203         rScore = max(gScores(geneInd),[],'omitnan');
-0204     case 'median'
-0205         rScore = median(gScores(geneInd),'omitnan');
-0206     case 'average'
-0207         rScore = mean(gScores(geneInd),'omitnan');
-0208 end
-0209 
-0210 end
-0211 
-0212 
-0213 
-0214 function updatedRule = processComplexRule(rule,genes,gScores,isozymeScoring,complexScoring)
-0215 % Update reactions containing both AND and OR expressions.
-0216 %
-0217 % Negative-score genes will be removed if they are isozymic, whereas they
-0218 % will not be removed if they are part of an enzyme complex. However, if
-0219 % the enzyme complex has a negative score, the entire complex will be
-0220 % removed, as long as it is not the only remaining element in the rule.
-0221 
-0222 
-0223 % Specify phrases to search for in the grRule. These phrases will find
-0224 % genes grouped by all ANDs (first phrase) or all ORs (second phrase).
-0225 search_phrases = {'\([^&|\(\) ]+( & [^&|\(\) ]+)+\)', '\([^&|\(\) ]+( \| [^&|\(\) ]+)+\)'};
-0226 
-0227 % initialize some variables
-0228 subsets = {};  % subsets are groups of genes grouped by all ANDs or all ORs
-0229 c = 1;  % counter to keep track of the group (subset) number
-0230 r_orig = rule;  % record original rule to determine when it stops changing
-0231 for k = 1:100  % iterate some arbitrarily high number of times
-0232     for j = 1:length(search_phrases)
-0233         new_subset = regexp(rule,search_phrases{j},'match')';  % extract subsets
-0234         if ~isempty(new_subset)
-0235             subsets = [subsets; new_subset];  % append to list of subsets
-0236             subset_nums = arrayfun(@num2str,(c:length(subsets))','UniformOutput',false);  % get group numbers to be assigned to the new subsets, and convert to strings
-0237             rule = regexprep(rule,search_phrases{j},strcat('#',subset_nums,'#'),'once');  % replace the subsets in the expression with their group numbers (enclosed by "#"s)
-0238             c = c + length(new_subset);
-0239         end
-0240     end
-0241     if isequal(rule,r_orig)
-0242         break;  % stop iterating when rule stops changing
-0243     else
-0244         r_orig = rule;
-0245     end
-0246 end
-0247 subsets{end+1} = rule;  % add final state of rule as the last subset
-0248 
-0249 % score and update each subset, and append to gene list and gene scores
-0250 for i = 1:numel(subsets)
-0251     [subsets{i},subset_score] = processSimpleRule(subsets{i},genes,gScores,isozymeScoring,complexScoring);
-0252     gScores = [gScores; subset_score];
-0253     genes = [genes; {strcat('#',num2str(i),'#')}];
-0254 end
-0255 
-0256 % reconstruct the rule from its updated subsets
-0257 updatedRule = subsets{end};
-0258 for i = c-1:-1:1
-0259     updatedRule = regexprep(updatedRule,strcat('#',num2str(i),'#'),subsets{i});
-0260 end
-0261 
-0262 end
-0263 
-0264 
-0265
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/INIT/rescaleModelForINIT.html b/doc/INIT/rescaleModelForINIT.html deleted file mode 100644 index fab29af6b..000000000 --- a/doc/INIT/rescaleModelForINIT.html +++ /dev/null @@ -1,129 +0,0 @@ - - - - Description of rescaleModelForINIT - - - - - - - - - -
Home > INIT > rescaleModelForINIT.m
- - - -

rescaleModelForINIT -

- -

PURPOSE ^

-
rescaleModelForINIT
- -

SYNOPSIS ^

-
function model=rescaleModelForINIT(model, maxStoichDiff)
- -

DESCRIPTION ^

-
 rescaleModelForINIT
-
- The idea with this function is to rescale the MILP problem in ftINIT to avoid large differences
- in flux magnitudes between reactions. Such differences cause among other things
- difficulties regarding tolerances for integer variables.
- For now it just scales down all reactions with high stoichiometric coefficients
- There is room for improvement here - the best would be to convert mets such as albumin
- to instead represent 1/100 albumin - that would create much less extreme coefficients.
- This type of improvement is known as scaling in the literature around LPs and MILPs.
-
- model         the model to be modified (input and output)
- maxStoichVal  all reactions with stoichiometric coefficent higher than this 
-               will be scaled down. (optional, default 250)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function model=rescaleModelForINIT(model, maxStoichDiff)
-0002 % rescaleModelForINIT
-0003 %
-0004 % The idea with this function is to rescale the MILP problem in ftINIT to avoid large differences
-0005 % in flux magnitudes between reactions. Such differences cause among other things
-0006 % difficulties regarding tolerances for integer variables.
-0007 % For now it just scales down all reactions with high stoichiometric coefficients
-0008 % There is room for improvement here - the best would be to convert mets such as albumin
-0009 % to instead represent 1/100 albumin - that would create much less extreme coefficients.
-0010 % This type of improvement is known as scaling in the literature around LPs and MILPs.
-0011 %
-0012 % model         the model to be modified (input and output)
-0013 % maxStoichVal  all reactions with stoichiometric coefficent higher than this
-0014 %               will be scaled down. (optional, default 250)
-0015 
-0016 if (nargin < 2)
-0017     maxStoichDiff = 25;
-0018 end
-0019 
-0020 %Define maxMinRatio to be the ratio between the largest and smallest
-0021 %stoichiometric coefficients in each reaction.
-0022 %Scale all rxns with maxMinRatio > maxStoichDiff - just set all coeffs that are
-0023 %larger than maxStoichDiff*minVal to that value, and center the mean coeff to 1 for all rxns.
-0024 SAbs = abs(model.S);
-0025 for i = 1:numel(model.rxns)
-0026     tmp = SAbs(:,i);
-0027     tmp = tmp(tmp ~= 0);
-0028     mn = min(tmp);
-0029     %modify matrix
-0030     sign = ones(numel(model.mets),1);
-0031     sign(model.S(:,i) < 0) = -1;
-0032     sel = SAbs(:,i) > maxStoichDiff*mn;
-0033     model.S(sel,i) = sign(sel) .* maxStoichDiff*mn;
-0034 end
-0035 %center around 1
-0036 boolMat = model.S ~= 0;
-0037 absMat = abs(model.S);
-0038 rxnScales = sum(boolMat,1)./sum(absMat,1);
-0039 
-0040 model.S = model.S .* rxnScales;
-0041 
-0042 %{
-0043 if (nargin < 2)
-0044     maxStoichVal = 250;
-0045 end
-0046 
-0047 
-0048 %find all reactions containing high stoichiometry coefficients
-0049 maxCoeffs = max(model.S, [], 1);
-0050 rxnsToCheck = maxCoeffs > maxStoichVal;
-0051 
-0052 %for debugging:
-0053 %constructEquations(model, model.rxns(rxnsToCheck))
-0054 
-0055 rxnsToCheckInd = find(rxnsToCheck);
-0056 
-0057 %We just scale all reactions so they don't have a coefficient > maxStoichVal for now
-0058 
-0059 %do this with a loop, doesn't really matter
-0060 for rxnInd = rxnsToCheckInd
-0061     %find the lowest index which is not a pointless metabolite, such as H+, H2O etc.
-0062     rxnS = model.S(:,rxnInd);
-0063     %metInd = find(rxnS ~= 0);
-0064     
-0065     largestCoeff = max(abs(rxnS));
-0066     scaleFactor = maxStoichVal/largestCoeff;
-0067     model.S(:,rxnInd) = model.S(:,rxnInd) .* scaleFactor;
-0068 end
-0069 %}
-0070 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/INIT/reverseRxns.html b/doc/INIT/reverseRxns.html deleted file mode 100644 index abca5f469..000000000 --- a/doc/INIT/reverseRxns.html +++ /dev/null @@ -1,68 +0,0 @@ - - - - Description of reverseRxns - - - - - - - - - -
Home > INIT > reverseRxns.m
- - - -

reverseRxns -

- -

PURPOSE ^

-
reverseRxns
- -

SYNOPSIS ^

-
function model=reverseRxns(model, rxns)
- -

DESCRIPTION ^

-
 reverseRxns
- Reverses reactions
- model     the model to change (input/output)
- rxns      the rxns to reverse
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function model=reverseRxns(model, rxns)
-0002 % reverseRxns
-0003 % Reverses reactions
-0004 % model     the model to change (input/output)
-0005 % rxns      the rxns to reverse
-0006 
-0007 rxnInd = find(ismember(model.rxns,rxns));
-0008 
-0009 %reverse the reactions
-0010 model.S(:,rxnInd) = model.S(:,rxnInd)*-1;
-0011 %swap the bounds
-0012 ub = model.ub(rxnInd);
-0013 model.ub(rxnInd) = -model.lb(rxnInd);
-0014 model.lb(rxnInd) = -ub;
-0015 %flip the objective
-0016 model.c(rxnInd) = -model.c(rxnInd);
-0017 
-0018 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/INIT/runINIT.html b/doc/INIT/runINIT.html deleted file mode 100644 index 15cbb20d1..000000000 --- a/doc/INIT/runINIT.html +++ /dev/null @@ -1,445 +0,0 @@ - - - - Description of runINIT - - - - - - - - - -
Home > INIT > runINIT.m
- - - -

runINIT -

- -

PURPOSE ^

-
runINIT
- -

SYNOPSIS ^

-
function [outModel, deletedRxns, metProduction, fValue]=runINIT(model,rxnScores,presentMets,essentialRxns,prodWeight,allowExcretion,noRevLoops,params)
- -

DESCRIPTION ^

-
 runINIT
-    Generates a model using the INIT algorithm, based on proteomics and/or
-   transcriptomics and/or metabolomics and/or metabolic tasks. This is the 
-   original implementation, which is now replaced with ftINIT.
-
-   model           a reference model structure
-   rxnScores       a vector of scores for the reactions in the model.
-                   Positive scores are reactions to keep and negative
-                   scores are reactions to exclude (optional, default all 0.0)
-   presentMets     cell array with unique metabolite names that the model
-                   should produce (optional, default [])
-   essentialRxns   cell array of reactions that are essential and that
-                   have to be in the resulting model. This is normally
-                   used when fitting a model to task (see fitTasks) (optional,
-                   default [])
-   prodWeight      a score that determines the value of having
-                   net-production of metabolites. This is a way of having
-                   a more functional network as it provides a reason for
-                   including bad reactions for connectivity reasons. This
-                   score is for each metabolite, and the sum of these weights
-                   and the scores for the reactions is what is optimized
-                   (optional, default 0.5)
-   allowExcretion  true if excretion of all metabolites should be allowed.
-                   This results in fewer reactions being considered
-                   dead-ends, but all reactions in the resulting model may
-                   not be able to carry flux. If this is "false" then the
-                   equality constraints are taken from model.b. If the
-                   input model lacks exchange reactions then this should
-                   probably be "true", or a large proportion of the model
-                   would be excluded for connectivity reasons
-                   (optional, default false)
-   noRevLoops      true if reversible reactions should be constrained to
-                   only carry flux in one direction. This prevents
-                   reversible reactions from being wrongly assigned as
-                   connected (the forward and backward reactions can form a
-                   loop and therefore appear connected), but it makes the
-                   problem significantly more computationally intensive to
-                   solve (two more integer constraints per reversible reaction)
-                   (optional, default false)
-   params          parameter structure for use by optimizeProb
-
-   outModel        the resulting model structure
-   deletedRxns     reactions which were deleted by the algorithm
-   metProduction   array that indicates which of the
-                   metabolites in presentMets that could be
-                   produced
-                   -2: metabolite name not found in model
-                   -1: metabolite found, but it could not be produced
-                   1: metabolite could be produced
-   fValue          objective value (sum of (the negative of)
-                   reaction scores for the included reactions and
-                   prodWeight*number of produced metabolites)
-
-   This function is the actual implementation of the algorithm. See
-   getINITModel for a higher-level function for model reconstruction. See
-   PLoS Comput Biol. 2012;8(5):e1002518 for details regarding the
-   implementation.
-
- Usage: [outModel deletedRxns metProduction fValue]=runINIT(model,...
-           rxnScores,presentMets,essentialRxns,prodWeight,allowExcretion,...
-           noRevLoops,params)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function [outModel, deletedRxns, metProduction, fValue]=runINIT(model,rxnScores,presentMets,essentialRxns,prodWeight,allowExcretion,noRevLoops,params)
-0002 % runINIT
-0003 %    Generates a model using the INIT algorithm, based on proteomics and/or
-0004 %   transcriptomics and/or metabolomics and/or metabolic tasks. This is the
-0005 %   original implementation, which is now replaced with ftINIT.
-0006 %
-0007 %   model           a reference model structure
-0008 %   rxnScores       a vector of scores for the reactions in the model.
-0009 %                   Positive scores are reactions to keep and negative
-0010 %                   scores are reactions to exclude (optional, default all 0.0)
-0011 %   presentMets     cell array with unique metabolite names that the model
-0012 %                   should produce (optional, default [])
-0013 %   essentialRxns   cell array of reactions that are essential and that
-0014 %                   have to be in the resulting model. This is normally
-0015 %                   used when fitting a model to task (see fitTasks) (optional,
-0016 %                   default [])
-0017 %   prodWeight      a score that determines the value of having
-0018 %                   net-production of metabolites. This is a way of having
-0019 %                   a more functional network as it provides a reason for
-0020 %                   including bad reactions for connectivity reasons. This
-0021 %                   score is for each metabolite, and the sum of these weights
-0022 %                   and the scores for the reactions is what is optimized
-0023 %                   (optional, default 0.5)
-0024 %   allowExcretion  true if excretion of all metabolites should be allowed.
-0025 %                   This results in fewer reactions being considered
-0026 %                   dead-ends, but all reactions in the resulting model may
-0027 %                   not be able to carry flux. If this is "false" then the
-0028 %                   equality constraints are taken from model.b. If the
-0029 %                   input model lacks exchange reactions then this should
-0030 %                   probably be "true", or a large proportion of the model
-0031 %                   would be excluded for connectivity reasons
-0032 %                   (optional, default false)
-0033 %   noRevLoops      true if reversible reactions should be constrained to
-0034 %                   only carry flux in one direction. This prevents
-0035 %                   reversible reactions from being wrongly assigned as
-0036 %                   connected (the forward and backward reactions can form a
-0037 %                   loop and therefore appear connected), but it makes the
-0038 %                   problem significantly more computationally intensive to
-0039 %                   solve (two more integer constraints per reversible reaction)
-0040 %                   (optional, default false)
-0041 %   params          parameter structure for use by optimizeProb
-0042 %
-0043 %   outModel        the resulting model structure
-0044 %   deletedRxns     reactions which were deleted by the algorithm
-0045 %   metProduction   array that indicates which of the
-0046 %                   metabolites in presentMets that could be
-0047 %                   produced
-0048 %                   -2: metabolite name not found in model
-0049 %                   -1: metabolite found, but it could not be produced
-0050 %                   1: metabolite could be produced
-0051 %   fValue          objective value (sum of (the negative of)
-0052 %                   reaction scores for the included reactions and
-0053 %                   prodWeight*number of produced metabolites)
-0054 %
-0055 %   This function is the actual implementation of the algorithm. See
-0056 %   getINITModel for a higher-level function for model reconstruction. See
-0057 %   PLoS Comput Biol. 2012;8(5):e1002518 for details regarding the
-0058 %   implementation.
-0059 %
-0060 % Usage: [outModel deletedRxns metProduction fValue]=runINIT(model,...
-0061 %           rxnScores,presentMets,essentialRxns,prodWeight,allowExcretion,...
-0062 %           noRevLoops,params)
-0063 
-0064 if nargin<2
-0065     rxnScores=zeros(numel(model.rxns),1);
-0066 end
-0067 if isempty(rxnScores)
-0068     rxnScores=zeros(numel(model.rxns),1);
-0069 end
-0070 if nargin<3 || isempty(presentMets)
-0071     presentMets={};
-0072 else
-0073     presentMets=convertCharArray(presentMets);
-0074 end
-0075 if nargin<4 || isempty(essentialRxns)
-0076     essentialRxns={};
-0077 else
-0078     essentialRxns=convertCharArray(essentialRxns);
-0079 end
-0080 if nargin<5 || isempty(prodWeight)
-0081     prodWeight=0.5;
-0082 end
-0083 if nargin<6
-0084     allowExcretion=false;
-0085 end
-0086 if nargin<7
-0087     noRevLoops=false;
-0088 end
-0089 if nargin<8
-0090     params=[];
-0091 end
-0092 
-0093 if numel(presentMets)~=numel(unique(presentMets))
-0094     EM='Duplicate metabolite names in presentMets';
-0095     dispEM(EM);
-0096 end
-0097 
-0098 %Default is that the metabolites cannot be produced
-0099 if ~isempty(presentMets)
-0100     metProduction=ones(numel(presentMets),1)*-2;
-0101     presentMets=upper(presentMets);
-0102     pmIndexes=find(ismember(presentMets,upper(model.metNames)));
-0103     metProduction(pmIndexes)=-1; %Then set that they are at least found
-0104 else
-0105     metProduction=[];
-0106     pmIndexes=[];
-0107 end
-0108 
-0109 %The model should be in the reversible format and all relevant exchange
-0110 %reactions should be open
-0111 if isfield(model,'unconstrained')
-0112     EM='Exchange metabolites are still present in the model. Use simplifyModel if this is not intended';
-0113     dispEM(EM,false);
-0114 end
-0115 
-0116 %The irreversible reactions that are essential must have a flux and are
-0117 %therefore not optimized for using MILP, which reduces the problem size.
-0118 %However, reversible reactions must have a flux in one direction, so they
-0119 %have to stay in the problem. The essentiality constraint on reversible
-0120 %reactions is implemented in the same manner as for reversible reactions
-0121 %when noRevLoops==true, but with the additional constraint that C ub=-1.
-0122 %This forces one of the directions to be active.
-0123 revRxns=find(model.rev~=0);
-0124 essentialReversible=find(ismember(model.rxns(revRxns),essentialRxns));
-0125 essentialRxns=intersect(essentialRxns,model.rxns(model.rev==0));
-0126 
-0127 %Convert the model to irreversible
-0128 irrevModel=convertToIrrev(model);
-0129 rxnScores=[rxnScores;rxnScores(model.rev==1)];
-0130 %These are used if noRevLoops is true
-0131 if noRevLoops==true
-0132     forwardIndexes=find(model.rev~=0);
-0133     backwardIndexes=(numel(model.rxns)+1:numel(irrevModel.rxns))';
-0134 else
-0135     %Then they should only be used for essential reversible reactions
-0136     forwardIndexes=revRxns(essentialReversible);
-0137     backwardIndexes=essentialReversible+numel(model.rxns);
-0138 end
-0139 
-0140 %Get the indexes of the essential reactions and remove them from the
-0141 %scoring vector
-0142 essentialIndex=find(ismember(irrevModel.rxns,essentialRxns));
-0143 rxnScores(essentialIndex)=[];
-0144 
-0145 %Go through each of the presentMets (if they exist) and modify the S matrix
-0146 %so that each reaction which produces any of them also produces a
-0147 %corresponding fake metabolite and the opposite in the reverse direction.
-0148 
-0149 %This is to deal with the fact that there is no compartment info regarding
-0150 %the presentMets. This modifies the irrevModel structure, but that is fine
-0151 %since it's the model structure that is returned.
-0152 if any(pmIndexes)
-0153     irrevModel.metNames=upper(irrevModel.metNames);
-0154     metsToAdd.mets=strcat({'FAKEFORPM'},num2str(pmIndexes));
-0155     metsToAdd.metNames=metsToAdd.mets;
-0156     metsToAdd.compartments=irrevModel.comps{1};
-0157     
-0158     %There is no constraints on the metabolites yet, since maybe not all of
-0159     %them could be produced
-0160     irrevModel=addMets(irrevModel,metsToAdd);
-0161 end
-0162 
-0163 %Modify the matrix
-0164 for i=1:numel(pmIndexes)
-0165     %Get the matching mets
-0166     I=ismember(irrevModel.metNames,presentMets(pmIndexes(i)));
-0167     
-0168     %Find the reactions where any of them are used.
-0169     [~, K, L]=find(irrevModel.S(I,:));
-0170     
-0171     %This ugly loop is to avoid problems if a metabolite occurs several
-0172     %times in one reaction
-0173     KK=unique(K);
-0174     LL=zeros(numel(KK),1);
-0175     for j=1:numel(KK)
-0176         LL(j)=sum(L(K==KK(j)));
-0177     end
-0178     irrevModel.S(numel(irrevModel.mets)-numel(pmIndexes)+i,KK)=LL;
-0179 end
-0180 
-0181 %Some nice to have numbers
-0182 nMets=numel(irrevModel.mets);
-0183 nRxns=numel(irrevModel.rxns);
-0184 nEssential=numel(essentialIndex);
-0185 nNonEssential=nRxns-nEssential;
-0186 nonEssentialIndex=setdiff(1:nRxns,essentialIndex);
-0187 S=irrevModel.S;
-0188 
-0189 %Add so that each non-essential reaction produces one unit of a fake
-0190 %metabolite
-0191 temp=sparse(1:nRxns,1:nRxns,1);
-0192 temp(essentialIndex,:)=[];
-0193 S=[S;temp];
-0194 
-0195 %Add another set of reactions (will be binary) which also produce these
-0196 %fake metabolites, but with a stoichiometry of 1000
-0197 temp=sparse(1:nNonEssential,1:nNonEssential,1000);
-0198 temp=[sparse(nMets,nNonEssential);temp];
-0199 S=[S temp];
-0200 
-0201 %Add reactions for net-production of (real) metabolites
-0202 if prodWeight~=0
-0203     temp=[speye(nMets-numel(pmIndexes))*-1;sparse(nNonEssential+numel(pmIndexes),nMets-numel(pmIndexes))];
-0204     S=[S temp];
-0205     %To keep the number of reactions added like this
-0206     nNetProd=nMets-numel(pmIndexes);
-0207 else
-0208     nNetProd=0;
-0209 end
-0210 
-0211 %Add constraints so that reversible reactions can only be used in one
-0212 %direction. This is done by adding the fake metabolites A, B, C for each
-0213 %reversible reaction in the following manner
-0214 % forward: A + .. => ... backwards: B + ... => ... int1: C => 1000 A int2:
-0215 % C => 1000 B A ub=999.9 B ub=999.9 C lb=-1 int1 and int2 are binary
-0216 if any(forwardIndexes)
-0217     nRevBounds=numel(forwardIndexes);
-0218     
-0219     %Add the A metabolites for the forward reactions and the B metabolites
-0220     %for the reverse reactions
-0221     I=speye(numel(irrevModel.rxns))*-1;
-0222     temp=[I(forwardIndexes,:);I(backwardIndexes,:)];
-0223     
-0224     %Padding
-0225     temp=[temp sparse(size(temp,1),size(S,2)-numel(irrevModel.rxns))];
-0226     
-0227     %Add the int1 & int2 reactions that produce A and B
-0228     temp=[temp speye(nRevBounds*2)*1000];
-0229     
-0230     %And add that they also consume C
-0231     temp=[temp;[sparse(nRevBounds,size(S,2)) speye(nRevBounds)*-1 speye(nRevBounds)*-1]];
-0232     
-0233     %Add the new reactions and metabolites
-0234     S=[S sparse(size(S,1),nRevBounds*2)];
-0235     S=[S;temp];
-0236 else
-0237     nRevBounds=0;
-0238 end
-0239 
-0240 %Add so that the essential reactions must have a small flux and that the
-0241 %binary ones (and net-production reactions) may have zero flux. The integer
-0242 %reactions for reversible reactions have [0 1]
-0243 prob.blx=[irrevModel.lb;zeros(nNonEssential+nNetProd+nRevBounds*2,1)];
-0244 prob.blx(essentialIndex)=max(0.1,prob.blx(essentialIndex));
-0245 
-0246 %Add so that the binary ones and net-production reactions can have at the
-0247 %most flux 1.0
-0248 prob.bux=[irrevModel.ub;ones(nNonEssential+nNetProd+nRevBounds*2,1)];
-0249 
-0250 %Add that the fake metabolites must be produced in a small amount and that
-0251 %the A and B metabolites for reversible reactions can be [0 999.9] and C
-0252 %metabolites [-1 0]
-0253 prob.blc=[irrevModel.b(:,1);ones(nNonEssential,1);zeros(nRevBounds*2,1);ones(nRevBounds,1)*-1];
-0254 
-0255 %Add that normal metabolites can be freely excreted if
-0256 %allowExcretion==true, and that the fake ones can be excreted 1000 units at
-0257 %most. C metabolites for essential reversible reactions should have an
-0258 %upper bound of -1. If noRevLoops is false, then add this constraint for
-0259 %all the reactions instead.
-0260 if noRevLoops==true
-0261     revUB=zeros(nRevBounds,1);
-0262     revUB(essentialReversible)=-1;
-0263 else
-0264     revUB=ones(nRevBounds,1)*-1;
-0265 end
-0266 if allowExcretion==true
-0267     metUB=inf(nMets,1);
-0268 else
-0269     metUB=irrevModel.b(:,min(size(irrevModel.b,2),2));
-0270 end
-0271 prob.buc=[metUB;ones(nNonEssential,1)*1000;ones(nRevBounds*2,1)*999.9;revUB];
-0272 
-0273 %Add objective coefficients for the binary reactions. The negative is used
-0274 %since we're minimizing. The negative is taken for the prodWeight as well,
-0275 %in order to be consistent with the syntax that positive scores are good
-0276 prob.c=[zeros(nRxns,1);rxnScores;ones(nNetProd,1)*prodWeight*-1;zeros(nRevBounds*2,1)];
-0277 prob.a=S;
-0278 
-0279 % adapt problem structure for cobra-style solver
-0280 prob.c=[prob.c;zeros(size(prob.a,1),1)];
-0281 prob.A=[prob.a -speye(size(prob.a,1))];
-0282 prob.b=zeros(size(prob.a,1), 1);
-0283 prob.ub=[prob.bux; prob.buc];
-0284 prob.osense=1;
-0285 prob.csense=char(zeros(1,size(prob.a,1)));
-0286 prob.csense(:)='E';
-0287 
-0288 %We still don't know which of the presentMets that can be produced. Go
-0289 %through them, force production, and see if the problem can be solved
-0290 for i=1:numel(pmIndexes)
-0291     prob.blc(numel(irrevModel.mets)-numel(pmIndexes)+i)=1;
-0292     prob.lb=[prob.blx; prob.blc];
-0293     res=optimizeProb(prob,params);
-0294     isFeasible=checkSolution(res);
-0295     if ~isFeasible
-0296         %Reset the constraint again
-0297         prob.blc(numel(irrevModel.mets)-numel(pmIndexes)+i)=0;
-0298     else
-0299         %Metabolite produced
-0300         metProduction(pmIndexes(i))=1;
-0301     end
-0302 end
-0303 prob.lb=[prob.blx; prob.blc];
-0304 
-0305 %Add that the binary reactions may only take integer values.
-0306 prob.vartype = repmat('C', 1, size(prob.A, 2));
-0307 allInt=[(nRxns+1):(nRxns+nNonEssential) size(S,2)-nRevBounds*2+1:size(S,2)];
-0308 prob.vartype(allInt) = 'B';
-0309 
-0310 % solve problem
-0311 res=optimizeProb(prob,params);
-0312 
-0313 %Problem should not be infeasible, but it is possible that the time limit
-0314 %was reached before finding any solutions.
-0315 if ~checkSolution(res)
-0316     if strcmp(res.origStat, 'TIME_LIMIT')
-0317         EM='Time limit reached without finding a solution. Try increasing the TimeLimit parameter.';
-0318     else
-0319         EM='The problem is infeasible';
-0320     end
-0321     dispEM(EM);
-0322 end
-0323 
-0324 fValue=res.obj;
-0325 
-0326 %Get all reactions used in the irreversible model
-0327 usedRxns=(nonEssentialIndex(res.full(nRxns+1:nRxns+nNonEssential)<0.1))';
-0328 
-0329 %Map to reversible model IDs
-0330 usedRxns=[usedRxns(usedRxns<=numel(model.rxns));revRxns(usedRxns(usedRxns>numel(model.rxns))-numel(model.rxns))];
-0331 
-0332 %Then get the ones that are not used in either direction or is essential
-0333 I=true(numel(model.rxns),1);
-0334 I(usedRxns)=false;
-0335 I(essentialIndex)=false;
-0336 deletedRxns=model.rxns(I);
-0337 outModel=removeReactions(model,I,true,true);
-0338 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/INIT/scoreComplexModel.html b/doc/INIT/scoreComplexModel.html deleted file mode 100644 index 51ace0e59..000000000 --- a/doc/INIT/scoreComplexModel.html +++ /dev/null @@ -1,482 +0,0 @@ - - - - Description of scoreComplexModel - - - - - - - - - -
Home > INIT > scoreComplexModel.m
- - - -

scoreComplexModel -

- -

PURPOSE ^

-
scoreComplexModel
- -

SYNOPSIS ^

-
function [rxnScores, geneScores, hpaScores, arrayScores] = scoreComplexModel(model,hpaData,arrayData,tissue,celltype,noGeneScore,isozymeScoring,complexScoring,multipleCellScoring,hpaLevelScores)
- -

DESCRIPTION ^

-
 scoreComplexModel
-   Scores the reactions and genes in a model containing complex gene rules
-   based on expression data from HPA and/or gene arrays.
-
-   It is highly recommended that the model grRules are "cleaned" and
-   verified by the "cleanModelGeneRules" function prior to scoring the
-   model with scoreComplexModel.
-
-   model               a model structure
-   hpaData             HPA data structure from parseHPA (optional if arrayData is
-                       supplied, default [])
-   arrayData           gene expression data structure (optional if hpaData is
-                       supplied, default [])
-       genes           cell array with the unique gene names
-       tissues         cell array with the tissue names. The list may not be
-                       unique, as there can be multiple cell types per tissue
-       celltypes       cell array with the cell type names for each tissue
-       levels          GENESxTISSUES array with the expression level for
-                       each gene in each tissue/celltype. NaN should be
-                       used when no measurement was performed
-       threshold       a single value or a vector of gene expression 
-                       thresholds, above which genes are considered to be
-                       "expressed". (optional, by default, the mean expression
-                       levels of each gene across all tissues in arrayData
-                       will be used as the threshold values)
-   tissue              tissue to score for. Should exist in either
-                       hpaData.tissues or arrayData.tissues
-   celltype            cell type to score for. Should exist in either
-                       hpaData.celltypes or arrayData.celltypes for this
-                       tissue (optional, default is to use the max values
-                       among all the cell types for the tissue. Use [] if
-                       you want to supply more arguments)
-   noGeneScore         score for reactions without genes (optional, default -2)
-   isozymeScoring      determines how scores are calculated for reactions
-                       with multiple genes joined by "OR" expression(s)
-                       ('min', 'max', 'median', 'average')
-                       (optional, default 'max')
-   complexScoring      determines how scores are calculated for reactions
-                       with multiple genes joined by "AND" expression(s)
-                       ('min', 'max', 'median', 'average')
-                       (optional, default 'min')
-   multipleCellScoring determines how scores are calculated when several
-                       cell types are used ('max' or 'average')
-                       (optional, default 'max')
-   hpaLevelScores      structure with numerical scores for the expression
-                       level categories from HPA. The structure should have a
-                       "names" and a "scores" field (optional, see code for
-                       default scores)
-
-   rxnScores       scores for each of the reactions in model
-   geneScores      scores for each of the genes in model. Genes which are
-                   not in the dataset(s) have -Inf as scores
-   hpaScores       scores for each of the genes in model if only taking hpaData
-                   into account. Genes which are not in the dataset(s)
-                   have -Inf as scores
-   arrayScores     scores for each of the genes in model if only taking arrayData
-                   into account. Genes which are not in the dataset(s)
-                   have -Inf as scores
-
- Usage: [rxnScores, geneScores, hpaScores, arrayScores]=scoreComplexModel(...
-               model,hpaData,arrayData,tissue,celltype,noGeneScore,isozymeScoring,
-               complexScoring,multipleCellScoring,hpaLevelScores)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 function [rxnScores, geneScores, hpaScores, arrayScores] = scoreComplexModel(model,hpaData,arrayData,tissue,celltype,noGeneScore,isozymeScoring,complexScoring,multipleCellScoring,hpaLevelScores)
-0002 % scoreComplexModel
-0003 %   Scores the reactions and genes in a model containing complex gene rules
-0004 %   based on expression data from HPA and/or gene arrays.
-0005 %
-0006 %   It is highly recommended that the model grRules are "cleaned" and
-0007 %   verified by the "cleanModelGeneRules" function prior to scoring the
-0008 %   model with scoreComplexModel.
-0009 %
-0010 %   model               a model structure
-0011 %   hpaData             HPA data structure from parseHPA (optional if arrayData is
-0012 %                       supplied, default [])
-0013 %   arrayData           gene expression data structure (optional if hpaData is
-0014 %                       supplied, default [])
-0015 %       genes           cell array with the unique gene names
-0016 %       tissues         cell array with the tissue names. The list may not be
-0017 %                       unique, as there can be multiple cell types per tissue
-0018 %       celltypes       cell array with the cell type names for each tissue
-0019 %       levels          GENESxTISSUES array with the expression level for
-0020 %                       each gene in each tissue/celltype. NaN should be
-0021 %                       used when no measurement was performed
-0022 %       threshold       a single value or a vector of gene expression
-0023 %                       thresholds, above which genes are considered to be
-0024 %                       "expressed". (optional, by default, the mean expression
-0025 %                       levels of each gene across all tissues in arrayData
-0026 %                       will be used as the threshold values)
-0027 %   tissue              tissue to score for. Should exist in either
-0028 %                       hpaData.tissues or arrayData.tissues
-0029 %   celltype            cell type to score for. Should exist in either
-0030 %                       hpaData.celltypes or arrayData.celltypes for this
-0031 %                       tissue (optional, default is to use the max values
-0032 %                       among all the cell types for the tissue. Use [] if
-0033 %                       you want to supply more arguments)
-0034 %   noGeneScore         score for reactions without genes (optional, default -2)
-0035 %   isozymeScoring      determines how scores are calculated for reactions
-0036 %                       with multiple genes joined by "OR" expression(s)
-0037 %                       ('min', 'max', 'median', 'average')
-0038 %                       (optional, default 'max')
-0039 %   complexScoring      determines how scores are calculated for reactions
-0040 %                       with multiple genes joined by "AND" expression(s)
-0041 %                       ('min', 'max', 'median', 'average')
-0042 %                       (optional, default 'min')
-0043 %   multipleCellScoring determines how scores are calculated when several
-0044 %                       cell types are used ('max' or 'average')
-0045 %                       (optional, default 'max')
-0046 %   hpaLevelScores      structure with numerical scores for the expression
-0047 %                       level categories from HPA. The structure should have a
-0048 %                       "names" and a "scores" field (optional, see code for
-0049 %                       default scores)
-0050 %
-0051 %   rxnScores       scores for each of the reactions in model
-0052 %   geneScores      scores for each of the genes in model. Genes which are
-0053 %                   not in the dataset(s) have -Inf as scores
-0054 %   hpaScores       scores for each of the genes in model if only taking hpaData
-0055 %                   into account. Genes which are not in the dataset(s)
-0056 %                   have -Inf as scores
-0057 %   arrayScores     scores for each of the genes in model if only taking arrayData
-0058 %                   into account. Genes which are not in the dataset(s)
-0059 %                   have -Inf as scores
-0060 %
-0061 % Usage: [rxnScores, geneScores, hpaScores, arrayScores]=scoreComplexModel(...
-0062 %               model,hpaData,arrayData,tissue,celltype,noGeneScore,isozymeScoring,
-0063 %               complexScoring,multipleCellScoring,hpaLevelScores)
-0064 %
-0065 
-0066 
-0067 if nargin < 5
-0068     celltype = [];
-0069 end
-0070 if nargin < 6 || isempty(noGeneScore)
-0071     noGeneScore = -2;
-0072 end
-0073 if nargin < 7 || isempty(isozymeScoring)
-0074     isozymeScoring = 'max';
-0075 end
-0076 if nargin < 8 || isempty(complexScoring)
-0077     complexScoring = 'min';
-0078 end
-0079 if nargin < 9 || isempty(multipleCellScoring)
-0080     multipleCellScoring = 'max';
-0081 end
-0082 if nargin < 10
-0083     % The first four are for APE, the other ones for staining
-0084     hpaLevelScores.names = {'High' 'Medium' 'Low' 'None' 'Strong' 'Moderate' 'Weak' 'Negative' 'Not detected'};
-0085     hpaLevelScores.scores = [20 15 10 -8 20 15 10 -8 -8];
-0086 end
-0087 
-0088 if isempty(hpaData) && isempty(arrayData)
-0089     EM = 'Must supply hpaData, arrayData or both';
-0090     dispEM(EM);
-0091 end
-0092 if ~ismember(lower(isozymeScoring),{'min','max','median','average'})
-0093     EM = 'Valid options for isozymeScoring are "min", "max", "median", or "average"';
-0094     dispEM(EM);
-0095 end
-0096 if ~ismember(lower(complexScoring),{'min','max','median','average'})
-0097     EM = 'Valid options for complexScoring are "min", "max", "median", or "average"';
-0098     dispEM(EM);
-0099 end
-0100 if ~ismember(lower(multipleCellScoring),{'max','average'})
-0101     EM = 'Valid options for multipleCellScoring are "max" or "average"';
-0102     dispEM(EM);
-0103 end
-0104 
-0105 
-0106 % Throw an error if array data for only one tissue is supplied without
-0107 % specifying threshold values
-0108 if ~isempty(arrayData)
-0109     if numel(unique(arrayData.tissues)) < 2
-0110         if ~isfield(arrayData,'threshold') || isempty(arrayData.threshold)
-0111             EM = 'arrayData must contain measurements for at least two celltypes/tissues since the score is calculated based on the expression level compared to the overall average';
-0112             dispEM(EM);
-0113         end
-0114     end
-0115 end
-0116 
-0117 % Process arrayData.threshold if necessary
-0118 if isfield(arrayData,'threshold') && (numel(arrayData.threshold) == 1)
-0119     % if only a single gene threshold value is provided, then just
-0120     % duplicate this value for all genes.
-0121     arrayData.threshold = arrayData.threshold*ones(size(arrayData.genes));
-0122 end
-0123 
-0124 % This is so the code can ignore which combination of input data is used
-0125 if isempty(arrayData)
-0126     arrayData.genes={};
-0127     arrayData.tissues={};
-0128     arrayData.celltypes={};
-0129     arrayData.levels=[];
-0130     arrayData.threshold=[];
-0131 end
-0132 if isempty(hpaData)
-0133     hpaData.genes={};
-0134     hpaData.tissues={};
-0135     hpaData.celltypes={};
-0136     hpaData.levels={};
-0137     hpaData.types={};
-0138     hpaData.reliabilities={};
-0139     hpaData.gene2Level=[];
-0140     hpaData.gene2Type=[];
-0141     hpaData.gene2Reliability=[];
-0142 end
-0143 
-0144 % Check that the tissue exists
-0145 if ~ismember(upper(tissue),upper(hpaData.tissues)) && ~ismember(upper(tissue),upper(arrayData.tissues))
-0146     EM = 'The tissue name does not match';
-0147     dispEM(EM);
-0148 end
-0149 if any(celltype)
-0150     % Check that both data types has cell type defined if that is to be used
-0151     if ~isfield(hpaData,'celltypes') || ~isfield(arrayData,'celltypes')
-0152         EM = 'Both hpaData and arrayData must contain cell type information if cell type is to be used';
-0153         dispEM(EM);
-0154     end
-0155     if ~ismember(upper(celltype),upper(hpaData.celltypes)) && ~ismember(upper(celltype),upper(arrayData.celltypes))
-0156         EM = 'The cell type name does not match';
-0157         dispEM(EM);
-0158     end
-0159 end
-0160 
-0161 % Some preprocessing of the structures to increase efficiency
-0162 % Remove all tissues that are not the correct one
-0163 J = ~strcmpi(hpaData.tissues,tissue);
-0164 
-0165 %If cell type is supplied, then only keep that cell type
-0166 if any(celltype)
-0167     J = J | ~strcmpi(hpaData.celltypes,celltype);
-0168 end
-0169 
-0170 hpaData.tissues(J)=[];
-0171 if isfield(hpaData,'celltypes')
-0172     hpaData.celltypes(J)=[];
-0173 end
-0174 if isfield(hpaData,'gene2Level')
-0175     hpaData.gene2Level(:,J)=[];
-0176 end
-0177 if isfield(hpaData,'gene2Type')
-0178     hpaData.gene2Type(:,J)=[];
-0179 end
-0180 if isfield(hpaData,'gene2Reliability')
-0181     hpaData.gene2Reliability(:,J)=[];
-0182 end
-0183 
-0184 % Remove all genes from the structures that are not in model or that aren't
-0185 % measured in the tissue
-0186 if ~isempty(hpaData.genes) % This should not be necessary, but the summation is a 0x1 matrix and the other is []
-0187     I = ~ismember(hpaData.genes,model.genes) | sum(hpaData.gene2Level,2) == 0;
-0188 else
-0189     I = [];
-0190 end
-0191 hpaData.genes(I) = [];
-0192 if isfield(hpaData,'gene2Level')
-0193     hpaData.gene2Level(I,:) = [];
-0194 end
-0195 if isfield(hpaData,'gene2Type')
-0196     hpaData.gene2Type(I,:) = [];
-0197 end
-0198 if isfield(hpaData,'gene2Reliability')
-0199     hpaData.gene2Reliability(I,:) = [];
-0200 end
-0201 
-0202 I = strcmpi(arrayData.tissues,tissue);
-0203 % If cell type is supplied, then only keep that cell type
-0204 if any(celltype)
-0205     I = I & strcmpi(arrayData.celltypes,celltype);
-0206 end
-0207 
-0208 % Remove all genes from the structures that are not in model or that aren't
-0209 % measured in the tissue
-0210 J = ~ismember(arrayData.genes,model.genes) | all(isnan(arrayData.levels(:,I)),2);
-0211 arrayData.genes(J) = [];
-0212 arrayData.levels(J,:) = [];
-0213 if isfield(arrayData,'threshold')
-0214     arrayData.threshold(J) = [];
-0215 end
-0216 
-0217 % Calculate the scores for the arrayData. These scores are calculated for
-0218 % each genes from its fold change between the tissue/celltype(s) in question
-0219 % and all other celltypes, or the threshold if supplied. This is a lower
-0220 % quality data than protein abundance, since gene abundance is an indirect
-0221 % estimate of protein level. These scores are therefore only used for genes
-0222 % for which there is no HPA data available. The fold changes are transformed
-0223 % as min(5*log(x),10) for x > 1 and max(5*log(x),-5) for x < 1 in order to
-0224 % have negative scores for lower expressed genes and to scale the scores
-0225 % to have somewhat lower weights than the HPA scores
-0226 tempArrayLevels = arrayData.levels;
-0227 tempArrayLevels(isnan(tempArrayLevels)) = 0;
-0228 if isfield(arrayData,'threshold') && ~isempty(arrayData.threshold)
-0229     % if provided, the user-supplied expression threshold value(s) will be
-0230     % used as the "average" expression level to which each gene is compared
-0231     average = arrayData.threshold;
-0232 else
-0233     average = sum(tempArrayLevels,2)./sum(~isnan(arrayData.levels),2);
-0234 end
-0235 if strcmpi(multipleCellScoring,'max')
-0236     current = max(tempArrayLevels(:,I),[],2);
-0237 else
-0238     current = sum(tempArrayLevels(:,I),2)./sum(~isnan(arrayData.levels(:,I)),2);
-0239 end
-0240 if ~isempty(current)
-0241     aScores = 5*log(current./average);
-0242 else
-0243     aScores = [];
-0244 end
-0245 aScores(aScores > 0) = min(aScores(aScores > 0),10);
-0246 aScores(aScores < 0) = max(aScores(aScores < 0),-5);
-0247 aScores(isnan(aScores)) = -5;  % NaNs occur when gene expression is zero across all tissues
-0248 
-0249 % Map the HPA levels to scores
-0250 [I, J] = ismember(upper(hpaData.levels),upper(hpaLevelScores.names));
-0251 if ~all(I)
-0252     EM = 'There are expression level categories that do not match to hpaLevelScores';
-0253     dispEM(EM);
-0254 end
-0255 [K, L, M] = find(hpaData.gene2Level);
-0256 scores = hpaLevelScores.scores(J);
-0257 if strcmpi(multipleCellScoring,'max')
-0258     hScores = max(sparse(K,L,scores(M),numel(hpaData.genes),numel(hpaData.tissues)),[],2);
-0259 else
-0260     hScores = mean(sparse(K,L,scores(M),numel(hpaData.genes),numel(hpaData.tissues)),2);
-0261 end
-0262 
-0263 % Assign gene scores, prioritizing HPA (protein) data over arrayData (RNA)
-0264 geneScores = nan(numel(model.genes),1);
-0265 hpaScores = -Inf(numel(model.genes),1);
-0266 arrayScores = -Inf(numel(model.genes),1);
-0267 
-0268 [I, J] = ismember(model.genes,arrayData.genes);
-0269 geneScores(I) = aScores(J(I));
-0270 arrayScores(I) = aScores(J(I));
-0271 
-0272 [I, J] = ismember(model.genes,hpaData.genes);
-0273 geneScores(I) = hScores(J(I));
-0274 hpaScores(I) = hScores(J(I));
-0275 
-0276 
-0277 % To speed things up, only need to score each unique grRule once
-0278 [uRules,~,rule_ind] = unique(model.grRules);
-0279 uScores = nan(size(uRules));
-0280 
-0281 % convert logic operators to symbols
-0282 uRules = regexprep(uRules,' and ',' & ');
-0283 uRules = regexprep(uRules,' or ',' | ');
-0284 
-0285 % score based on presence/combination of & and | operators
-0286 for i = 1:numel(uRules)
-0287     if isempty(uRules{i})
-0288         uScores(i) = noGeneScore;
-0289     elseif contains(uRules{i},'&') && contains(uRules{i},'|')
-0290         uScores(i) = scoreComplexRule(uRules{i},model.genes,geneScores,isozymeScoring,complexScoring);
-0291     else
-0292         uScores(i) = scoreSimpleRule(uRules{i},model.genes,geneScores,isozymeScoring,complexScoring);
-0293     end
-0294 end
-0295 
-0296 % NaN reaction scores should be changed to the no-gene score
-0297 uScores(isnan(uScores)) = noGeneScore;
-0298 
-0299 % re-map unique rule scores to model
-0300 rxnScores = uScores(rule_ind);
-0301 
-0302 end
-0303 
-0304 
-0305 
-0306 function rScore = scoreSimpleRule(rule,genes,gScores,isozymeScoring,complexScoring)
-0307 %Score reactions with simple gene rules (those with all ANDs or all ORs).
-0308 
-0309 if ~contains(rule,'&')
-0310     scoreMethod = isozymeScoring;
-0311 elseif ~contains(rule,'|')
-0312     scoreMethod = complexScoring;
-0313 else
-0314     error('This function cannot handle complex gene rules.');
-0315 end
-0316 ruleGenes = unique(regexp(rule,'[^&|\(\) ]+','match'));
-0317 [~,geneInd] = ismember(ruleGenes,genes);
-0318 switch lower(scoreMethod)
-0319     case 'min'
-0320         rScore = min(gScores(geneInd),[],'omitnan');
-0321     case 'max'
-0322         rScore = max(gScores(geneInd),[],'omitnan');
-0323     case 'median'
-0324         rScore = median(gScores(geneInd),'omitnan');
-0325     case 'average'
-0326         rScore = mean(gScores(geneInd),'omitnan');
-0327 end
-0328 
-0329 end
-0330 
-0331 
-0332 
-0333 function rScore = scoreComplexRule(rule,genes,gScores,isozymeScoring,complexScoring)
-0334 %Score reactions with complex gene rules (those with both ANDs or ORs).
-0335 
-0336 % Specify phrases to search for in the grRule. These phrases will find
-0337 % genes grouped by all ANDs (first phrase) or all ORs (second phrase).
-0338 search_phrases = {'\([^&|\(\) ]+( & [^&|\(\) ]+)+\)', '\([^&|\(\) ]+( \| [^&|\(\) ]+)+\)'};
-0339 
-0340 % initialize some variables
-0341 subsets = {};  % subsets are groups of genes grouped by all ANDs or all ORs
-0342 c = 1;  % counter to keep track of the group (subset) number
-0343 r_orig = rule;  % record original rule to determine when it stops changing
-0344 for k = 1:100  % iterate some arbitrarily high number of times
-0345     for j = 1:length(search_phrases)
-0346         new_subset = regexp(rule,search_phrases{j},'match')';  % extract subsets
-0347         if ~isempty(new_subset)
-0348             subsets = [subsets; new_subset];  % append to list of subsets
-0349             subset_nums = arrayfun(@num2str,(c:length(subsets))','UniformOutput',false);  % get group numbers to be assigned to the new subsets, and convert to strings
-0350             rule = regexprep(rule,search_phrases{j},strcat('#',subset_nums,'#'),'once');  % replace the subsets in the expression with their group numbers (enclosed by "#"s)
-0351             c = c + length(new_subset);
-0352         end
-0353     end
-0354     if isequal(rule,r_orig)
-0355         break;  % stop iterating when rule stops changing
-0356     else
-0357         r_orig = rule;
-0358     end
-0359 end
-0360 subsets{end+1} = rule;  % add final state of rule as the last subset
-0361 
-0362 % score each subset and append to gene list and gene scores
-0363 for i = 1:numel(subsets)
-0364     gScores = [gScores; scoreSimpleRule(subsets{i},genes,gScores,isozymeScoring,complexScoring)];
-0365     genes = [genes; {strcat('#',num2str(i),'#')}];
-0366 end
-0367 
-0368 % the final subset score is the overall reaction score
-0369 rScore = gScores(end);
-0370 
-0371 end
-0372
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/alpha.png b/doc/alpha.png deleted file mode 100644 index c73de7b05000443a0842f2e915d30dc5efec0dd1..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 273 zcmV+s0q*{ZP)z zQ4WJJ2!`q6(c~&{CcFyX%{{O*3+<>*r)K@)L#;sgtx%hY2zp`w01>%5jgw&J!A6Ov z{oxj&d7k&j`4Qtd0>I2H(i=Rwz9Tqxf(W|?ki|=ctL(aA|es#WFKbc?zg4C=hd_}m12PXzTKJB+iB?u XpQ?QQ=I-(g00000NkvXXu0mjf#?^X; diff --git a/doc/c++.png b/doc/c++.png deleted file mode 100644 index 24f56e6293df813f7699555d0fdd0224a33bdac9..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 327 zcmeAS@N?(olHy`uVBq!ia0vp^0YJ>p!2~4#tiFE(NUrMq>1fP(BLp1!W^mpLQ_Wwp7rPrm~SUGa2r45^s&cKTi3W&@s7VZD}9S!LiPTl|j(*)-gYW;;XAZ?5N!pnK5hG z+s}VG5+xWO6mIF=yOWvujML^HlXZ+Yu?Qyj=7(iWd!%tXIGN|}`LH!?g3;OMg0piY zXCLcLf98Km#%@Dm=Gw_oB65#C&Ig=Xv$e7}bMZ3wpl2`Gw(%Wrdp_NvM0oStJBj<- zw>I9sUd+GU{%T3g&-nYj{hnNcohMx1C8q6LzjX6wt1Wi%t17>Iemh??{C9K})9DTU VtbG#CZUOzr;OXk;vd$@?2>_TKh~WSL diff --git a/doc/c.png b/doc/c.png deleted file mode 100644 index c39fbf0e25ee296c5da082458363c45d945e55ac..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 252 zcmVqm`?`neZy@-MWWPW6I1ran`JUPt^Pp2nEy;5sZWf01@dO#z`=%5EER@AM$q-T7II}~u7He5MzB*^2($9;r8$^sTRx!mG z*Y={Rp11gKlvQkAY5N${nZR6`uQXd6Q{e@Bh2dQhbZ(t1?070Ye8{5GRQ*|k);Is- zyZYFOBO(zQWDhg*y_Wu+*U+*r-a`3&yE1OHzojSttaK8#KYM}z0000 - - - Description of FSEOF - - - - - - - - - -
Home > core > FSEOF.m
- - - -

FSEOF -

- -

PURPOSE ^

-
FSEOF
- -

SYNOPSIS ^

-
function targets=FSEOF(model,biomassRxn,targetRxn,iterations,coefficient,outputFile)
- -

DESCRIPTION ^

-
 FSEOF
-   Implements the Flux Scanning based on Enforced Objective Flux algorithm.
-
- Input:
-   model           a model structure
-   biomassRxn      string with reaction ID of the biomass formation or
-                   growth reaction
-   targetRxn       string with reaction ID of target reaction
-   iterations      numeric indicating number of iterations (optional,
-                   default 10)
-   coefficient     numeric indicating ratio of optimal target reaction
-                   flux, must be less than 1 (optional, default 0.9)
-   outputFile      string with output filename (optional, default prints
-                   to command window)
-
- Output:
-   targets         structure with information for identified targets
-       logical     logical array indicating whether a model reaction was
-                   identified as target by FSEOF
-       slope       numeric array with FSEOF slopes for target reactions
-
- This function writes an tab-delimited file or prints to command window.
- If an output has been specified (targets), it will also generate a
- structure indicating for each model reaction whether it is identified by
- FSEOF as a target and the slope of the reaction when switching from
- biomass formation to product formation.
-
- Usage: targets = FSEOF(model, biomassRxn, targetRxn, iterations,...
-                   coefficient, outputFile)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function targets=FSEOF(model,biomassRxn,targetRxn,iterations,coefficient,outputFile)
-0002 % FSEOF
-0003 %   Implements the Flux Scanning based on Enforced Objective Flux algorithm.
-0004 %
-0005 % Input:
-0006 %   model           a model structure
-0007 %   biomassRxn      string with reaction ID of the biomass formation or
-0008 %                   growth reaction
-0009 %   targetRxn       string with reaction ID of target reaction
-0010 %   iterations      numeric indicating number of iterations (optional,
-0011 %                   default 10)
-0012 %   coefficient     numeric indicating ratio of optimal target reaction
-0013 %                   flux, must be less than 1 (optional, default 0.9)
-0014 %   outputFile      string with output filename (optional, default prints
-0015 %                   to command window)
-0016 %
-0017 % Output:
-0018 %   targets         structure with information for identified targets
-0019 %       logical     logical array indicating whether a model reaction was
-0020 %                   identified as target by FSEOF
-0021 %       slope       numeric array with FSEOF slopes for target reactions
-0022 %
-0023 % This function writes an tab-delimited file or prints to command window.
-0024 % If an output has been specified (targets), it will also generate a
-0025 % structure indicating for each model reaction whether it is identified by
-0026 % FSEOF as a target and the slope of the reaction when switching from
-0027 % biomass formation to product formation.
-0028 %
-0029 % Usage: targets = FSEOF(model, biomassRxn, targetRxn, iterations,...
-0030 %                   coefficient, outputFile)
-0031 
-0032 biomassRxn=char(biomassRxn);
-0033 targetRxn=char(targetRxn);
-0034 
-0035 if nargin<4
-0036     iterations=10;
-0037     coefficient=0.9;
-0038 end
-0039 
-0040 if nargin <5
-0041     coefficient=0.9;
-0042 end
-0043 
-0044 if nargin == 6
-0045     output=1;
-0046 else
-0047     output=0;
-0048 end
-0049 
-0050 %Find out the maximum theoretical yield of target reaction
-0051 model=setParam(model,'obj',targetRxn,1);
-0052 sol=solveLP(model,1);
-0053 targetMax=sol.f*coefficient;   % 90 percent of the theoretical yield
-0054 
-0055 model=setParam(model,'obj',biomassRxn,1);
-0056 
-0057 fseof.results=zeros(length(model.rxns),iterations);
-0058 fseof.target=zeros(length(model.rxns),1);
-0059 rxnDirection=zeros(length(model.rxns),1);
-0060 
-0061 %Enforce objective flux iteratively
-0062 for i=1:iterations
-0063     n=i*targetMax/iterations;
-0064     model=setParam(model,'lb',targetRxn,n);
-0065     
-0066     sol=solveLP(model,1);
-0067     
-0068     fseof.results(:,i)=sol.x;
-0069     
-0070     %Loop through all fluxes and identify the ones that increased upon the
-0071     %enforced objective flux
-0072     for j=1:length(fseof.results)
-0073         if fseof.results(j,1) > 0   %Check the positive fluxes
-0074             
-0075             if i == 1   %The initial round
-0076                 rxnDirection(j,1)=1;
-0077                 fseof.target(j,1)=1;
-0078             else
-0079                 
-0080                 if (fseof.results(j,i) > fseof.results(j,i-1)) & fseof.target(j,1)
-0081                     fseof.target(j,1)=1;
-0082                 else
-0083                     fseof.target(j,1)=0;
-0084                 end
-0085             end
-0086             
-0087         elseif fseof.results(j,1) < 0 %Check the negative fluxes
-0088             
-0089             if i == 1   %The initial round
-0090                 rxnDirection(j,1)=-1;
-0091                 fseof.target(j,1)=1;
-0092             else
-0093                 if (fseof.results(j,i) < fseof.results(j,i-1)) & fseof.target(j,1)
-0094                     fseof.target(j,1)=1;
-0095                 else
-0096                     fseof.target(j,1)=0;
-0097                 end
-0098             end
-0099             
-0100         end
-0101         
-0102     end
-0103 end
-0104 
-0105 %Generating output
-0106 formatSpec='%s\t%s\t%s\t%s\t%s\t%s\t%s\n';
-0107 if output == 1    %Output to a file
-0108     outputFile=char(outputFile);
-0109     fid=fopen(outputFile,'w');
-0110     fprintf(fid,formatSpec,'Slope','rowID','Enzyme ID','Enzyme Name','Subsystems','Direction','Gr Rule');
-0111 else              %Output to screen
-0112     fprintf(formatSpec,'Slope','rowID','Enzyme ID','Enzyme Name','Subsystems','Direction','Gr Rule');
-0113 end
-0114 
-0115 for num=1:length(fseof.target)
-0116     if fseof.target(num,1) == 1
-0117         A0=num2str(abs(fseof.results(num,iterations)-fseof.results(num,1))/abs(targetMax-targetMax/iterations)); %Slope calculation
-0118         A1=num2str(num);                                  %row ID
-0119         A2=char(model.rxns(num));                         %enzyme ID
-0120         A3=char(model.rxnNames(num));                     %enzyme Name
-0121         if isfield(model,'subSystems') && ~isempty(model.subSystems{num});
-0122             if ~any(cellfun(@(x) iscell(x), model.subSystems));
-0123                 subSys = cellfun(@(x) {x}, model.subSystems, 'uni', 0);
-0124             else
-0125                 subSys = model.subSystems;
-0126             end
-0127             A4=char(strjoin(subSys{num},';'));                   %Subsystems
-0128         else
-0129             A4='';
-0130         end
-0131         A5=num2str(model.rev(num)*rxnDirection(num,1));   %reaction Dirction
-0132         A6=char(model.grRules(num));                      %Gr Rule
-0133         if output == 1    %Output to a file
-0134             fprintf(fid,formatSpec,A0,A1,A2,A3,A4,A5,A6);
-0135         else              %Output screen
-0136             fprintf(formatSpec,A0,A1,A2,A3,A4,A5,A6);
-0137         end
-0138     end
-0139 end
-0140 
-0141 if output == 1    %Output to a file
-0142     fclose(fid);
-0143 end
-0144 
-0145 if nargout == 1
-0146     targets.logical=logical(fseof.target);
-0147     targets.slope=abs(fseof.results(:,iterations)-fseof.results(:,1))/abs(targetMax-targetMax/iterations); %Slope calculation
-0148 end
-0149 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/addExchangeRxns.html b/doc/core/addExchangeRxns.html deleted file mode 100644 index c1bdf99fa..000000000 --- a/doc/core/addExchangeRxns.html +++ /dev/null @@ -1,166 +0,0 @@ - - - - Description of addExchangeRxns - - - - - - - - - -
Home > core > addExchangeRxns.m
- - - -

addExchangeRxns -

- -

PURPOSE ^

-
addExchangeRxns
- -

SYNOPSIS ^

-
function [model, addedRxns]=addExchangeRxns(model,reactionType,mets)
- -

DESCRIPTION ^

-
 addExchangeRxns
-   Adds exchange reactions for some metabolites
-
-   model           a model structure
-   reactionType    the type of reactions to add
-                   'in'    input reactions
-                   'out'   output reactions
-                   'both'  reversible input/output reactions. Positive
-                   direction corresponds to output
-   mets            either a cell array of metabolite IDs, a logical vector
-                   with the same number of elements as metabolites in the model,
-                   or a vector of indexes to add for (optional, default model.mets)
-
-   model           updated model structure
-   addedRxns       ids of the added reactions
-
-   This is a faster version than addRxns when adding exchange reactions.
-   New reactions are named "metName exchange (OUT/IN/BOTH)" while reaction
-   ids are formatted as "EXC_OUT/IN/BOTH_METID".
-
- Usage: [model, addedRxns]=addExchangeRxns(model,reactionType,mets)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function [model, addedRxns]=addExchangeRxns(model,reactionType,mets)
-0002 % addExchangeRxns
-0003 %   Adds exchange reactions for some metabolites
-0004 %
-0005 %   model           a model structure
-0006 %   reactionType    the type of reactions to add
-0007 %                   'in'    input reactions
-0008 %                   'out'   output reactions
-0009 %                   'both'  reversible input/output reactions. Positive
-0010 %                   direction corresponds to output
-0011 %   mets            either a cell array of metabolite IDs, a logical vector
-0012 %                   with the same number of elements as metabolites in the model,
-0013 %                   or a vector of indexes to add for (optional, default model.mets)
-0014 %
-0015 %   model           updated model structure
-0016 %   addedRxns       ids of the added reactions
-0017 %
-0018 %   This is a faster version than addRxns when adding exchange reactions.
-0019 %   New reactions are named "metName exchange (OUT/IN/BOTH)" while reaction
-0020 %   ids are formatted as "EXC_OUT/IN/BOTH_METID".
-0021 %
-0022 % Usage: [model, addedRxns]=addExchangeRxns(model,reactionType,mets)
-0023 
-0024 if nargin<3
-0025     mets=model.mets;
-0026 elseif ~islogical(mets) && ~isnumeric(mets)
-0027     mets=convertCharArray(mets);
-0028 end
-0029 J=getIndexes(model,mets,'mets',false);
-0030 mets=model.mets(J);
-0031 
-0032 reactionType=char(upper(reactionType));
-0033 
-0034 %Production is positive for OUT and BOTH
-0035 if strcmp(reactionType,'IN')
-0036     I=speye(numel(model.mets));
-0037 else
-0038     I=speye(numel(model.mets))*-1;
-0039 end
-0040 I=I(:,J);
-0041 
-0042 %Add an I matrix which corresponds to production of all metabolites
-0043 model.S=[model.S I];
-0044 if strcmp(reactionType,'BOTH')
-0045     model.lb=[model.lb;ones(numel(J),1)*-1000];
-0046     model.rev=[model.rev;ones(numel(J),1)];
-0047 else
-0048     model.lb=[model.lb;zeros(numel(J),1)];
-0049     model.rev=[model.rev;zeros(numel(J),1)];
-0050 end
-0051 model.ub=[model.ub;ones(numel(J),1)*1000];
-0052 model.c=[model.c;zeros(numel(J),1)];
-0053 
-0054 filler=cell(numel(J),1);
-0055 filler(:)={''};
-0056 addedRxns=strcat('EXC_',reactionType,'_',mets);
-0057 addedRxnNames=strcat(model.metNames(J),' exchange (',reactionType,')');
-0058 model.rxns=[model.rxns;addedRxns];
-0059 model.rxnNames=[model.rxnNames;addedRxnNames];
-0060 
-0061 if isfield(model,'eccodes')
-0062     model.eccodes=[model.eccodes;filler];
-0063 end
-0064 if isfield(model,'subSystems')
-0065     fillerSub = filler;
-0066     if any(cellfun(@(x) iscell(x), model.subSystems))
-0067         fillerSub(:)={{''}};
-0068     end
-0069     model.subSystems=[model.subSystems;fillerSub];
-0070 end
-0071 if isfield(model,'grRules')
-0072     model.grRules=[model.grRules;filler];
-0073 end
-0074 if isfield(model,'rxnFrom')
-0075     model.rxnFrom=[model.rxnFrom;filler];
-0076 end
-0077 if isfield(model,'rxnMiriams')
-0078     model.rxnMiriams=[model.rxnMiriams;filler];
-0079 end
-0080 if isfield(model,'rxnGeneMat')
-0081     model.rxnGeneMat=[model.rxnGeneMat;sparse(numel(J),numel(model.genes))];
-0082 end
-0083 if isfield(model,'rxnComps')
-0084     model.rxnComps=[model.rxnComps;ones(numel(J),1)];
-0085     fprintf('NOTE: The exchange reactions are assigned to the first compartment\n');
-0086 end
-0087 if isfield(model,'rxnNotes')
-0088     model.rxnNotes=[model.rxnNotes;filler];
-0089 end
-0090 if isfield(model,'rxnReferences')
-0091     model.rxnReferences=[model.rxnReferences;filler];
-0092 end
-0093 if isfield(model,'rxnConfidenceScores')
-0094     model.rxnConfidenceScores=[model.rxnConfidenceScores;NaN(numel(J),1)];
-0095 end
-0096 if isfield(model,'rxnDeltaG')
-0097     model.rxnDeltaG=[model.rxnDeltaG;NaN(numel(J),1)];
-0098 end
-0099 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/addGenesRaven.html b/doc/core/addGenesRaven.html deleted file mode 100644 index 39d26818d..000000000 --- a/doc/core/addGenesRaven.html +++ /dev/null @@ -1,221 +0,0 @@ - - - - Description of addGenesRaven - - - - - - - - - -
Home > core > addGenesRaven.m
- - - -

addGenesRaven -

- -

PURPOSE ^

-
addGenesRaven
- -

SYNOPSIS ^

-
function newModel=addGenesRaven(model,genesToAdd)
- -

DESCRIPTION ^

-
 addGenesRaven
-   Adds genes to a model
-
-   model        a model structure
-   genesToAdd   the genes genesToAdd can have the following fields:
-                genes          cell array with unique strings that
-                               identifies each gene. Only character which are
-                               allowed in SBML ids are allowed (mainly a-z,
-                               0-9 and '_'). However, there is no check
-                               for this performed, as it only matters if
-                               the model should be exported to SBML
-                geneShortNames cell array of gene abbreviations (optional,
-                               default '')
-                geneMiriams    cell array with MIRIAM structures (optional,
-                               default [])
-                proteins   cell array of protein names associated to
-                               each gene (optional, default '')
-
-   newModel     an updated model structure
-
-   NOTE: This function does not make extensive checks about MIRIAM formats,
-   forbidden characters or such.
-
- Usage: newModel=addGenesRaven(model,genesToAdd)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function newModel=addGenesRaven(model,genesToAdd)
-0002 % addGenesRaven
-0003 %   Adds genes to a model
-0004 %
-0005 %   model        a model structure
-0006 %   genesToAdd   the genes genesToAdd can have the following fields:
-0007 %                genes          cell array with unique strings that
-0008 %                               identifies each gene. Only character which are
-0009 %                               allowed in SBML ids are allowed (mainly a-z,
-0010 %                               0-9 and '_'). However, there is no check
-0011 %                               for this performed, as it only matters if
-0012 %                               the model should be exported to SBML
-0013 %                geneShortNames cell array of gene abbreviations (optional,
-0014 %                               default '')
-0015 %                geneMiriams    cell array with MIRIAM structures (optional,
-0016 %                               default [])
-0017 %                proteins   cell array of protein names associated to
-0018 %                               each gene (optional, default '')
-0019 %
-0020 %   newModel     an updated model structure
-0021 %
-0022 %   NOTE: This function does not make extensive checks about MIRIAM formats,
-0023 %   forbidden characters or such.
-0024 %
-0025 % Usage: newModel=addGenesRaven(model,genesToAdd)
-0026 
-0027 newModel=model;
-0028 
-0029 if isempty(genesToAdd)
-0030     return;
-0031 end
-0032 
-0033 %Check some stuff regarding the required fields
-0034 if ~isfield(genesToAdd,'genes')
-0035     EM='genes is a required field in genesToAdd';
-0036     dispEM(EM);
-0037 else
-0038     genesToAdd.genes=convertCharArray(genesToAdd.genes);
-0039 end
-0040 
-0041 %Number of genes
-0042 nGenes=numel(genesToAdd.genes);
-0043 nOldGenes=numel(model.genes);
-0044 filler=cell(nGenes,1);
-0045 filler(:)={''};
-0046 largeFiller=cell(nOldGenes,1);
-0047 largeFiller(:)={''};
-0048 
-0049 %Check that no gene ids are already present in the model
-0050 I=ismember(genesToAdd.genes,model.genes);
-0051 if all(I)
-0052     warning('All genes in genesToAdd.genes are already present in model.genes');
-0053     return
-0054 elseif any(I)
-0055     existingGenes=strjoin(genesToAdd.genes(I), ', ');
-0056     warning(['The following genes are already present in model.genes and will therefore not be added: ', existingGenes])
-0057     genesToAdd.genes(I)=[];
-0058     if isfield(genesToAdd,'geneShortNames')
-0059         genesToAdd.geneShortNames(I)=[];
-0060     end
-0061     if isfield(genesToAdd,'proteins')
-0062         genesToAdd.proteins(I)=[];
-0063     end
-0064     if isfield(genesToAdd,'geneMiriams')
-0065         genesToAdd.geneMiriams(I)=[];
-0066     end
-0067 else
-0068     newModel.genes=[newModel.genes;genesToAdd.genes(:)];
-0069 end
-0070 
-0071 %Some more checks and if they pass then add each field to the structure
-0072 if isfield(genesToAdd,'geneShortNames')
-0073     genesToAdd.geneShortNames=convertCharArray(genesToAdd.geneShortNames);
-0074     if numel(genesToAdd.geneShortNames)~=nGenes
-0075         EM='genesToAdd.geneShortNames must have the same number of elements as genesToAdd.genes';
-0076         dispEM(EM);
-0077     end
-0078     %Add empty field if it doesn't exist
-0079     if ~isfield(newModel,'geneShortNames')
-0080         newModel.geneShortNames=largeFiller;
-0081     end
-0082     newModel.geneShortNames=[newModel.geneShortNames;genesToAdd.geneShortNames(:)];
-0083 else
-0084     %Add empty strings if structure is in model
-0085     if isfield(newModel,'geneShortNames')
-0086         newModel.geneShortNames=[newModel.geneShortNames;filler];
-0087     end
-0088 end
-0089 if isfield(genesToAdd,'proteins')
-0090     genesToAdd.proteins=convertCharArray(genesToAdd.proteins);
-0091     if numel(genesToAdd.proteins)~=nGenes
-0092         EM='genesToAdd.proteins must have the same number of elements as genesToAdd.genes';
-0093         dispEM(EM);
-0094     end
-0095     %Add empty field if it doesn't exist
-0096     if ~isfield(newModel,'proteins')
-0097         newModel.proteins=largeFiller;
-0098     end
-0099     newModel.proteins=[newModel.proteins;genesToAdd.proteins(:)];
-0100 else
-0101     %Add empty strings if structure is in model
-0102     if isfield(newModel,'proteins')
-0103         newModel.proteins=[newModel.proteins;filler];
-0104     end
-0105 end
-0106 
-0107 
-0108 %Don't check the type of geneMiriams
-0109 if isfield(genesToAdd,'geneMiriams')
-0110     if numel(genesToAdd.geneMiriams)~=nGenes
-0111         EM='genesToAdd.geneMiriams must have the same number of elements as genesToAdd.genes';
-0112         dispEM(EM);
-0113     end
-0114     %Add empty field if it doesn't exist
-0115     if ~isfield(newModel,'geneMiriams')
-0116         newModel.geneMiriams=cell(nOldGenes,1);
-0117     end
-0118     newModel.geneMiriams=[newModel.geneMiriams;genesToAdd.geneMiriams(:)];
-0119 else
-0120     if isfield(newModel,'geneMiriams')
-0121         newModel.geneMiriams=[newModel.geneMiriams;cell(nGenes,1)];
-0122     end
-0123 end
-0124 
-0125 if isfield(genesToAdd,'geneComps')
-0126     if numel(genesToAdd.geneComps)~=nGenes
-0127         EM='genesToAdd.geneComps must have the same number of elements as genesToAdd.genes';
-0128         dispEM(EM);
-0129     end
-0130     %Add empty field if it doesn't exist
-0131     if ~isfield(newModel,'geneComps')
-0132         newModel.geneComps=ones(nOldGenes,1);
-0133         EM='Adding genes with compartment information to a model without such information. All existing genes will be assigned to the first compartment';
-0134         dispEM(EM,false);
-0135     end
-0136     newModel.geneComps=[newModel.geneComps;genesToAdd.geneComps(:)];
-0137 else
-0138     if isfield(newModel,'geneComps')
-0139         newModel.geneComps=[newModel.geneComps;ones(nGenes,1)];
-0140         fprintf('NOTE: The added genes will be assigned to the first compartment\n');
-0141     end
-0142 end
-0143 
-0144 if isfield(newModel,'geneFrom')
-0145     newModel.geneFrom=[newModel.geneFrom;filler];
-0146 end
-0147 
-0148 if isfield(newModel,'rxnGeneMat')
-0149     newModel.rxnGeneMat=[newModel.rxnGeneMat,zeros(length(newModel.rxns),nGenes)];
-0150 end
-0151 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/addMets.html b/doc/core/addMets.html deleted file mode 100644 index 2681ccee4..000000000 --- a/doc/core/addMets.html +++ /dev/null @@ -1,472 +0,0 @@ - - - - Description of addMets - - - - - - - - - -
Home > core > addMets.m
- - - -

addMets -

- -

PURPOSE ^

-
addMets
- -

SYNOPSIS ^

-
function newModel=addMets(model,metsToAdd,copyInfo,prefix)
- -

DESCRIPTION ^

-
 addMets
-   Adds metabolites to a model
-
- Input:
-   model       a model structure
-   metsToAdd   the metabolite structure can have the following fields:
-       mets            cell array with unique strings that identifies each
-                       metabolite (optional, default IDs of new
-                       metabolites are numbered with the prefix defined
-                       below)
-       metNames        cell array with the names of each metabolite
-       compartments    cell array with the compartment of each
-                       metabolite. Should match model.comps. If this is a
-                       string rather than a cell array it is assumed that
-                       all mets are in that compartment
-       b               Nx1 or Nx2 matrix with equality constraints for
-                       each metabolite (optional, default 0)
-       unconstrained   vector describing if each metabolite is an exchange
-                       metabolite (1) or not (0) (optional, default 0)
-       inchis          cell array with InChI strings (optional, default '')
-       metSmiles       cell array with SMILES strings (optional, default '')
-       metFormulas     cell array with the formulas  (optional, default '')
-       metMiriams      cell array with MIRIAM structures (optional, default [])
-       metCharges      metabolite charge (optional, default NaN)
-       metDeltaG       Gibbs free energy of formation at biochemical
-                       standard condition in kJ/mole (optional, default NaN)
-       metNotes        cell array with metabolite notes as strings
-                       (optional, default '')
-   copyInfo    when adding metabolites to a compartment where it
-               previously did not exist, the function will copy any
-               available annotation from the metabolite in another
-               compartment (optional, default true)
-   prefix      when metsToAdd.mets is not specified, new metabolite IDs
-               are generated with the prefix specified here. If IDs with
-               the prefix are already used in the model then the
-               numbering will start from the highest existing integer+1
-               (optional, default 'm_')
-
- Output:
-   newModel     an updated model structure
-
- This function does not make extensive checks about MIRIAM formats,
- forbidden characters or such.
-
- If multiple metabolites are added at once, the metMiriams cell array
- should be defined as (example with ChEBI and KEGG):
-
- metsToAdd.metMiriams{1} = struct('name',{{'chebi';'kegg.compound'}},...
-     'value',{{'CHEBI:18072';'C11821'}});
- metsToAdd.metMiriams{2} = struct('name',{{'chebi';'kegg.compound'}},...
-     'value',{{'CHEBI:31132';'C12248'}});
-
- Usage: newModel = addMets(model, metsToAdd, copyInfo, prefix)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function newModel=addMets(model,metsToAdd,copyInfo,prefix)
-0002 % addMets
-0003 %   Adds metabolites to a model
-0004 %
-0005 % Input:
-0006 %   model       a model structure
-0007 %   metsToAdd   the metabolite structure can have the following fields:
-0008 %       mets            cell array with unique strings that identifies each
-0009 %                       metabolite (optional, default IDs of new
-0010 %                       metabolites are numbered with the prefix defined
-0011 %                       below)
-0012 %       metNames        cell array with the names of each metabolite
-0013 %       compartments    cell array with the compartment of each
-0014 %                       metabolite. Should match model.comps. If this is a
-0015 %                       string rather than a cell array it is assumed that
-0016 %                       all mets are in that compartment
-0017 %       b               Nx1 or Nx2 matrix with equality constraints for
-0018 %                       each metabolite (optional, default 0)
-0019 %       unconstrained   vector describing if each metabolite is an exchange
-0020 %                       metabolite (1) or not (0) (optional, default 0)
-0021 %       inchis          cell array with InChI strings (optional, default '')
-0022 %       metSmiles       cell array with SMILES strings (optional, default '')
-0023 %       metFormulas     cell array with the formulas  (optional, default '')
-0024 %       metMiriams      cell array with MIRIAM structures (optional, default [])
-0025 %       metCharges      metabolite charge (optional, default NaN)
-0026 %       metDeltaG       Gibbs free energy of formation at biochemical
-0027 %                       standard condition in kJ/mole (optional, default NaN)
-0028 %       metNotes        cell array with metabolite notes as strings
-0029 %                       (optional, default '')
-0030 %   copyInfo    when adding metabolites to a compartment where it
-0031 %               previously did not exist, the function will copy any
-0032 %               available annotation from the metabolite in another
-0033 %               compartment (optional, default true)
-0034 %   prefix      when metsToAdd.mets is not specified, new metabolite IDs
-0035 %               are generated with the prefix specified here. If IDs with
-0036 %               the prefix are already used in the model then the
-0037 %               numbering will start from the highest existing integer+1
-0038 %               (optional, default 'm_')
-0039 %
-0040 % Output:
-0041 %   newModel     an updated model structure
-0042 %
-0043 % This function does not make extensive checks about MIRIAM formats,
-0044 % forbidden characters or such.
-0045 %
-0046 % If multiple metabolites are added at once, the metMiriams cell array
-0047 % should be defined as (example with ChEBI and KEGG):
-0048 %
-0049 % metsToAdd.metMiriams{1} = struct('name',{{'chebi';'kegg.compound'}},...
-0050 %     'value',{{'CHEBI:18072';'C11821'}});
-0051 % metsToAdd.metMiriams{2} = struct('name',{{'chebi';'kegg.compound'}},...
-0052 %     'value',{{'CHEBI:31132';'C12248'}});
-0053 %
-0054 % Usage: newModel = addMets(model, metsToAdd, copyInfo, prefix)
-0055 
-0056 if nargin<3
-0057     copyInfo=true;
-0058 end
-0059 if nargin<4
-0060     prefix='m_';
-0061 else
-0062     prefix=char(prefix);
-0063 end
-0064 
-0065 newModel=model;
-0066 
-0067 if isempty(metsToAdd)
-0068     return;
-0069 end
-0070 
-0071 %Check some stuff regarding the required fields
-0072 if ~isfield(metsToAdd,'mets')
-0073     metsToAdd.metNames=convertCharArray(metsToAdd.metNames);
-0074     metsToAdd.mets=generateNewIds(newModel,'mets',prefix,numel(metsToAdd.metNames));
-0075 else
-0076     metsToAdd.mets=convertCharArray(metsToAdd.mets);
-0077 end
-0078 if ~isfield(metsToAdd,'metNames')
-0079     metsToAdd.metNames=metsToAdd.mets;
-0080 else
-0081     metsToAdd.metNames=convertCharArray(metsToAdd.metNames);
-0082 end
-0083 if ~isfield(metsToAdd,'compartments')
-0084     EM='compartments is a required field in metsToAdd';
-0085     dispEM(EM);
-0086 else
-0087     metsToAdd.compartments=convertCharArray(metsToAdd.compartments);
-0088     %If only one compartment is given, assume it is for all metabolites
-0089     if numel(metsToAdd.compartments)==1 && numel(metsToAdd.mets)>1
-0090         temp=cell(numel(metsToAdd.mets),1);
-0091         temp(:)=metsToAdd.compartments;
-0092         metsToAdd.compartments=temp;
-0093     end
-0094 end
-0095 
-0096 %Number of metabolites
-0097 nMets=numel(metsToAdd.mets);
-0098 nOldMets=numel(model.mets);
-0099 filler=cell(nMets,1);
-0100 filler(:)={''};
-0101 largeFiller=cell(nOldMets,1);
-0102 largeFiller(:)={''};
-0103 
-0104 %Check that no metabolite ids are already present in the model
-0105 I=ismember(metsToAdd.mets,model.mets);
-0106 if any(I)
-0107     error('One or more elements in metsToAdd.mets are already present in model.mets: %s',...
-0108         strjoin(metsToAdd.mets(I),', '));
-0109 else
-0110     newModel.mets=[newModel.mets;metsToAdd.mets(:)];
-0111 end
-0112 
-0113 %Check that all the compartments could be found
-0114 [I, compMap]=ismember(metsToAdd.compartments,model.comps);
-0115 if ~all(I)
-0116     EM='metsToAdd.compartments must match model.comps';
-0117     dispEM(EM);
-0118 end
-0119 
-0120 %Check that the metabolite names aren't present in the same compartment.
-0121 %Not the neatest way maybe..
-0122 t1=strcat(metsToAdd.metNames(:),'***',metsToAdd.compartments(:));
-0123 t2=strcat(model.metNames,'***',model.comps(model.metComps));
-0124 if any(ismember(t1,t2))
-0125     EM='One or more elements in metsToAdd.metNames already exist in the same compartments as the one it is being added to';
-0126     dispEM(EM);
-0127 end
-0128 
-0129 %Some more checks and if they pass then add each field to the structure
-0130 if numel(metsToAdd.metNames)~=nMets
-0131     EM='metsToAdd.metNames must have the same number of elements as metsToAdd.mets';
-0132     dispEM(EM);
-0133 else
-0134     newModel.metNames=[newModel.metNames;metsToAdd.metNames(:)];
-0135 end
-0136 
-0137 if numel(compMap)~=nMets
-0138     EM='metsToAdd.compartments must have the same number of elements as metsToAdd.mets';
-0139     dispEM(EM);
-0140 else
-0141     newModel.metComps=[newModel.metComps;compMap(:)];
-0142 end
-0143 
-0144 if isfield(metsToAdd,'b')
-0145     if size(metsToAdd.b,1)~=nMets
-0146         EM='metsToAdd.b must have the same number of elements as metsToAdd.mets';
-0147         dispEM(EM);
-0148     else
-0149         %Add empty field if it doesn't exist
-0150         if ~isfield(newModel,'b')
-0151             newModel.b=zeros(nOldMets,1);
-0152         end
-0153         
-0154         %If the original is only one vector
-0155         if size(metsToAdd.b,2)>size(newModel.b,2)
-0156             newModel.b=[newModel.b newModel.b];
-0157         end
-0158         %Add the new ones
-0159         newModel.b=[newModel.b;metsToAdd.b];
-0160     end
-0161 else
-0162     if isfield(newModel,'b')
-0163         %Add the default
-0164         newModel.b=[newModel.b;zeros(nMets,size(newModel.b,2))];
-0165     end
-0166 end
-0167 
-0168 if isfield(metsToAdd,'unconstrained')
-0169     if numel(metsToAdd.unconstrained)~=nMets
-0170         EM='metsToAdd.unconstrained must have the same number of elements as metsToAdd.mets';
-0171         dispEM(EM);
-0172     else
-0173         %Add empty field if it doesn't exist
-0174         if ~isfield(newModel,'unconstrained')
-0175             newModel.unconstrained=zeros(nOldMets,1);
-0176         end
-0177         
-0178         %Add the new ones
-0179         newModel.unconstrained=[newModel.unconstrained;metsToAdd.unconstrained(:)];
-0180     end
-0181 else
-0182     if isfield(newModel,'unconstrained')
-0183         %Add the default
-0184         newModel.unconstrained=[newModel.unconstrained;zeros(nMets,1)];
-0185     end
-0186 end
-0187 
-0188 if isfield(metsToAdd,'inchis')
-0189     metsToAdd.inchis=convertCharArray(metsToAdd.inchis);
-0190     if numel(metsToAdd.inchis)~=nMets
-0191         EM='metsToAdd.inchis must have the same number of elements as metsToAdd.mets';
-0192         dispEM(EM);
-0193     end
-0194     %Add empty field if it doesn't exist
-0195     if ~isfield(newModel,'inchis')
-0196         newModel.inchis=largeFiller;
-0197     end
-0198     newModel.inchis=[newModel.inchis;metsToAdd.inchis(:)];
-0199 else
-0200     %Add empty strings if structure is in model
-0201     if isfield(newModel,'inchis')
-0202         newModel.inchis=[newModel.inchis;filler];
-0203     end
-0204 end
-0205 
-0206 
-0207 if isfield(metsToAdd,'metSmiles')
-0208     metsToAdd.metSmiles=convertCharArray(metsToAdd.metSmiles);
-0209     if numel(metsToAdd.metSmiles)~=nMets
-0210         EM='metsToAdd.metSmiles must have the same number of elements as metsToAdd.mets';
-0211         dispEM(EM);
-0212     end
-0213     %Add empty field if it doesn't exist
-0214     if ~isfield(newModel,'metSmiles')
-0215         newModel.metSmiles=largeFiller;
-0216     end
-0217     newModel.metSmiles=[newModel.metSmiles;metsToAdd.metSmiles(:)];
-0218 else
-0219     %Add empty strings if structure is in model
-0220     if isfield(newModel,'metSmiles')
-0221         newModel.metSmiles=[newModel.metSmiles;filler];
-0222     end
-0223 end
-0224 
-0225 if isfield(metsToAdd,'metFormulas')
-0226     metsToAdd.metFormulas=convertCharArray(metsToAdd.metFormulas);
-0227     if numel(metsToAdd.metFormulas)~=nMets
-0228         EM='metsToAdd.metFormulas must have the same number of elements as metsToAdd.mets';
-0229         dispEM(EM);
-0230     end
-0231     %Add empty field if it doesn't exist
-0232     if ~isfield(newModel,'metFormulas')
-0233         newModel.metFormulas=largeFiller;
-0234     end
-0235     newModel.metFormulas=[newModel.metFormulas;metsToAdd.metFormulas(:)];
-0236 else
-0237     %Add default
-0238     if isfield(newModel,'metFormulas')
-0239         newModel.metFormulas=[newModel.metFormulas;filler];
-0240     end
-0241 end
-0242 
-0243 if isfield(metsToAdd,'metCharges')
-0244     if numel(metsToAdd.metCharges)~=nMets
-0245         EM='metsToAdd.metCharges must have the same number of elements as metsToAdd.mets';
-0246         dispEM(EM);
-0247     end
-0248     if ~isnumeric(metsToAdd.metCharges)
-0249         EM='metsToAdd.metCharges must be of type "double"';
-0250         dispEM(EM);
-0251     end
-0252     if ~isfield(newModel,'metCharges')
-0253         newModel.metCharges=NaN(numel(largeFiller),1);
-0254     end
-0255     newModel.metCharges=[newModel.metCharges;metsToAdd.metCharges(:)];
-0256 else
-0257     %Add default
-0258     if isfield(newModel,'metCharges')
-0259         newModel.metCharges=[newModel.metCharges;NaN(numel(filler),1)];
-0260     end
-0261 end
-0262 
-0263 if isfield(metsToAdd,'metDeltaG')
-0264     if numel(metsToAdd.metDeltaG)~=nMets
-0265         EM='metsToAdd.metDeltaG must have the same number of elements as metsToAdd.mets';
-0266         dispEM(EM);
-0267     end
-0268     if ~isnumeric(metsToAdd.metDeltaG)
-0269         EM='metsToAdd.metDeltaG must be of type "double"';
-0270         dispEM(EM);
-0271     end
-0272     if ~isfield(newModel,'metDeltaG')
-0273         newModel.metDeltaG=NaN(numel(largeFiller),1);
-0274     end
-0275     newModel.metDeltaG=[newModel.metDeltaG;metsToAdd.metDeltaG(:)];
-0276 else
-0277     %Add default
-0278     if isfield(newModel,'metDeltaG')
-0279         newModel.metDeltaG=[newModel.metDeltaG;NaN(numel(filler),1)];
-0280     end
-0281 end
-0282 
-0283 
-0284 if isfield(metsToAdd,'metNotes')
-0285     metsToAdd.metNotes=convertCharArray(metsToAdd.metNotes);
-0286     if numel(metsToAdd.metNotes)==1 && numel(metsToAdd.mets)>1
-0287         temp=cell(numel(metsToAdd.mets),1);
-0288         temp(:)=metsToAdd.metNotes;
-0289         metsToAdd.metNotes=temp;
-0290     end
-0291     if numel(metsToAdd.metNotes)~=nMets
-0292         EM='metsToAdd.metNotes must have the same number of elements as metsToAdd.mets';
-0293         dispEM(EM);
-0294     end
-0295     %Add empty field if it doesn't exist
-0296     if ~isfield(newModel,'metNotes')
-0297         newModel.metNotes=largeFiller;
-0298     end
-0299     newModel.metNotes=[newModel.metNotes;metsToAdd.metNotes(:)];
-0300 else
-0301     %Add empty strings if structure is in model
-0302     if isfield(newModel,'metNotes')
-0303         newModel.metNotes=[newModel.metNotes;filler];
-0304     end
-0305 end
-0306 
-0307 %Don't check the type of metMiriams
-0308 if isfield(metsToAdd,'metMiriams')
-0309     if numel(metsToAdd.metMiriams)==1 && numel(metsToAdd.mets)>1
-0310         temp=cell(numel(metsToAdd.mets),1);
-0311         temp(:)={metsToAdd.metMiriams};
-0312         metsToAdd.metMiriams=temp;
-0313     end
-0314     if numel(metsToAdd.metMiriams)~=nMets
-0315         EM='metsToAdd.metMiriams must have the same number of elements as metsToAdd.mets';
-0316         dispEM(EM);
-0317     end
-0318     %Add empty field if it doesn't exist
-0319     if ~isfield(newModel,'metMiriams')
-0320         newModel.metMiriams=cell(nOldMets,1);
-0321     end
-0322     newModel.metMiriams=[newModel.metMiriams;metsToAdd.metMiriams(:)];
-0323 else
-0324     if isfield(newModel,'metMiriams')
-0325         newModel.metMiriams=[newModel.metMiriams;cell(nMets,1)];
-0326     end
-0327 end
-0328 
-0329 if isfield(newModel,'metFrom')
-0330     newModel.metFrom=[newModel.metFrom;filler];
-0331 end
-0332 
-0333 %Expand the S matrix
-0334 newModel.S=[newModel.S;sparse(nMets,size(newModel.S,2))];
-0335 
-0336 if copyInfo==true
-0337     [I, J]=ismember(metsToAdd.metNames,model.metNames);
-0338     J=J(I);
-0339     %I is the indexes of the new metabolites for which a metabolite with
-0340     %the same name existed
-0341     I=find(I)+nOldMets;
-0342     %Go through each of the added mets and copy annotation if it doesn't
-0343     %exist
-0344     for i=1:numel(I)
-0345         if isfield(newModel,'inchis')
-0346             if isempty(newModel.inchis{I(i)})
-0347                 newModel.inchis(I(i))=newModel.inchis(J(i));
-0348             end
-0349         end
-0350         if isfield(newModel,'metSmiles')
-0351             if isempty(newModel.metSmiles{I(i)})
-0352                 newModel.metSmiles(I(i))=newModel.metSmiles(J(i));
-0353             end
-0354         end        
-0355         if isfield(newModel,'metFormulas')
-0356             if isempty(newModel.metFormulas{I(i)})
-0357                 newModel.metFormulas(I(i))=newModel.metFormulas(J(i));
-0358             end
-0359         end
-0360         if isfield(newModel,'metMiriams')
-0361             if isempty(newModel.metMiriams{I(i)})
-0362                 newModel.metMiriams(I(i))=newModel.metMiriams(J(i));
-0363             end
-0364         end
-0365         if isfield(newModel,'metCharges')
-0366             newModel.metCharges(I(i))=newModel.metCharges(J(i));
-0367         end
-0368         if isfield(newModel,'metDeltaG')
-0369             newModel.metDeltaG(I(i))=newModel.metDeltaG(J(i));
-0370         end
-0371     end
-0372 end
-0373 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/addRxns.html b/doc/core/addRxns.html deleted file mode 100644 index 5a26576f6..000000000 --- a/doc/core/addRxns.html +++ /dev/null @@ -1,846 +0,0 @@ - - - - Description of addRxns - - - - - - - - - -
Home > core > addRxns.m
- - - -

addRxns -

- -

PURPOSE ^

-
addRxns
- -

SYNOPSIS ^

-
function newModel=addRxns(model,rxnsToAdd,eqnType,compartment,allowNewMets,allowNewGenes)
- -

DESCRIPTION ^

-
 addRxns
-   Adds reactions to a model
-
- Input:
-   model            a model structure
-   rxnsToAdd        the reaction structure can have the following fields:
-       rxns                cell array with unique strings that identifies
-                           each reaction
-       equations           cell array with equation strings. Decimal
-                           coefficients are expressed as "1.2".
-                           Reversibility is indicated by "<=>" or "=>"
-       mets                (alternative to equations) cell array with the
-                           metabolites involved in each reaction as nested
-                           arrays. E.g.: {{'met1','met2'},{'met1','met3','met4'}}
-                           In the case of one single reaction added, it
-                           can be a string array: {'met1','met2'}
-       stoichCoeffs        (alternative to equations) cell array with the
-                           corresponding stoichiometries as nested vectors
-                           E.g.: {[-1,+2],[-1,-1,+1]}. In the case of one
-                           single reaction added, it can be a vector: [-1,+2]
-       rxnNames            cell array with the names of each reaction
-                           (optional, default '')
-       lb                  vector with the lower bounds (optional, default
-                           model.annotations.defaultLB or -inf for
-                           reversible reactions and 0 for irreversible
-                           when "equations" is used. When "mets" and
-                           "stoichCoeffs" are ,used it defaults for all
-                           to model.annotations.defaultLB or -inf)
-       ub                  vector with the upper bounds (optional, default
-                           model.annotations.defaultUB or inf)
-       c                   vector with the objective function coefficients
-                           (optional, default 0)
-       eccodes             cell array with the EC-numbers for each
-                           reactions. Delimit several EC-numbers with ";"
-                           (optional, default '')
-       subSystems          cell array with the subsystems for each
-                           reaction (optional, default '')
-       grRules             cell array with the gene-reaction relationship
-                           for each reaction. E.g. "(A and B) or (C)"
-                           means that the reaction could be catalyzed by a
-                           complex between A & B or by C on its own. All
-                           the genes have to be present in model.genes.
-                           Add genes with addGenesRaven before calling
-                           this function if needed (optional, default '')
-       rxnMiriams          cell array with Miriam structures (optional,
-                           default [])
-       rxnComps            cell array with compartments (as in
-                           model.comps) (optional, default {})
-       rxnNotes            cell array with reaction notes (optional,
-                           default '')
-       rxnDeltaG           Gibbs free energy at biochemical standard
-                           condition in kJ/mole (optional, default NaN)
-       rxnReferences       cell array with reaction references (optional,
-                           default '')
-       rxnConfidenceScores vector with reaction confidence scores
-                           (optional, default NaN)
-   eqnType          double describing how the equation string should be
-                    interpreted
-                    1 - The metabolites are matched to model.mets. New
-                        metabolites (if allowed) are added to
-                        "compartment" (default)
-                    2 - The metabolites are matched to model.metNames and
-                        all metabolites are assigned to "compartment". Any
-                        new metabolites that are added will be assigned
-                        IDs "m1", "m2"... If IDs on the same form are
-                        already used in the model then the numbering will
-                        start from the highest used integer+1
-                    3 - The metabolites are written as
-                        "metNames[comps]". Only compartments in
-                        model.comps are allowed. Any
-                        new metabolites that are added will be assigned
-                        IDs "m1", "m2"... If IDs on the same form are
-                        already used in the model then the numbering will
-                        start from the highest used integer+1
-   compartment      a string with the compartment the metabolites should
-                    be placed in when using eqnType=2. Must match
-                    model.comps (optional when eqnType=1 or eqnType=3)
-   allowNewMets     true if the function is allowed to add new
-                    metabolites. Can also be a string, which will be used
-                    as prefix for the new metabolite IDs. It is highly
-                    recommended to first add any new metabolites with
-                    addMets rather than automatically through this
-                    function. addMets supports more annotation of
-                    metabolites, allows for the use of exchange
-                    metabolites, and using it reduces the risk of parsing
-                    errors (optional, default false)
-   allowNewGenes    true if the functions is allowed to add new genes
-                    (optional, default false)
-
- Output:
-   newModel         an updated model structure
-
-   This function does not make extensive checks about formatting of
-   gene-reaction rules.
-
-   When adding metabolites to a compartment where they previously do not
-   the function will copy any available information from the metabolite in
-   another compartment.
-
- Usage: newModel = addRxns(model, rxnsToAdd, eqnType, compartment,...
-                       allowNewMets, allowNewGenes)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function newModel=addRxns(model,rxnsToAdd,eqnType,compartment,allowNewMets,allowNewGenes)
-0002 % addRxns
-0003 %   Adds reactions to a model
-0004 %
-0005 % Input:
-0006 %   model            a model structure
-0007 %   rxnsToAdd        the reaction structure can have the following fields:
-0008 %       rxns                cell array with unique strings that identifies
-0009 %                           each reaction
-0010 %       equations           cell array with equation strings. Decimal
-0011 %                           coefficients are expressed as "1.2".
-0012 %                           Reversibility is indicated by "<=>" or "=>"
-0013 %       mets                (alternative to equations) cell array with the
-0014 %                           metabolites involved in each reaction as nested
-0015 %                           arrays. E.g.: {{'met1','met2'},{'met1','met3','met4'}}
-0016 %                           In the case of one single reaction added, it
-0017 %                           can be a string array: {'met1','met2'}
-0018 %       stoichCoeffs        (alternative to equations) cell array with the
-0019 %                           corresponding stoichiometries as nested vectors
-0020 %                           E.g.: {[-1,+2],[-1,-1,+1]}. In the case of one
-0021 %                           single reaction added, it can be a vector: [-1,+2]
-0022 %       rxnNames            cell array with the names of each reaction
-0023 %                           (optional, default '')
-0024 %       lb                  vector with the lower bounds (optional, default
-0025 %                           model.annotations.defaultLB or -inf for
-0026 %                           reversible reactions and 0 for irreversible
-0027 %                           when "equations" is used. When "mets" and
-0028 %                           "stoichCoeffs" are ,used it defaults for all
-0029 %                           to model.annotations.defaultLB or -inf)
-0030 %       ub                  vector with the upper bounds (optional, default
-0031 %                           model.annotations.defaultUB or inf)
-0032 %       c                   vector with the objective function coefficients
-0033 %                           (optional, default 0)
-0034 %       eccodes             cell array with the EC-numbers for each
-0035 %                           reactions. Delimit several EC-numbers with ";"
-0036 %                           (optional, default '')
-0037 %       subSystems          cell array with the subsystems for each
-0038 %                           reaction (optional, default '')
-0039 %       grRules             cell array with the gene-reaction relationship
-0040 %                           for each reaction. E.g. "(A and B) or (C)"
-0041 %                           means that the reaction could be catalyzed by a
-0042 %                           complex between A & B or by C on its own. All
-0043 %                           the genes have to be present in model.genes.
-0044 %                           Add genes with addGenesRaven before calling
-0045 %                           this function if needed (optional, default '')
-0046 %       rxnMiriams          cell array with Miriam structures (optional,
-0047 %                           default [])
-0048 %       rxnComps            cell array with compartments (as in
-0049 %                           model.comps) (optional, default {})
-0050 %       rxnNotes            cell array with reaction notes (optional,
-0051 %                           default '')
-0052 %       rxnDeltaG           Gibbs free energy at biochemical standard
-0053 %                           condition in kJ/mole (optional, default NaN)
-0054 %       rxnReferences       cell array with reaction references (optional,
-0055 %                           default '')
-0056 %       rxnConfidenceScores vector with reaction confidence scores
-0057 %                           (optional, default NaN)
-0058 %   eqnType          double describing how the equation string should be
-0059 %                    interpreted
-0060 %                    1 - The metabolites are matched to model.mets. New
-0061 %                        metabolites (if allowed) are added to
-0062 %                        "compartment" (default)
-0063 %                    2 - The metabolites are matched to model.metNames and
-0064 %                        all metabolites are assigned to "compartment". Any
-0065 %                        new metabolites that are added will be assigned
-0066 %                        IDs "m1", "m2"... If IDs on the same form are
-0067 %                        already used in the model then the numbering will
-0068 %                        start from the highest used integer+1
-0069 %                    3 - The metabolites are written as
-0070 %                        "metNames[comps]". Only compartments in
-0071 %                        model.comps are allowed. Any
-0072 %                        new metabolites that are added will be assigned
-0073 %                        IDs "m1", "m2"... If IDs on the same form are
-0074 %                        already used in the model then the numbering will
-0075 %                        start from the highest used integer+1
-0076 %   compartment      a string with the compartment the metabolites should
-0077 %                    be placed in when using eqnType=2. Must match
-0078 %                    model.comps (optional when eqnType=1 or eqnType=3)
-0079 %   allowNewMets     true if the function is allowed to add new
-0080 %                    metabolites. Can also be a string, which will be used
-0081 %                    as prefix for the new metabolite IDs. It is highly
-0082 %                    recommended to first add any new metabolites with
-0083 %                    addMets rather than automatically through this
-0084 %                    function. addMets supports more annotation of
-0085 %                    metabolites, allows for the use of exchange
-0086 %                    metabolites, and using it reduces the risk of parsing
-0087 %                    errors (optional, default false)
-0088 %   allowNewGenes    true if the functions is allowed to add new genes
-0089 %                    (optional, default false)
-0090 %
-0091 % Output:
-0092 %   newModel         an updated model structure
-0093 %
-0094 %   This function does not make extensive checks about formatting of
-0095 %   gene-reaction rules.
-0096 %
-0097 %   When adding metabolites to a compartment where they previously do not
-0098 %   the function will copy any available information from the metabolite in
-0099 %   another compartment.
-0100 %
-0101 % Usage: newModel = addRxns(model, rxnsToAdd, eqnType, compartment,...
-0102 %                       allowNewMets, allowNewGenes)
-0103 
-0104 if nargin<3
-0105     eqnType=1;
-0106 elseif ~isnumeric(eqnType)
-0107     EM='eqnType must be numeric';
-0108     dispEM(EM);
-0109 elseif ~ismember(eqnType,[1 2 3])
-0110     EM='eqnType must be 1, 2, or 3';
-0111     dispEM(EM);
-0112 end    
-0113 
-0114 if nargin<4
-0115     compartment=[];
-0116 else
-0117     compartment=char(compartment);
-0118 end
-0119 if nargin<5
-0120     allowNewMets=false;
-0121 elseif ~islogical(allowNewMets)
-0122     allowNewMets=char(allowNewMets);
-0123 end
-0124 if nargin<6
-0125     allowNewGenes=false;
-0126 end
-0127 
-0128 if allowNewGenes & isfield(rxnsToAdd,'grRules')
-0129     genesToAdd.genes = strjoin(convertCharArray(rxnsToAdd.grRules));
-0130     genesToAdd.genes = regexp(genesToAdd.genes,' |)|(|and|or','split'); % Remove all grRule punctuation
-0131     genesToAdd.genes = genesToAdd.genes(~cellfun(@isempty,genesToAdd.genes));  % Remove spaces and empty genes
-0132     genesToAdd.genes = setdiff(unique(genesToAdd.genes),model.genes); % Only keep new genes
-0133     if isfield(model,'geneComps')
-0134         genesToAdd.geneComps(1:numel(genesToAdd.genes)) = repmat(11,numel(genesToAdd.genes),1);
-0135     end
-0136     if ~isempty(genesToAdd.genes)
-0137         fprintf('\nNew genes added to the model:\n')
-0138         fprintf([strjoin(genesToAdd.genes,'\n') '\n'])
-0139         newModel=addGenesRaven(model,genesToAdd);
-0140     else
-0141         newModel=model;
-0142     end
-0143 else
-0144     newModel=model;
-0145 end
-0146 
-0147 %If no reactions should be added
-0148 if isempty(rxnsToAdd)
-0149     return;
-0150 end
-0151 
-0152 if eqnType==2 || (eqnType==1 && allowNewMets==true)
-0153     compartment=char(compartment);
-0154     if ~ismember(compartment,model.comps)
-0155         EM='compartment must match one of the compartments in model.comps';
-0156         dispEM(EM);
-0157     end
-0158 end
-0159 
-0160 if ~isfield(rxnsToAdd,'rxns')
-0161     EM='rxns is a required field in rxnsToAdd';
-0162     dispEM(EM);
-0163 else
-0164     rxnsToAdd.rxns=convertCharArray(rxnsToAdd.rxns);
-0165     %To fit with some later printing
-0166     rxnsToAdd.rxns=rxnsToAdd.rxns(:);
-0167 end
-0168 if ~(isfield(rxnsToAdd,'equations') || (isfield(rxnsToAdd,'mets') && isfield(rxnsToAdd,'stoichCoeffs')))
-0169     EM='Either "equations" or "mets"+"stoichCoeffs" are required fields in rxnsToAdd';
-0170     dispEM(EM);
-0171 end
-0172 
-0173 if any(ismember(rxnsToAdd.rxns,model.rxns))
-0174     EM='One or more reaction id was already present in the model. Use changeRxns or remove the existing reactions before adding new ones';
-0175     dispEM(EM);
-0176 end
-0177 
-0178 %Normal case: equations provided
-0179 if isfield(rxnsToAdd,'equations')
-0180     rxnsToAdd.equations=convertCharArray(rxnsToAdd.equations);
-0181 
-0182     %Alternative case: mets+stoichiometry provided
-0183 else
-0184     %In the case of 1 rxn added (array of strings + vector), transform to
-0185     %cells of length=1:
-0186     if iscellstr(rxnsToAdd.mets)
-0187         rxnsToAdd.mets={rxnsToAdd.mets};
-0188     end
-0189     if isnumeric(rxnsToAdd.stoichCoeffs)
-0190         rxnsToAdd.stoichCoeffs = {rxnsToAdd.stoichCoeffs};
-0191     end
-0192     %Now both rxnsToAdd.mets and rxnsToAdd.stoichCoeffs should be cell
-0193     %arrays & of the same size:
-0194     if ~iscell(rxnsToAdd.mets) || ~iscell(rxnsToAdd.stoichCoeffs)
-0195         EM='rxnsToAdd.mets & rxnsToAdd.stoichCoeffs must be cell arrays';
-0196         dispEM(EM);
-0197     elseif length(rxnsToAdd.stoichCoeffs) ~= length(rxnsToAdd.mets)
-0198         EM = 'rxnsToAdd.stoichCoeffs must have the same number of elements as rxnsToAdd.mets';
-0199         dispEM(EM);
-0200     end
-0201     %In this case we need lb to decide if the reaction is reversible or not:
-0202     if ~isfield(rxnsToAdd,'lb')
-0203         %Fill with standard if it doesn't exist
-0204         rxnsToAdd.lb=-inf(size(rxnsToAdd.mets));
-0205     elseif ~isnumeric(rxnsToAdd.lb)
-0206         EM = 'rxnsToAdd.lb must be a vector';
-0207         dispEM(EM);
-0208     elseif length(rxnsToAdd.lb) ~= length(rxnsToAdd.mets)
-0209         EM = 'rxnsToAdd.lb must have the same number of elements as rxnsToAdd.mets';
-0210         dispEM(EM);
-0211     end
-0212     %Now we construct equations, to comply with the rest of the script:
-0213     rxnsToAdd.equations = cell(size(rxnsToAdd.mets));
-0214     for i = 1:length(rxnsToAdd.mets)
-0215         mets         = rxnsToAdd.mets{i};
-0216         stoichCoeffs = rxnsToAdd.stoichCoeffs{i};
-0217         if isfield(rxnsToAdd,'ub')
-0218             isrev        = rxnsToAdd.lb(i) < 0 && rxnsToAdd.ub(i) > 0;
-0219         else
-0220             isrev        = rxnsToAdd.lb(i) < 0;
-0221         end
-0222         rxnsToAdd.equations{i} = buildEquation(mets,stoichCoeffs,isrev);
-0223     end
-0224 end
-0225 
-0226 nRxns=numel(rxnsToAdd.rxns);
-0227 nOldRxns=numel(model.rxns);
-0228 filler=cell(nRxns,1);
-0229 filler(:)={''};
-0230 cellfiller=cell(nRxns,1);
-0231 cellfiller(:)={{''}};
-0232 largeFiller=cell(nOldRxns,1);
-0233 largeFiller(:)={''};
-0234 largeCellFiller=cell(nOldRxns,1);
-0235 largeCellFiller(:)={{''}};
-0236 
-0237 %***Add everything to the model except for the equations.
-0238 if numel(rxnsToAdd.equations)~=nRxns
-0239     EM='rxnsToAdd.equations must have the same number of elements as rxnsToAdd.rxns';
-0240     dispEM(EM);
-0241 end
-0242 
-0243 %Parse the equations. This is done at this early stage since I need the
-0244 %reversibility info
-0245 [S, mets, badRxns, reversible]=constructS(rxnsToAdd.equations);
-0246 EM='The following equations have one or more metabolites both as substrate and product. Only the net equations will be added:';
-0247 dispEM(EM,false,rxnsToAdd.rxns(badRxns));
-0248 
-0249 newModel.rev=[newModel.rev;reversible];
-0250 newModel.rxns=[newModel.rxns;rxnsToAdd.rxns(:)];
-0251 
-0252 if isfield(rxnsToAdd,'rxnNames')
-0253     rxnsToAdd.rxnNames=convertCharArray(rxnsToAdd.rxnNames);
-0254     if numel(rxnsToAdd.rxnNames)~=nRxns
-0255         EM='rxnsToAdd.rxnNames must have the same number of elements as rxnsToAdd.rxns';
-0256         dispEM(EM);
-0257     end
-0258     %Fill with standard if it doesn't exist
-0259     if ~isfield(newModel,'rxnNames')
-0260         newModel.rxnNames=largeFiller;
-0261     end
-0262     newModel.rxnNames=[newModel.rxnNames;rxnsToAdd.rxnNames(:)];
-0263 else
-0264     %Fill with standard if it doesn't exist
-0265     if isfield(newModel,'rxnNames')
-0266         newModel.rxnNames=[newModel.rxnNames;filler];
-0267     end
-0268 end
-0269 
-0270 if isfield(newModel,'annotation') & isfield(newModel.annotation,'defaultLB')
-0271     newLb=newModel.annotation.defaultLB;
-0272 else
-0273     newLb=-inf;
-0274 end
-0275 
-0276 if isfield(rxnsToAdd,'lb')
-0277     if numel(rxnsToAdd.lb)~=nRxns
-0278         EM='rxnsToAdd.lb must have the same number of elements as rxnsToAdd.rxns';
-0279         dispEM(EM);
-0280     end
-0281     %Fill with standard if it doesn't exist
-0282     if ~isfield(newModel,'lb')
-0283         newModel.lb=zeros(nOldRxns,1);
-0284         newModel.lb(newModel.rev~=0)=newLb;
-0285     end
-0286     newModel.lb=[newModel.lb;rxnsToAdd.lb(:)];
-0287 else
-0288     %Fill with standard if it doesn't exist
-0289     if isfield(newModel,'lb')
-0290         I=zeros(nRxns,1);
-0291         I(reversible~=0)=newLb;
-0292         newModel.lb=[newModel.lb;I];
-0293     end
-0294 end
-0295 
-0296 if isfield(newModel,'annotation') & isfield(newModel.annotation,'defaultUB')
-0297     newUb=newModel.annotation.defaultUB;
-0298 else
-0299     newUb=inf;
-0300 end
-0301 
-0302 if isfield(rxnsToAdd,'ub')
-0303     if numel(rxnsToAdd.ub)~=nRxns
-0304         EM='rxnsToAdd.ub must have the same number of elements as rxnsToAdd.rxns';
-0305         dispEM(EM);
-0306     end
-0307     %Fill with standard if it doesn't exist
-0308     if ~isfield(newModel,'ub')
-0309         newModel.ub=repmat(newUb,nOldRxns,1);
-0310     end
-0311     newModel.ub=[newModel.ub;rxnsToAdd.ub(:)];
-0312 else
-0313     %Fill with standard if it doesn't exist
-0314     if isfield(newModel,'ub')
-0315         newModel.ub=[newModel.ub;repmat(newUb,nRxns,1)];
-0316     end
-0317 end
-0318 
-0319 if isfield(rxnsToAdd,'c')
-0320     if numel(rxnsToAdd.c)~=nRxns
-0321         EM='rxnsToAdd.c must have the same number of elements as rxnsToAdd.rxns';
-0322         dispEM(EM);
-0323     end
-0324     %Fill with standard if it doesn't exist
-0325     if ~isfield(newModel,'c')
-0326         newModel.c=zeros(nOldRxns,1);
-0327     end
-0328     newModel.c=[newModel.c;rxnsToAdd.c(:)];
-0329 else
-0330     %Fill with standard if it doesn't exist
-0331     if isfield(newModel,'c')
-0332         newModel.c=[newModel.c;zeros(nRxns,1)];
-0333     end
-0334 end
-0335 
-0336 if isfield(rxnsToAdd,'eccodes')
-0337     rxnsToAdd.eccodes=convertCharArray(rxnsToAdd.eccodes);
-0338     if numel(rxnsToAdd.eccodes)~=nRxns
-0339         EM='rxnsToAdd.eccodes must have the same number of elements as rxnsToAdd.rxns';
-0340         dispEM(EM);
-0341     end
-0342     %Fill with standard if it doesn't exist
-0343     if ~isfield(newModel,'eccodes')
-0344         newModel.eccodes=largeFiller;
-0345     end
-0346     newModel.eccodes=[newModel.eccodes;rxnsToAdd.eccodes(:)];
-0347 else
-0348     %Fill with standard if it doesn't exist
-0349     if isfield(newModel,'eccodes')
-0350         newModel.eccodes=[newModel.eccodes;filler];
-0351     end
-0352 end
-0353 
-0354 if isfield(rxnsToAdd,'subSystems')
-0355     % Has to be cell array
-0356     if ischar(rxnsToAdd.subSystems)
-0357         rxnsToAdd.subSystems = {rxnsToAdd.subSystems};
-0358     end
-0359     % If all nested cells are 1x1, then unnest
-0360     if all(cellfun(@(x) iscell(x) && isscalar(x), rxnsToAdd.subSystems))
-0361         rxnsToAdd.subSystems = transpose([rxnsToAdd.subSystems{:}]);
-0362     end
-0363     % Cell array should now be as simple as possible. Check if it is nested
-0364     subSysRxnsNested = any(cellfun(@(x) iscell(x), rxnsToAdd.subSystems));
-0365     if isfield(newModel,'subSystems')
-0366         subSysModelNested = any(cellfun(@(x) iscell(x), newModel.subSystems));
-0367     else
-0368         subSysModelNested = subSysRxnsNested;
-0369         if subSysRxnsNested
-0370             newModel.subSystems=largeCellFiller;
-0371         else
-0372             newModel.subSystems=largeFiller;
-0373         end
-0374     end
-0375     if subSysRxnsNested && ~subSysModelNested
-0376         % Make all existing subSystems nested
-0377         newModel.subSystems = cellfun(@(x) {x}, newModel.subSystems, 'uni', 0);
-0378     elseif ~subSysRxnsNested && subSysModelNested
-0379         rxnsToAdd.subSystems = cellfun(@(x) {x}, rxnsToAdd.subSystems, 'uni', 0);
-0380     end
-0381     if numel(rxnsToAdd.subSystems)~=nRxns
-0382         EM='rxnsToAdd.subSystems must have the same number of elements as rxnsToAdd.rxns';
-0383         dispEM(EM);
-0384     end
-0385     newModel.subSystems=[newModel.subSystems;rxnsToAdd.subSystems(:)];
-0386 else
-0387     %Fill with standard if it does not exist
-0388     if isfield(newModel,'subSystems')
-0389         if any(cellfun(@(x) iscell(x), newModel.subSystems))
-0390             newModel.subSystems=[newModel.subSystems;cellfiller];
-0391         else
-0392             newModel.subSystems=[newModel.subSystems;filler];
-0393         end
-0394     end
-0395 end
-0396 if isfield(rxnsToAdd,'rxnMiriams')
-0397     if numel(rxnsToAdd.rxnMiriams)~=nRxns
-0398         EM='rxnsToAdd.rxnMiriams must have the same number of elements as rxnsToAdd.rxns';
-0399         dispEM(EM);
-0400     end
-0401     %Fill with standard if it doesn't exist
-0402     if ~isfield(newModel,'rxnMiriams')
-0403         newModel.rxnMiriams=cell(nOldRxns,1);
-0404     end
-0405     newModel.rxnMiriams=[newModel.rxnMiriams;rxnsToAdd.rxnMiriams(:)];
-0406 else
-0407     %Fill with standard if it doesn't exist
-0408     if isfield(newModel,'rxnMiriams')
-0409         newModel.rxnMiriams=[newModel.rxnMiriams;cell(nRxns,1)];
-0410     end
-0411 end
-0412 if isfield(rxnsToAdd,'rxnComps')
-0413     if numel(rxnsToAdd.rxnComps)~=nRxns
-0414         EM='rxnsToAdd.rxnComps must have the same number of elements as rxnsToAdd.rxns';
-0415         dispEM(EM);
-0416     end
-0417     %Fill with standard if it doesn't exist
-0418     if ~isfield(newModel,'rxnComps')
-0419         newModel.rxnComps=ones(nOldRxns,1);
-0420         EM='Adding reactions with compartment information to a model without such information. All existing reactions will be assigned to the first compartment';
-0421         dispEM(EM,false);
-0422     end
-0423     newModel.rxnComps=[newModel.rxnComps;rxnsToAdd.rxnComps(:)];
-0424 else
-0425     %Fill with standard if it doesn't exist
-0426     if isfield(newModel,'rxnComps')
-0427         newModel.rxnComps=[newModel.rxnComps;ones(nRxns,1)];
-0428         %fprintf('NOTE: The added reactions will be assigned to the first
-0429         %compartment\n');
-0430     end
-0431 end
-0432 if isfield(rxnsToAdd,'grRules')
-0433     rxnsToAdd.grRules=convertCharArray(rxnsToAdd.grRules);
-0434     if numel(rxnsToAdd.grRules)~=nRxns
-0435         EM='rxnsToAdd.grRules must have the same number of elements as rxnsToAdd.rxns';
-0436         dispEM(EM);
-0437     end
-0438     %Fill with standard if it doesn't exist
-0439     if ~isfield(newModel,'grRules')
-0440         newModel.grRules=largeFiller;
-0441     end
-0442     newModel.grRules=[newModel.grRules;rxnsToAdd.grRules(:)];
-0443 else
-0444     %Fill with standard if it doesn't exist
-0445     if isfield(newModel,'grRules')
-0446         newModel.grRules=[newModel.grRules;filler];
-0447     end
-0448 end
-0449 
-0450 if isfield(rxnsToAdd,'rxnFrom')
-0451     rxnsToAdd.rxnFrom=convertCharArray(rxnsToAdd.rxnFrom);
-0452     if numel(rxnsToAdd.rxnFrom)~=nRxns
-0453         EM='rxnsToAdd.rxnFrom must have the same number of elements as rxnsToAdd.rxns';
-0454         dispEM(EM);
-0455     end
-0456     %Fill with standard if it doesn't exist
-0457     if ~isfield(newModel,'rxnFrom')
-0458         newModel.rxnFrom=largeFiller;
-0459     end
-0460     newModel.rxnFrom=[newModel.rxnFrom;rxnsToAdd.rxnFrom(:)];
-0461 else
-0462     %Fill with standard if it doesn't exist
-0463     if isfield(newModel,'rxnFrom')
-0464         newModel.rxnFrom=[newModel.rxnFrom;filler];
-0465     end
-0466 end
-0467 
-0468 if isfield(rxnsToAdd,'rxnNotes')
-0469     rxnsToAdd.rxnNotes=convertCharArray(rxnsToAdd.rxnNotes);
-0470     if numel(rxnsToAdd.rxnNotes)~=nRxns
-0471         EM='rxnsToAdd.rxnNotes must have the same number of elements as rxnsToAdd.rxns';
-0472         dispEM(EM);
-0473     end
-0474     %Fill with standard if it doesn't exist
-0475     if ~isfield(newModel,'rxnNotes')
-0476         newModel.rxnNotes=largeFiller;
-0477     end
-0478     newModel.rxnNotes=[newModel.rxnNotes;rxnsToAdd.rxnNotes(:)];
-0479 else
-0480     %Fill with standard if it doesn't exist
-0481     if isfield(newModel,'rxnNotes')
-0482         newModel.rxnNotes=[newModel.rxnNotes;filler];
-0483     end
-0484 end
-0485 
-0486 if isfield(rxnsToAdd,'rxnReferences')
-0487     rxnsToAdd.rxnReferences=convertCharArray(rxnsToAdd.rxnReferences);
-0488     if numel(rxnsToAdd.rxnReferences)~=nRxns
-0489         EM='rxnsToAdd.rxnReferences must have the same number of elements as rxnsToAdd.rxns';
-0490         dispEM(EM);
-0491     end
-0492     %Fill with standard if it doesn't exist
-0493     if ~isfield(newModel,'rxnReferences')
-0494         newModel.rxnReferences=largeFiller;
-0495     end
-0496     newModel.rxnReferences=[newModel.rxnReferences;rxnsToAdd.rxnReferences(:)];
-0497 else
-0498     %Fill with standard if it doesn't exist
-0499     if isfield(newModel,'rxnReferences')
-0500         newModel.rxnReferences=[newModel.rxnReferences;filler];
-0501     end
-0502 end
-0503 
-0504 if isfield(rxnsToAdd,'pwys')
-0505     rxnsToAdd.pwys=convertCharArray(rxnsToAdd.pwys);
-0506     if numel(rxnsToAdd.pwys)~=nRxns
-0507         EM='rxnsToAdd.pwys must have the same number of elements as rxnsToAdd.rxns';
-0508         dispEM(EM);
-0509     end
-0510     %Fill with standard if it doesn't exist
-0511     if ~isfield(newModel,'pwys')
-0512         newModel.pwys=largeFiller;
-0513     end
-0514     newModel.pwys=[newModel.pwys;rxnsToAdd.pwys(:)];
-0515 else
-0516     %Fill with standard if it doesn't exist
-0517     if isfield(newModel,'pwys')
-0518         newModel.pwys=[newModel.pwys;filler];
-0519     end
-0520 end
-0521 
-0522 if isfield(rxnsToAdd,'rxnConfidenceScores')
-0523     if numel(rxnsToAdd.rxnConfidenceScores)~=nRxns
-0524         EM='rxnsToAdd.rxnConfidenceScores must have the same number of elements as rxnsToAdd.rxns';
-0525         dispEM(EM);
-0526     end
-0527     %Fill with standard if it doesn't exist
-0528     if ~isfield(newModel,'rxnConfidenceScores')
-0529         newModel.rxnConfidenceScores=NaN(nOldRxns,1);
-0530     end
-0531     newModel.rxnConfidenceScores=[newModel.rxnConfidenceScores;rxnsToAdd.rxnConfidenceScores(:)];
-0532 else
-0533     %Fill with standard if it doesn't exist
-0534     if isfield(newModel,'rxnConfidenceScores')
-0535         newModel.rxnConfidenceScores=[newModel.rxnConfidenceScores;NaN(nRxns,1)];
-0536     end
-0537 end
-0538 
-0539 if isfield(rxnsToAdd,'rxnDeltaG')
-0540     if numel(rxnsToAdd.rxnDeltaG)~=nRxns
-0541         EM='rxnsToAdd.rxnDeltaG must have the same number of elements as rxnsToAdd.rxns';
-0542         dispEM(EM);
-0543     end
-0544     %Fill with standard if it doesn't exist
-0545     if ~isfield(newModel,'rxnDeltaG')
-0546         newModel.rxnDeltaG=NaN(nOldRxns,1);
-0547     end
-0548     newModel.rxnDeltaG=[newModel.rxnDeltaG;rxnsToAdd.rxnDeltaG(:)];
-0549 else
-0550     %Fill with standard if it doesn't exist
-0551     if isfield(newModel,'rxnDeltaG')
-0552         newModel.rxnDeltaG=[newModel.rxnDeltaG;NaN(nRxns,1)];
-0553     end
-0554 end
-0555 
-0556 
-0557 %***Start parsing the equations and adding the info to the S matrix The
-0558 %mets are matched to model.mets
-0559 if eqnType==1
-0560     [I, J]=ismember(mets,model.mets);
-0561     if ~all(I)
-0562         if allowNewMets==true || ischar(allowNewMets)
-0563             %Add the new mets
-0564             metsToAdd.mets=mets(~I);
-0565             metsToAdd.metNames=metsToAdd.mets;
-0566             metsToAdd.compartments=compartment;
-0567             if ischar(allowNewMets)
-0568                 newModel=addMets(newModel,metsToAdd,true,allowNewMets);
-0569             else
-0570                 newModel=addMets(newModel,metsToAdd,true);
-0571             end
-0572         else
-0573             EM='One or more equations contain metabolites that are not in model.mets. Set allowNewMets to true to allow this function to add metabolites or use addMets to add them before calling this function. Are you sure that eqnType=1?';
-0574             dispEM(EM);
-0575         end
-0576     end
-0577     %Calculate the indexes of the metabolites and add the info
-0578     metIndexes=J;
-0579     metIndexes(~I)=numel(newModel.mets)-sum(~I)+1:numel(newModel.mets);
-0580 end
-0581 
-0582 %Do some stuff that is the same for eqnType=2 and eqnType=3
-0583 if eqnType==2 || eqnType==3
-0584     %For later..
-0585     t2=strcat(model.metNames,'***',model.comps(model.metComps));
-0586 end
-0587 
-0588 %The mets are matched to model.metNames and assigned to "compartment"
-0589 if eqnType==2
-0590     %%Check that the metabolite names aren't present in the same
-0591     %%compartment.
-0592     %Not the neatest way maybe..
-0593     t1=strcat(mets,'***',compartment);
-0594     [I, J]=ismember(t1,t2);
-0595     
-0596     if ~all(I)
-0597         if allowNewMets==true || ischar(allowNewMets)
-0598             %Add the new mets
-0599             metsToAdd.metNames=mets(~I);
-0600             metsToAdd.compartments=compartment;
-0601             if ischar(allowNewMets)
-0602                 newModel=addMets(newModel,metsToAdd,true,allowNewMets);
-0603             else
-0604                 newModel=addMets(newModel,metsToAdd,true);
-0605             end
-0606         else
-0607             EM='One or more equations contain metabolites that are not in model.mets. Set allowNewMets to true to allow this function to add metabolites or use addMets to add them before calling this function';
-0608             dispEM(EM);
-0609         end
-0610     end
-0611     
-0612     %Calculate the indexes of the metabolites
-0613     metIndexes=J;
-0614     metIndexes(~I)=numel(newModel.mets)-sum(~I)+1:numel(newModel.mets);
-0615 end
-0616 
-0617 %The equations are on the form metNames[compName]
-0618 if eqnType==3
-0619     %Parse the metabolite names
-0620     metNames=cell(numel(mets),1);
-0621     compartments=metNames;
-0622     for i=1:numel(mets)
-0623         starts=max(strfind(mets{i},'['));
-0624         ends=max(strfind(mets{i},']'));
-0625         
-0626         %Check that the formatting is correct
-0627         if isempty(starts) || isempty(ends) || ends<numel(mets{i})
-0628             EM=['The metabolite ' mets{i} ' is not correctly formatted for eqnType=3'];
-0629             dispEM(EM);
-0630         end
-0631         
-0632         %Check that the compartment is correct
-0633         compartments{i}=mets{i}(starts+1:ends-1);
-0634         I=ismember(compartments(i),newModel.comps);
-0635         if ~I
-0636             EM=['The metabolite ' mets{i} ' has a compartment that is not in model.comps'];
-0637             dispEM(EM);
-0638         end
-0639         metNames{i}=mets{i}(1:starts-1);
-0640     end
-0641     
-0642     %Check if the metabolite exists already
-0643     t1=strcat(metNames,'***',compartments);
-0644     [I, J]=ismember(t1,t2);
-0645     
-0646     if ~all(I)
-0647         if allowNewMets==true | ischar(allowNewMets)
-0648             %Add the new mets
-0649             metsToAdd.metNames=metNames(~I);
-0650             metsToAdd.compartments=compartments(~I);
-0651             if ischar(allowNewMets)
-0652                 newModel=addMets(newModel,metsToAdd,true,allowNewMets);
-0653             else
-0654                 newModel=addMets(newModel,metsToAdd,true);
-0655             end
-0656         else
-0657             EM='One or more equations contain metabolites that are not in model.metNames. Set allowNewMets to true to allow this function to add metabolites or use addMets to add them before calling this function';
-0658             dispEM(EM);
-0659         end
-0660     end
-0661     
-0662     %Calculate the indexes of the metabolites
-0663     metIndexes=J;
-0664     metIndexes(~I)=numel(newModel.mets)-sum(~I)+1:numel(newModel.mets);
-0665 end
-0666 
-0667 %Add the info to the stoichiometric matrix
-0668 newModel.S=[newModel.S sparse(size(newModel.S,1),nRxns)];
-0669 
-0670 for i=1:nRxns
-0671     newModel.S(metIndexes,nOldRxns+i)=S(:,i);
-0672     %Parse the grRules and check whether all genes in grRules appear in
-0673     %genes
-0674     if isfield(newModel,'grRules')
-0675         rule=newModel.grRules{nOldRxns+i};
-0676         rule=strrep(rule,'(','');
-0677         rule=strrep(rule,')','');
-0678         rule=strrep(rule,' or ',' ');
-0679         rule=strrep(rule,' and ',' ');
-0680         genes=regexp(rule,' ','split');
-0681         [I, J]=ismember(genes,newModel.genes);
-0682         if ~all(I) && any(rule)
-0683             EM=['Not all genes for reaction ' rxnsToAdd.rxns{i} ' were found in model.genes. If needed, add genes with addGenesRaven before calling this function, or set the ''allowNewGenes'' flag to true'];
-0684             dispEM(EM);
-0685         end
-0686     end
-0687 end
-0688 
-0689 %Make temporary minimal model structure with only new rxns, to parse to
-0690 %standardizeGrRules
-0691 newRxnsModel.genes=newModel.genes;
-0692 newRxnsModel.grRules=newModel.grRules(length(model.rxns)+1:end);
-0693 newRxnsModel.rxns=newModel.rxns(length(model.rxns)+1:end);
-0694 
-0695 %Fix grRules and reconstruct rxnGeneMat
-0696 [grRules,rxnGeneMat] = standardizeGrRules(newRxnsModel,true);
-0697 newModel.rxnGeneMat = [newModel.rxnGeneMat; rxnGeneMat];
-0698 newModel.grRules = [newModel.grRules(1:nOldRxns); grRules];
-0699 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/addRxnsGenesMets.html b/doc/core/addRxnsGenesMets.html deleted file mode 100644 index 0ab9c27ba..000000000 --- a/doc/core/addRxnsGenesMets.html +++ /dev/null @@ -1,274 +0,0 @@ - - - - Description of addRxnsGenesMets - - - - - - - - - -
Home > core > addRxnsGenesMets.m
- - - -

addRxnsGenesMets -

- -

PURPOSE ^

-
addRxnsGenesMets
- -

SYNOPSIS ^

-
function model=addRxnsGenesMets(model,sourceModel,rxns,addGene,rxnNote,confidence)
- -

DESCRIPTION ^

-
 addRxnsGenesMets
-   Copies reactions from a source model to a new model, including
-   (new) metabolites and genes
-
-   model           draft model where reactions should be copied to
-   sourceModel     model where reactions and metabolites are sourced from
-   rxns            cell array with reaction IDs (from source model). Can also
-                   be string if only one reaction is added
-   addGene         three options:
-                   false   no genes are annotated to the new reactions
-                   true    grRules ared copied from the sourceModel and
-                           new genes are added when required
-                   string or cell array
-                           new grRules are specified as string or cell
-                           array, and any new genes are added when
-                           required
-                   (optional, default false)
-   rxnNote         cell array with strings explaining why reactions were copied
-                   to the model, to be included as newModel.rxnNotes. Can also
-                   be string if same rxnNotes should be added for each new
-                   reaction, or only one reaction is to be added (optional, default
-                   'Added via addRxnsAndMets()')
-   confidence      integer specifying confidence score for all reactions.
-                   4:  biochemical data: direct evidence from enzymes
-                       assays
-                   3:  genetic data: knockout/-in or overexpression
-                       analysis
-                   2:  physiological data: indirect evidence, e.g.
-                       secretion products or defined medium requirement
-                       sequence data: genome annotation
-                   1:  modeling data: required for functional model,
-                       hypothetical reaction
-                   0:  no evidence
-                   following doi:10.1038/nprot.2009.203 (optional, default 0)
-
-   newModel        an updated model structure
-
-     This function only works if the draft model and source model follow
-    the same metabolite and compartment naming convention. Metabolites are
-    only matched by metaboliteName[compartment]. Useful if one wants to copy
-    additional reactions from source to draft after getModelFromHomology was
-    used involving the same models.
-
- Usage: newModel=addRxnsGenesMets(model,sourceModel,rxns,addGene,rxnNote,confidence)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function model=addRxnsGenesMets(model,sourceModel,rxns,addGene,rxnNote,confidence)
-0002 % addRxnsGenesMets
-0003 %   Copies reactions from a source model to a new model, including
-0004 %   (new) metabolites and genes
-0005 %
-0006 %   model           draft model where reactions should be copied to
-0007 %   sourceModel     model where reactions and metabolites are sourced from
-0008 %   rxns            cell array with reaction IDs (from source model). Can also
-0009 %                   be string if only one reaction is added
-0010 %   addGene         three options:
-0011 %                   false   no genes are annotated to the new reactions
-0012 %                   true    grRules ared copied from the sourceModel and
-0013 %                           new genes are added when required
-0014 %                   string or cell array
-0015 %                           new grRules are specified as string or cell
-0016 %                           array, and any new genes are added when
-0017 %                           required
-0018 %                   (optional, default false)
-0019 %   rxnNote         cell array with strings explaining why reactions were copied
-0020 %                   to the model, to be included as newModel.rxnNotes. Can also
-0021 %                   be string if same rxnNotes should be added for each new
-0022 %                   reaction, or only one reaction is to be added (optional, default
-0023 %                   'Added via addRxnsAndMets()')
-0024 %   confidence      integer specifying confidence score for all reactions.
-0025 %                   4:  biochemical data: direct evidence from enzymes
-0026 %                       assays
-0027 %                   3:  genetic data: knockout/-in or overexpression
-0028 %                       analysis
-0029 %                   2:  physiological data: indirect evidence, e.g.
-0030 %                       secretion products or defined medium requirement
-0031 %                       sequence data: genome annotation
-0032 %                   1:  modeling data: required for functional model,
-0033 %                       hypothetical reaction
-0034 %                   0:  no evidence
-0035 %                   following doi:10.1038/nprot.2009.203 (optional, default 0)
-0036 %
-0037 %   newModel        an updated model structure
-0038 %
-0039 %     This function only works if the draft model and source model follow
-0040 %    the same metabolite and compartment naming convention. Metabolites are
-0041 %    only matched by metaboliteName[compartment]. Useful if one wants to copy
-0042 %    additional reactions from source to draft after getModelFromHomology was
-0043 %    used involving the same models.
-0044 %
-0045 % Usage: newModel=addRxnsGenesMets(model,sourceModel,rxns,addGene,rxnNote,confidence)
-0046 
-0047 if nargin<6
-0048     confidence=0;
-0049 end
-0050 rxns=convertCharArray(rxns);
-0051 if nargin<5
-0052     rxnNote={'Added via addRxnsGenesMets()'};
-0053 else
-0054     rxnNote=convertCharArray(rxnNote);
-0055 end
-0056 if numel(rxnNote)==1 && numel(rxns)>1
-0057     rxnNoteArray=cell(1,numel(rxns));
-0058     rxnNoteArray(:)=rxnNote;
-0059     rxnNote=rxnNoteArray;
-0060 end
-0061 if nargin<4
-0062     addGene=false;
-0063 end
-0064 
-0065 % Obtain indexes of reactions in source model
-0066 [notNewRxn,oldRxn]=ismember(rxns,model.rxns);
-0067 rxns=rxns(~notNewRxn);
-0068 if isempty(rxns)
-0069     error('All reactions are already in the model.');
-0070 elseif ~isempty(notNewRxn)
-0071     fprintf('The following reactions were already present in the model and will not be added:\n')
-0072     fprintf([strjoin(model.rxns(oldRxn(find(oldRxn))),'\n') '\n'])
-0073 end
-0074 
-0075 [~, rxnIdx]=ismember(rxns,sourceModel.rxns); % Get rxnIDs
-0076 if any(rxnIdx==0)
-0077     dispEM('The following reaction IDs could not be found in the source model:',true,...
-0078         rxns(rxnIdx==0));
-0079 end
-0080 
-0081 % Add new metabolites
-0082 metIdx=find(any(sourceModel.S(:,rxnIdx),2)); % Get metabolite IDs
-0083 % Many of the metabolites in are already in the draft model, so only add
-0084 % the new metabolites
-0085 
-0086 % Match by metNames[metComps]. First make these structures for each model.
-0087 metCompsN =cellstr(num2str(model.metComps));
-0088 map=containers.Map(cellstr(num2str(transpose([1:length(model.comps)]))),model.comps);
-0089 metCompsN = map.values(metCompsN);
-0090 metCompsN = strcat(model.metNames,'[',metCompsN,']');
-0091 
-0092 sourcemetCompsN=cellstr(num2str(sourceModel.metComps));
-0093 map=containers.Map(cellstr(num2str(transpose([1:length(sourceModel.comps)]))),sourceModel.comps);
-0094 sourcemetCompsN = map.values(sourcemetCompsN);
-0095 sourcemetCompsN=strcat(sourceModel.metNames,'[',sourcemetCompsN,']');
-0096 
-0097 newMetCompsN=sourcemetCompsN(metIdx);
-0098 notNewMet=newMetCompsN(ismember(newMetCompsN,metCompsN));
-0099 
-0100 if ~isempty(notNewMet)
-0101     fprintf('\nThe following metabolites were already present in the model and will not be added:\n')
-0102     fprintf([strjoin(transpose(notNewMet),'\n') '\n'])
-0103 end
-0104 
-0105 metIdx=metIdx(~ismember(sourcemetCompsN(metIdx),metCompsN));
-0106 
-0107 if ~isempty(metIdx)
-0108     fprintf('\nThe following metabolites will be added to the model:\n')
-0109     fprintf([strjoin(transpose(sourcemetCompsN(metIdx)),'\n') '\n'])
-0110     
-0111     if isfield(sourceModel,'mets')
-0112         metsToAdd.mets=sourceModel.mets(metIdx);
-0113     end
-0114     if isfield(sourceModel,'metNames')
-0115         metsToAdd.metNames=sourceModel.metNames(metIdx);
-0116     end
-0117     if isfield(sourceModel,'metFormulas')
-0118         metsToAdd.metFormulas=sourceModel.metFormulas(metIdx);
-0119     end
-0120     if isfield(sourceModel,'metCharges')
-0121         metsToAdd.metCharges=sourceModel.metCharges(metIdx);
-0122     end
-0123     if isfield(sourceModel,'metMiriams')
-0124         metsToAdd.metMiriams=sourceModel.metMiriams(metIdx);
-0125     end
-0126     if isfield(sourceModel,'metNotes')
-0127         metsToAdd.metNotes=sourceModel.metNotes(metIdx);
-0128     end
-0129     if isfield(sourceModel,'inchis')
-0130         metsToAdd.inchis=sourceModel.inchis(metIdx);
-0131     end
-0132     if isfield(sourceModel,'metSmiles')
-0133         metsToAdd.metSmiles=sourceModel.metSmiles(metIdx);
-0134     end
-0135     if isfield(sourceModel,'metDeltaG')
-0136         metsToAdd.metDeltaG=sourceModel.metDeltaG(metIdx);
-0137     end
-0138     
-0139     metsToAdd.compartments=strtrim(cellstr(num2str(sourceModel.metComps(metIdx)))); % Convert from compartment string to compartment number
-0140     [~,idx]=ismember(metsToAdd.compartments,strsplit(num2str(1:length(sourceModel.comps)))); % Match compartment number to compartment abbreviation
-0141     metsToAdd.compartments=sourceModel.comps(idx); % Fill in compartment abbreviations
-0142     
-0143     model=addMets(model,metsToAdd);
-0144 end
-0145 fprintf('\nNumber of metabolites added to the model:\n')
-0146 fprintf([num2str(numel(metIdx)),'\n'])
-0147 
-0148 % Add new genes
-0149 if ~islogical(addGene) | addGene ~= false
-0150     if ischar(addGene)
-0151         rxnToAdd.grRules={addGene};
-0152     elseif iscell(addGene)
-0153         rxnToAdd.grRules=addGene(~notNewRxn); 
-0154     else
-0155         rxnToAdd.grRules=sourceModel.grRules(rxnIdx); % Get the relevant grRules
-0156     end
-0157 end
-0158 % Add new reactions
-0159 rxnToAdd.equations=constructEquations(sourceModel,rxnIdx);
-0160 rxnToAdd.rxnNames=sourceModel.rxnNames(rxnIdx);
-0161 rxnToAdd.rxns=sourceModel.rxns(rxnIdx);
-0162 rxnToAdd.lb=sourceModel.lb(rxnIdx);
-0163 rxnToAdd.ub=sourceModel.ub(rxnIdx);
-0164 rxnToAdd.rxnNotes(:)=rxnNote(~notNewRxn);
-0165 rxnToAdd.rxnConfidenceScores=NaN(1,numel(rxnToAdd.rxns));
-0166 if ~isnumeric(confidence)
-0167     EM='confidence score must be numeric';
-0168     dispEM(EM, true);
-0169 end
-0170 rxnToAdd.rxnConfidenceScores(:)=confidence;
-0171 if isfield(sourceModel,'rxnDeltaG')
-0172     rxnToAdd.rxnDeltaG=sourceModel.rxnDeltaG(rxnIdx);
-0173 end
-0174 if isfield(sourceModel,'subSystems')
-0175     rxnToAdd.subSystems=sourceModel.subSystems(rxnIdx);
-0176 end
-0177 if isfield(sourceModel,'eccodes')
-0178     rxnToAdd.eccodes=sourceModel.eccodes(rxnIdx);
-0179 end
-0180 model=addRxns(model,rxnToAdd,3,'',false,true);
-0181 
-0182 fprintf('\nNumber of reactions added to the model:\n')
-0183 fprintf([num2str(numel(rxnIdx)),'\n'])
-0184 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/addTransport.html b/doc/core/addTransport.html deleted file mode 100644 index 21b58cbe2..000000000 --- a/doc/core/addTransport.html +++ /dev/null @@ -1,250 +0,0 @@ - - - - Description of addTransport - - - - - - - - - -
Home > core > addTransport.m
- - - -

addTransport -

- -

PURPOSE ^

-
addTransport
- -

SYNOPSIS ^

-
function [model, addedRxns]=addTransport(model,fromComp,toComps,metNames,isRev,onlyToExisting,prefix)
- -

DESCRIPTION ^

-
 addTransport
-   Adds transport reactions between compartments
-
-   model           a model structure
-   fromComp        the id of the compartment to transport from (should
-                   match model.comps)
-   toComps         a cell array of compartment names to transport to (should
-                   match model.comps)
-   metNames        the metabolite names to add transport for (optional, all
-                   metabolites in fromComp)
-   isRev           true if the transport reactions should be reversible
-                   (optional, default true)
-   onlyToExisting  true if transport of a metabolite should only be added
-                   if it already exists in toComp. If false, then new metabolites
-                   are added with addMets first (optional, default true)
-   prefix          string specifying prefix to reaction IDs (optional, default
-                   'tr_')
-
-   This is a faster version than addRxns when adding transport reactions.
-   New reaction names are formatted as "metaboliteName, fromComp-toComp", 
-   while new reaction IDs are sequentially counted with a tr_ prefix:
-   e.g. tr_0001, tr_0002, etc.
-
- Usage: [model, addedRxns]=addTransport(model,fromComp,toComps,metNames,...
-           isRev,onlyToExisting,prefix)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function [model, addedRxns]=addTransport(model,fromComp,toComps,metNames,isRev,onlyToExisting,prefix)
-0002 % addTransport
-0003 %   Adds transport reactions between compartments
-0004 %
-0005 %   model           a model structure
-0006 %   fromComp        the id of the compartment to transport from (should
-0007 %                   match model.comps)
-0008 %   toComps         a cell array of compartment names to transport to (should
-0009 %                   match model.comps)
-0010 %   metNames        the metabolite names to add transport for (optional, all
-0011 %                   metabolites in fromComp)
-0012 %   isRev           true if the transport reactions should be reversible
-0013 %                   (optional, default true)
-0014 %   onlyToExisting  true if transport of a metabolite should only be added
-0015 %                   if it already exists in toComp. If false, then new metabolites
-0016 %                   are added with addMets first (optional, default true)
-0017 %   prefix          string specifying prefix to reaction IDs (optional, default
-0018 %                   'tr_')
-0019 %
-0020 %   This is a faster version than addRxns when adding transport reactions.
-0021 %   New reaction names are formatted as "metaboliteName, fromComp-toComp",
-0022 %   while new reaction IDs are sequentially counted with a tr_ prefix:
-0023 %   e.g. tr_0001, tr_0002, etc.
-0024 %
-0025 % Usage: [model, addedRxns]=addTransport(model,fromComp,toComps,metNames,...
-0026 %           isRev,onlyToExisting,prefix)
-0027 
-0028 fromComp=char(fromComp);
-0029 [I, fromID]=ismember(model.comps,fromComp);
-0030 fromID=find(fromID);
-0031 if sum(I)~=1
-0032     EM='fromComps must have exactly one match in model.comps';
-0033     dispEM(EM);
-0034 end
-0035 toComps=convertCharArray(toComps);
-0036 [I, toIDs]=ismember(toComps,model.comps);
-0037 if ~all(I)
-0038     EM='All compartments in toComps must have a match in model.comps';
-0039     dispEM(EM);
-0040 end
-0041 if nargin<4
-0042     %Find all metabolites in fromComp
-0043     metNames=model.metNames(model.metComps==fromID);
-0044 elseif isempty(metNames)
-0045     %Find all metabolites in fromComp
-0046     metNames=model.metNames(ismember(model.metComps,model.comps(fromID)));
-0047 else
-0048     metNames=convertCharArray(metNames);
-0049 end
-0050 
-0051 if nargin<5
-0052     isRev=true;
-0053 end
-0054 if nargin<6
-0055     onlyToExisting=true;
-0056 end
-0057 if nargin<7
-0058     prefix='tr_';
-0059 else
-0060     prefix=char(prefix);
-0061 end
-0062 
-0063 %Check that the names are unique
-0064 if numel(unique(metNames))~=numel(metNames)
-0065     dispEM('Not all metabolite names are unique');
-0066 end
-0067 
-0068 %Get the indexes of the mets in fromComp
-0069 I=find(model.metComps==fromID);
-0070 [J, K]=ismember(metNames,model.metNames(I));
-0071 if ~all(J)
-0072     EM='Not all metabolites in metNames exist in fromComp';
-0073     dispEM(EM);
-0074 end
-0075 fromMets=I(K); %These are the ids of the metabolites to transport. The order corresponds to metNames
-0076 addedRxns={};
-0077 %Loop through and add for each compartment in toComps
-0078 for i=1:numel(toComps)
-0079     fromMetsInComp=fromMets; %If onlyToExisting==true then not all mets are transported to each compartment
-0080     %Get the indexes of the mets in the compartment
-0081     I=find(model.metComps==toIDs(i));
-0082     [J, K]=ismember(metNames,model.metNames(I));
-0083     if onlyToExisting==true || all(J)
-0084         toMets=I(K(J)); %Only look at the existing ones
-0085         fromMetsInComp=fromMetsInComp(J);
-0086     else
-0087         %This is if not all metabolites exist in the target compartment,
-0088         %and they should be added
-0089         metsToAdd.metNames=metNames(J==0);
-0090         metsToAdd.compartments=toComps{i};
-0091         model=addMets(model,metsToAdd);
-0092         
-0093         %Redo the mapping when all mets are there. A bit lazy, but it's
-0094         %fast anyways
-0095         I=find(model.metComps==toIDs(i));
-0096         [~, K]=ismember(metNames,model.metNames(I));
-0097         toMets=I(K); %All are guaranteed to be found now
-0098     end
-0099     
-0100     %Construct the S matrix
-0101     nRxns=numel(fromMetsInComp);
-0102     newS=zeros(numel(model.mets),nRxns);
-0103     newS(sub2ind(size(newS),fromMetsInComp(:),(1:nRxns)'))=-1;
-0104     newS(sub2ind(size(newS),toMets(:),(1:nRxns)'))=1;
-0105     
-0106     %Add the reactions
-0107     model.S=[model.S sparse(newS)];
-0108     if isfield(model.annotation,'defaultLB')
-0109         lb = model.annotation.defaultLB;
-0110         ub = model.annotation.defaultUB;
-0111     else
-0112         lb = -inf;
-0113         ub = inf;
-0114     end
-0115     if isRev==true
-0116         model.lb=[model.lb;ones(nRxns,1)*lb];
-0117         model.rev=[model.rev;ones(nRxns,1)];
-0118     else
-0119         model.lb=[model.lb;zeros(nRxns,1)];
-0120         model.rev=[model.rev;zeros(nRxns,1)];
-0121     end
-0122     model.ub=[model.ub;ones(nRxns,1)*ub];
-0123     model.c=[model.c;zeros(nRxns,1)];
-0124     
-0125     %Add annotation
-0126     filler=cell(nRxns,1);
-0127     filler(:)={''};
-0128     addedRxnsID=generateNewIds(model,'rxns',prefix,nRxns);
-0129     addedRxnsName=transpose(strcat(metNames, {' transport, '}, model.compNames(fromID), '-', model.compNames(toIDs(i))));
-0130     model.rxns=[model.rxns;addedRxnsID];
-0131     model.rxnNames=[model.rxnNames;addedRxnsName];
-0132     
-0133     if isfield(model,'eccodes')
-0134         model.eccodes=[model.eccodes;filler];
-0135     end
-0136     if isfield(model,'subSystems')
-0137         isNested = any(cellfun(@(x) iscell(x), model.subSystems));
-0138         ssFiller = filler;
-0139         if isRev==1
-0140             ssFiller(:) = {['Transport between ' fromComp ' and ' toComps{i}]};
-0141         else
-0142             ssFiller(:) = {['Transport from ' fromComp ' to ' toComps{i}]};
-0143         end
-0144         if isNested
-0145             ssFiller = cellfun(@(x) {x}, ssFiller, 'uni', 0);
-0146         end
-0147         model.subSystems=[model.subSystems;ssFiller];
-0148     end
-0149     if isfield(model,'grRules')
-0150         model.grRules=[model.grRules;filler];
-0151     end
-0152     if isfield(model,'rxnFrom')
-0153         model.rxnFrom=[model.rxnFrom;filler];
-0154     end
-0155     if isfield(model,'rxnMiriams')
-0156         model.rxnMiriams=[model.rxnMiriams;cell(nRxns,1)];
-0157     end
-0158     if isfield(model,'rxnComps')
-0159         model.rxnComps=[model.rxnComps;ones(nRxns,1)];
-0160         fprintf('NOTE: The added transport reactions will be added to the first compartment\n');
-0161     end
-0162     if isfield(model,'rxnGeneMat')
-0163         model.rxnGeneMat=[model.rxnGeneMat;sparse(nRxns,numel(model.genes))];
-0164     end
-0165     if isfield(model,'rxnNotes')
-0166         model.rxnNotes=[model.rxnNotes;filler];
-0167     end
-0168     if isfield(model,'rxnReferences')
-0169         model.rxnReferences=[model.rxnReferences;filler];
-0170     end
-0171     if isfield(model,'rxnConfidenceScores')
-0172         model.rxnConfidenceScores=[model.rxnConfidenceScores;ones(nRxns,1)];
-0173     end
-0174     if isfield(model,'rxnDeltaG')
-0175         model.rxnDeltaG=[model.rxnDeltaG;zeros(nRxns,1)];
-0176     end
-0177     addedRxns = [addedRxns; addedRxnsID];
-0178 end
-0179 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/analyzeSampling.html b/doc/core/analyzeSampling.html deleted file mode 100644 index 8394c477b..000000000 --- a/doc/core/analyzeSampling.html +++ /dev/null @@ -1,250 +0,0 @@ - - - - Description of analyzeSampling - - - - - - - - - -
Home > core > analyzeSampling.m
- - - -

analyzeSampling -

- -

PURPOSE ^

-
analyzeSampling
- -

SYNOPSIS ^

-
function scores=analyzeSampling(Tex, df, solutionsA, solutionsB, printResults)
- -

DESCRIPTION ^

-
 analyzeSampling
-   Compares the significance of change in flux between two conditions with
-   the significance of change in gene expression
-
-   Tex             a vector of t-scores for the change in gene expression
-                   for each reaction. This score could be the Student t
-                   between the two conditions, or you can calculate it from
-                   a p-value (by computing the inverse of the so called error
-                   function). If you choose the second alternative you should
-                   be aware that the transcripts that increased in expression
-                   level should have positive values and those who decreased
-                   in expression level should have negative values (the
-                   p-values only tell you if the fluxes changed or not but
-                   not in which direction)
-   df              the degrees of freedom in the t-test
-   solutionsA      random solutions for the reference condition (as
-                   generated by randomSampling)
-   solutionsB      random solutions for the test condition (as generated
-                   by randomSampling)
-   printResults    prints the most significant reactions in each category
-                   (optional, default false)
-
-   scores          a Nx3 column matrix with the probabilities of a reaction:
-                   1) changing both in flux and expression in the same direction
-                   2) changing in expression but not in flux
-                   3) changing in flux but not in expression or changing
-                      in opposed directions in flux and expression.
-
- Usage: scores=analyzeSampling(Tex, df, solutionsA, solutionsB, printResults)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 function scores=analyzeSampling(Tex, df, solutionsA, solutionsB, printResults)
-0002 % analyzeSampling
-0003 %   Compares the significance of change in flux between two conditions with
-0004 %   the significance of change in gene expression
-0005 %
-0006 %   Tex             a vector of t-scores for the change in gene expression
-0007 %                   for each reaction. This score could be the Student t
-0008 %                   between the two conditions, or you can calculate it from
-0009 %                   a p-value (by computing the inverse of the so called error
-0010 %                   function). If you choose the second alternative you should
-0011 %                   be aware that the transcripts that increased in expression
-0012 %                   level should have positive values and those who decreased
-0013 %                   in expression level should have negative values (the
-0014 %                   p-values only tell you if the fluxes changed or not but
-0015 %                   not in which direction)
-0016 %   df              the degrees of freedom in the t-test
-0017 %   solutionsA      random solutions for the reference condition (as
-0018 %                   generated by randomSampling)
-0019 %   solutionsB      random solutions for the test condition (as generated
-0020 %                   by randomSampling)
-0021 %   printResults    prints the most significant reactions in each category
-0022 %                   (optional, default false)
-0023 %
-0024 %   scores          a Nx3 column matrix with the probabilities of a reaction:
-0025 %                   1) changing both in flux and expression in the same direction
-0026 %                   2) changing in expression but not in flux
-0027 %                   3) changing in flux but not in expression or changing
-0028 %                      in opposed directions in flux and expression.
-0029 %
-0030 % Usage: scores=analyzeSampling(Tex, df, solutionsA, solutionsB, printResults)
-0031 
-0032 if nargin<5
-0033     printResults=false;
-0034 end
-0035 
-0036 nRxns=numel(Tex);
-0037 pM=zeros(nRxns,1);
-0038 pH=zeros(nRxns,1);
-0039 pR=zeros(nRxns,1);
-0040 
-0041 %Check that the number of reactions is the same in both expression and flux
-0042 if nRxns~=size(solutionsA,1)
-0043     EM='The number of reactions must be the same in Tex as in solutionsA';
-0044     dispEM(EM);
-0045 end
-0046 
-0047 %Get the Z-score and mean for the solutions
-0048 mA=mean(solutionsA,2);
-0049 mB=mean(solutionsB,2);
-0050 Zf=getFluxZ(solutionsA, solutionsB);
-0051 
-0052 %Clear up the tex if there are elements that are NaN or +/- Inf.
-0053 I=isnan(Tex) | isinf(Tex);
-0054 if any(I)
-0055     EM='There are t-scores that are NaN or +/- Inf. These values are changed to 0.0';
-0056     dispEM(EM,false);
-0057 end
-0058 Tex(I)=0;
-0059 
-0060 for i=1:nRxns
-0061     %Check how the flux has changed. The means are needed because to
-0062     %differentiate between a positive flux changing to a smaller flux and a
-0063     %negative flux changing to a more negative flux (which is a larger
-0064     %flux)
-0065     I=mB(i)/mA(i);
-0066     if I<0
-0067         pM(i)=erf(abs(Zf(i)));
-0068         pH(i)=(1-pM(i))*(2*tcdf(abs(Tex(i)),df)-1);
-0069         pR(i)=0;
-0070     else
-0071         if mB(i)<0
-0072             Zf(i)=Zf(i)*-1;
-0073         end
-0074     end
-0075 
-0076     I=Zf(i)/Tex(i);
-0077     if I<0
-0078         pM(i)=erf(abs(Zf(i)));
-0079         pH(i)=(1-pM(i))*(2*tcdf(abs(Tex(i)),df)-1);
-0080         pR(i)=0;
-0081     else
-0082         pR(i)=erf(abs(Zf(i)))*(2*tcdf(abs(Tex(i)),df)-1);
-0083         pH(i)=(2*tcdf(abs(Tex(i)),df)-1)*(1-erf(abs(Zf(i))));
-0084         pM(i)=erf(abs(Zf(i)))*(1-(2*tcdf(abs(Tex(i)),df)-1));
-0085     end
-0086 end
-0087 
-0088 scores=[pR pH pM];
-0089 
-0090 if printResults==true
-0091     fprintf('TOP SCORING REACTIONS\n\n');
-0092     %The top 10 hits in the first category
-0093     [I, J]=sort(pR,'descend');
-0094     fprintf('Reactions which change both in flux and expression in the same direction\nReaction\tProbability\n');
-0095     for i=1:10
-0096         fprintf([num2str(J(i)) '\t' num2str(I(i)) '\n']);
-0097     end
-0098 
-0099     %The top 10 hits in the first category
-0100     [I, J]=sort(pH,'descend');
-0101     fprintf('\nReactions which change in expression but not in flux\nReaction\tProbability\n');
-0102     for i=1:10
-0103         fprintf([num2str(J(i)) '\t' num2str(I(i)) '\n']);
-0104     end
-0105 
-0106     %The top 10 hits in the first category
-0107     [I, J]=sort(pM,'descend');
-0108     fprintf('\nReactions which change in flux but not in expression, or in opposed directions in flux and expression\nReaction\tProbability\n');
-0109     for i=1:10
-0110         fprintf([num2str(J(i)) '\t' num2str(I(i)) '\n']);
-0111     end
-0112 end
-0113 end
-0114 
-0115 function p = tcdf(t,v,uflag)
-0116 % TCDF Student's T cumulative distribution function (cdf).
-0117 %
-0118 % P = TCDF(X,V) computes the cdf for Student's T distribution
-0119 % with V degrees of freedom, at the values in X. V must be a
-0120 % scalar or have the same size as T.
-0121 %
-0122 % P = TCDF(X,V,'upper') computes it for the upper tail instead
-0123 % of the lower tail.
-0124 %
-0125 % This is an alternative to the TCDF function that is implemented
-0126 % in the Matlab statistics toolbox. This version originates from
-0127 % http://www.statsci.org/matlab/statbox.html and originally was called TP.
-0128 % It has been renamed to TCDF for drop-in compatibility with the Matlab
-0129 % version.
-0130 %
-0131 % Gordon Smyth, University of Queensland, gks@maths.uq.edu.au
-0132 % 3 Apr 97
-0133 %
-0134 % NaN compatible - Markus Bauer and Eric Maris, FCDC
-0135 % 27 Jan 2005
-0136 %
-0137 % fixed bug concerning NaN compatibility
-0138 % 21 Aug 2006, Markus Siegel
-0139 %
-0140 % added support for upper tail, see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=3045
-0141 % 13 Jan 2016, Robert Oostenveld
-0142 %
-0143 % taken from https://github.com/fieldtrip/fieldtrip/blob/master/external/stats/tcdf.m
-0144 % 05 May 2022
-0145 
-0146 if v <= 0, error('Degrees of freedom must be positive.'); end
-0147 
-0148 % resize v if necessary
-0149 if all(size(v)==1)
-0150     v = ones(size(t))*v;
-0151 end
-0152 
-0153 %check for NaN's - don't do calculations on them, give those out as NaNs
-0154 if any( not(isfinite(t(:))) | not(isfinite(v(:))) )
-0155     sel = find(isfinite(t) & isfinite(v));
-0156     x=nan(size(t));
-0157     p=nan(size(t));
-0158     x(sel) = t(sel).^2 ./ (v(sel) + t(sel).^2) ;
-0159     p(sel) = 0.5 .* ( 1 + sign(t(sel)) .* betainc( x(sel), 0.5, 0.5*v(sel) ) );
-0160 else
-0161     x = t.^2 ./ (v + t.^2) ;
-0162     p = 0.5 .* ( 1 + sign(t) .* betainc( x, 0.5, 0.5*v ) );
-0163 end
-0164 
-0165 if nargin==3
-0166     if strcmp(uflag, 'upper')
-0167         % compute it for the upper tail instead of the lower tail
-0168         p = 1-p;
-0169     else
-0170         error('incorrect specification of uflag');
-0171     end
-0172 end
-0173 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/buildEquation.html b/doc/core/buildEquation.html deleted file mode 100644 index af52df23d..000000000 --- a/doc/core/buildEquation.html +++ /dev/null @@ -1,122 +0,0 @@ - - - - Description of buildEquation - - - - - - - - - -
Home > core > buildEquation.m
- - - -

buildEquation -

- -

PURPOSE ^

-
buildEquation
- -

SYNOPSIS ^

-
function equationString=buildEquation(mets,stoichCoeffs,isrev)
- -

DESCRIPTION ^

-
 buildEquation
-   Construct single equation string for a given reaction
-
-   mets            cell array with metabolites involved in the reaction.
-   stoichCoeffs    vector with corresponding stoichiometric coeffs.
-   isrev           logical indicating if the reaction is or not
-                   reversible.
-
-   equationString  equation as a string
-
-    Usage: equationString=buildEquation(mets,stoichCoeffs,isrev)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 function equationString=buildEquation(mets,stoichCoeffs,isrev)
-0002 % buildEquation
-0003 %   Construct single equation string for a given reaction
-0004 %
-0005 %   mets            cell array with metabolites involved in the reaction.
-0006 %   stoichCoeffs    vector with corresponding stoichiometric coeffs.
-0007 %   isrev           logical indicating if the reaction is or not
-0008 %                   reversible.
-0009 %
-0010 %   equationString  equation as a string
-0011 %
-0012 %    Usage: equationString=buildEquation(mets,stoichCoeffs,isrev)
-0013 
-0014 mets=convertCharArray(mets);
-0015 if ~isnumeric(stoichCoeffs)
-0016     EM = 'stoichCoeffs must be a numeric vector';
-0017     dispEM(EM);
-0018 elseif ~islogical(isrev)
-0019     EM = 'isrev must be a logical';
-0020     dispEM(EM);
-0021 elseif length(mets) ~= length(stoichCoeffs)
-0022     EM = 'lengths of mets and stoichCoeffs should be the same';
-0023     dispEM(EM);
-0024 end
-0025 
-0026 %Reactant half:
-0027 reactants       = mets(stoichCoeffs<0);
-0028 reactantsCoeffs = abs(stoichCoeffs(stoichCoeffs<0));
-0029 reactantsEqn    = concatenateEquation(reactants,reactantsCoeffs);
-0030 
-0031 %Product half:
-0032 products       = mets(stoichCoeffs>0);
-0033 productsCoeffs = abs(stoichCoeffs(stoichCoeffs>0));
-0034 productsEqn    = concatenateEquation(products,productsCoeffs);
-0035 
-0036 %Full equation:
-0037 if isrev
-0038     equationString = [reactantsEqn ' <=> ' productsEqn];
-0039 else
-0040     equationString = [reactantsEqn ' => ' productsEqn];
-0041 end
-0042 
-0043 end
-0044 
-0045 function eqn = concatenateEquation(mets,stoichCoeffs)
-0046 %This function concatenates metabolites and stoich. coefficients to form
-0047 %either the left or right side of the rxn equation
-0048 eqn = '';
-0049 for i = 1:length(stoichCoeffs)
-0050     if i == 1
-0051         plusString='';
-0052     else
-0053         plusString=' + ';
-0054     end
-0055     stoich = stoichCoeffs(i);
-0056     if stoich == 1
-0057         stoich = '';
-0058     else
-0059         stoich = [num2str(stoich) ' '];
-0060     end
-0061     eqn = [eqn plusString stoich mets{i}];
-0062 end
-0063 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/canConsume.html b/doc/core/canConsume.html deleted file mode 100644 index bedcde3c9..000000000 --- a/doc/core/canConsume.html +++ /dev/null @@ -1,83 +0,0 @@ - - - - Description of canConsume - - - - - - - - - -
Home > core > canConsume.m
- - - -

canConsume -

- -

PURPOSE ^

-
canConsume
- -

SYNOPSIS ^

-
function consumed=canConsume(model,mets)
- -

DESCRIPTION ^

-
 canConsume
-   Checks which metabolites that can be consumed by a model using the
-   specified constraints
-
-   model       a model structure
-   mets        either a cell array of metabolite IDs, a logical vector 
-               with the same number of elements as metabolites in the model,
-               or a vector of indexes to check for (optional, default model.mets)
-
-   consumed    vector with true if the corresponding metabolite could be
-               produced
-
- Usage: consumed=canConsume(model,mets)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function consumed=canConsume(model,mets)
-0002 % canConsume
-0003 %   Checks which metabolites that can be consumed by a model using the
-0004 %   specified constraints
-0005 %
-0006 %   model       a model structure
-0007 %   mets        either a cell array of metabolite IDs, a logical vector
-0008 %               with the same number of elements as metabolites in the model,
-0009 %               or a vector of indexes to check for (optional, default model.mets)
-0010 %
-0011 %   consumed    vector with true if the corresponding metabolite could be
-0012 %               produced
-0013 %
-0014 % Usage: consumed=canConsume(model,mets)
-0015 
-0016 if nargin<2
-0017     mets=model.mets;
-0018 elseif ~islogical(mets) && ~isnumeric(mets)
-0019     mets=convertCharArray(mets);
-0020 end
-0021 
-0022 [model, rxns]=addExchangeRxns(model,'in',mets);
-0023 consumed=haveFlux(model,10^-5,rxns);
-0024 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/canProduce.html b/doc/core/canProduce.html deleted file mode 100644 index 40f9f0346..000000000 --- a/doc/core/canProduce.html +++ /dev/null @@ -1,85 +0,0 @@ - - - - Description of canProduce - - - - - - - - - -
Home > core > canProduce.m
- - - -

canProduce -

- -

PURPOSE ^

-
canProduce
- -

SYNOPSIS ^

-
function produced=canProduce(model,mets)
- -

DESCRIPTION ^

-
 canProduce
-   Checks which metabolites that can be produced from a model using the
-   specified constraints. This is a less advanced but faster version of
-   checkProduction.
-
-   model       a model structure
-   mets        either a cell array of metabolite IDs, a logical vector 
-               with the same number of elements as metabolites in the model,
-               or a vector of indexes to check for (optional, default model.mets)
-
-   produced    vector with true if the corresponding metabolite could be
-               produced
-
- Usage: produced=canProduce(model,mets)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function produced=canProduce(model,mets)
-0002 % canProduce
-0003 %   Checks which metabolites that can be produced from a model using the
-0004 %   specified constraints. This is a less advanced but faster version of
-0005 %   checkProduction.
-0006 %
-0007 %   model       a model structure
-0008 %   mets        either a cell array of metabolite IDs, a logical vector
-0009 %               with the same number of elements as metabolites in the model,
-0010 %               or a vector of indexes to check for (optional, default model.mets)
-0011 %
-0012 %   produced    vector with true if the corresponding metabolite could be
-0013 %               produced
-0014 %
-0015 % Usage: produced=canProduce(model,mets)
-0016 
-0017 if nargin<2
-0018     mets=model.mets;
-0019 elseif ~islogical(mets) && ~isnumeric(mets)
-0020     mets=convertCharArray(mets);
-0021 end
-0022 
-0023 [model, rxns]=addExchangeRxns(model,'out',mets);
-0024 produced=haveFlux(model,10^-5,rxns);
-0025 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/changeGrRules.html b/doc/core/changeGrRules.html deleted file mode 100644 index 82d3ea2c7..000000000 --- a/doc/core/changeGrRules.html +++ /dev/null @@ -1,116 +0,0 @@ - - - - Description of changeGrRules - - - - - - - - - -
Home > core > changeGrRules.m
- - - -

changeGrRules -

- -

PURPOSE ^

-
changeGrRules
- -

SYNOPSIS ^

-
function model = changeGrRules(model,rxns,grRules,replace)
- -

DESCRIPTION ^

-
 changeGrRules
-   Changes multiple grRules at the same time.
-
-   model       a model structure to change the gene association
-   rxns        string or cell array of reaction IDs
-   grRules     string of additional or replacement gene association.
-               Should be written with ' and ' to indicate subunits, ' or '
-               to indicate isoenzymes, and brackets '()' to separate
-               different instances
-   replace     true if old gene association should be replaced with new
-               association. False if new gene association should be
-               concatenated to the old association (optional, default true)
-
-   model       an updated model structure
-
- Usage: changeGrRules(model,rxns,grRules,replace)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function model = changeGrRules(model,rxns,grRules,replace)
-0002 % changeGrRules
-0003 %   Changes multiple grRules at the same time.
-0004 %
-0005 %   model       a model structure to change the gene association
-0006 %   rxns        string or cell array of reaction IDs
-0007 %   grRules     string of additional or replacement gene association.
-0008 %               Should be written with ' and ' to indicate subunits, ' or '
-0009 %               to indicate isoenzymes, and brackets '()' to separate
-0010 %               different instances
-0011 %   replace     true if old gene association should be replaced with new
-0012 %               association. False if new gene association should be
-0013 %               concatenated to the old association (optional, default true)
-0014 %
-0015 %   model       an updated model structure
-0016 %
-0017 % Usage: changeGrRules(model,rxns,grRules,replace)
-0018 
-0019 if nargin==3
-0020     replace=true;
-0021 end
-0022 
-0023 rxns=convertCharArray(rxns);
-0024 grRules=convertCharArray(grRules);
-0025 
-0026 if isscalar(grRules) && ~isscalar(rxns)
-0027     grRules = repmat(grRules,1,numel(rxns));
-0028 end
-0029 if ~(numel(grRules)==numel(rxns))
-0030     error('Number of rxns and grRules should be identical')
-0031 end
-0032 
-0033 % Add genes to model
-0034 geneList = getGenesFromGrRules(grRules);
-0035 genesToAdd.genes=setdiff(geneList,model.genes); % Only keep the genes that are not yet part of the model.genes.
-0036 if ~isempty(genesToAdd.genes)
-0037     model=addGenesRaven(model,genesToAdd); % Add genes
-0038 end
-0039     
-0040 % Find reaction and gene indices
-0041 idx=getIndexes(model,rxns,'rxns');
-0042 
-0043 % Change gene associations
-0044 if replace==true % Replace old gene associations
-0045     model.grRules(idx)=grRules;
-0046 else % Add gene associations, add new gene rules after 'OR'.
-0047     model.grRules(idx)=strcat('(',model.grRules(idx),') or (',grRules,')');
-0048 end
-0049 
-0050 %Fix grRules and reconstruct rxnGeneMat
-0051 [grRules,rxnGeneMat] = standardizeGrRules(model,true);
-0052 model.grRules = grRules;
-0053 model.rxnGeneMat = rxnGeneMat;
-0054 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/changeRxns.html b/doc/core/changeRxns.html deleted file mode 100644 index fb5927ca2..000000000 --- a/doc/core/changeRxns.html +++ /dev/null @@ -1,249 +0,0 @@ - - - - Description of changeRxns - - - - - - - - - -
Home > core > changeRxns.m
- - - -

changeRxns -

- -

PURPOSE ^

-
changeRxns
- -

SYNOPSIS ^

-
function model=changeRxns(model,rxns,equations,eqnType,compartment,allowNewMets)
- -

DESCRIPTION ^

-
 changeRxns
-   Modifies the equations of reactions
-
-   model            a model structure
-   rxns             cell array with reaction ids
-   equations        cell array with equations. Alternatively, it can be a
-                    structure with the fields "mets" and "stoichCoeffs",
-                    in the same fashion as addRxns. E.g.:
-                    equations.mets = {{'met1','met2'},{'met1','met3'}}
-                    equations.stoichCoeffs = {[-1,+2],[-1,+1]}
-   eqnType          double describing how the equation string should be
-                    interpreted
-                    1 - The metabolites are matched to model.mets. New
-                        metabolites (if allowed) are added to
-                        "compartment" (default)
-                    2 - The metabolites are matched to model.metNames and
-                        all metabolites are assigned to "compartment". Any
-                        new metabolites that are added will be assigned
-                        IDs "m1", "m2"... If IDs on the same form are
-                        already used in the model then the numbering will
-                        start from the highest used integer+1
-                    3 - The metabolites are written as
-                        "metNames[compNames]". Only compartments in
-                        model.compNames are allowed. Any
-                        new metabolites that are added will be assigned
-                        IDs "m1", "m2"... If IDs on the same form are
-                        already used in the model then the numbering will
-                        start from the highest used integer+1
-   compartment      a string with the compartment the metabolites should
-                    be placed in when using eqnType=2. Must match
-                    model.compNames (optional when eqnType=1 or eqnType=3)
-   allowNewMets     true if the function is allowed to add new
-                    metabolites. It is highly recommended to first add
-                    any new metabolites with addMets rather than
-                    automatically through this function. addMets supports
-                    more annotation of metabolites, allows for the use of
-                    exchange metabolites, and using it reduces the risk
-                    of parsing errors (optional, default false)
-
-   model            an updated model structure
-
-   NOTE: This function should be used with some care, since it doesn't
-   care about bounds on the reactions. Changing a irreversible reaction to
-   a reversible one (or the other way around) will only change the
-   model.rev field and not the model.lb/model.ub fields. The reaction will
-   therefore still be having the same reversibility because of the
-   bounds. Use setParams to change the bounds.
-
-   NOTE: When adding metabolites to a compartment where it previously
-   doesn't exist, the function will copy any available information from
-   the metabolite in another compartment.
-
- Usage: model=changeRxns(model,rxns,equations,eqnType,compartment,allowNewMets)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function model=changeRxns(model,rxns,equations,eqnType,compartment,allowNewMets)
-0002 % changeRxns
-0003 %   Modifies the equations of reactions
-0004 %
-0005 %   model            a model structure
-0006 %   rxns             cell array with reaction ids
-0007 %   equations        cell array with equations. Alternatively, it can be a
-0008 %                    structure with the fields "mets" and "stoichCoeffs",
-0009 %                    in the same fashion as addRxns. E.g.:
-0010 %                    equations.mets = {{'met1','met2'},{'met1','met3'}}
-0011 %                    equations.stoichCoeffs = {[-1,+2],[-1,+1]}
-0012 %   eqnType          double describing how the equation string should be
-0013 %                    interpreted
-0014 %                    1 - The metabolites are matched to model.mets. New
-0015 %                        metabolites (if allowed) are added to
-0016 %                        "compartment" (default)
-0017 %                    2 - The metabolites are matched to model.metNames and
-0018 %                        all metabolites are assigned to "compartment". Any
-0019 %                        new metabolites that are added will be assigned
-0020 %                        IDs "m1", "m2"... If IDs on the same form are
-0021 %                        already used in the model then the numbering will
-0022 %                        start from the highest used integer+1
-0023 %                    3 - The metabolites are written as
-0024 %                        "metNames[compNames]". Only compartments in
-0025 %                        model.compNames are allowed. Any
-0026 %                        new metabolites that are added will be assigned
-0027 %                        IDs "m1", "m2"... If IDs on the same form are
-0028 %                        already used in the model then the numbering will
-0029 %                        start from the highest used integer+1
-0030 %   compartment      a string with the compartment the metabolites should
-0031 %                    be placed in when using eqnType=2. Must match
-0032 %                    model.compNames (optional when eqnType=1 or eqnType=3)
-0033 %   allowNewMets     true if the function is allowed to add new
-0034 %                    metabolites. It is highly recommended to first add
-0035 %                    any new metabolites with addMets rather than
-0036 %                    automatically through this function. addMets supports
-0037 %                    more annotation of metabolites, allows for the use of
-0038 %                    exchange metabolites, and using it reduces the risk
-0039 %                    of parsing errors (optional, default false)
-0040 %
-0041 %   model            an updated model structure
-0042 %
-0043 %   NOTE: This function should be used with some care, since it doesn't
-0044 %   care about bounds on the reactions. Changing a irreversible reaction to
-0045 %   a reversible one (or the other way around) will only change the
-0046 %   model.rev field and not the model.lb/model.ub fields. The reaction will
-0047 %   therefore still be having the same reversibility because of the
-0048 %   bounds. Use setParams to change the bounds.
-0049 %
-0050 %   NOTE: When adding metabolites to a compartment where it previously
-0051 %   doesn't exist, the function will copy any available information from
-0052 %   the metabolite in another compartment.
-0053 %
-0054 % Usage: model=changeRxns(model,rxns,equations,eqnType,compartment,allowNewMets)
-0055 
-0056 if nargin<4
-0057     eqnType=1;
-0058 end
-0059 
-0060 if nargin<5
-0061     compartment=[];
-0062 end
-0063 if nargin<6
-0064     allowNewMets=false;
-0065 end
-0066 
-0067 rxns=convertCharArray(rxns);
-0068 compartment=char(compartment);
-0069 
-0070 %Find the indexes of the reactions and throw an error if they aren't all
-0071 %found
-0072 [I, J]=ismember(rxns,model.rxns);
-0073 if ~all(I)
-0074     EM='All reaction ids must exist in the model';
-0075     dispEM(EM);
-0076 end
-0077 
-0078 %The reactions are changed in the following manner. First create a
-0079 %rxns-structure by copying info from the model. Then remove the old
-0080 %reactions. Then add the updated ones using addRxns. Lastly, the model is
-0081 %reordered to match the original order. This is done like this to make use
-0082 %of the advanced parsing of equations that addRxns use.
-0083 rxnsToChange.rxns=rxns;
-0084 if isfield(equations,'mets') && isfield(equations,'stoichCoeffs')
-0085     rxnsToChange.mets=equations.mets;
-0086     rxnsToChange.stoichCoeffs=equations.stoichCoeffs;
-0087 else
-0088     rxnsToChange.equations=convertCharArray(equations);
-0089 end
-0090 if isfield(model,'rxnNames')
-0091     rxnsToChange.rxnNames=model.rxnNames(J);
-0092 end
-0093 if isfield(model,'lb')
-0094     rxnsToChange.lb=model.lb(J);
-0095 end
-0096 if isfield(model,'ub')
-0097     rxnsToChange.ub=model.ub(J);
-0098 end
-0099 if isfield(model,'c')
-0100     rxnsToChange.c=model.c(J);
-0101 end
-0102 if isfield(model,'eccodes')
-0103     rxnsToChange.eccodes=model.eccodes(J);
-0104 end
-0105 if isfield(model,'subSystems')
-0106     rxnsToChange.subSystems=model.subSystems(J);
-0107 end
-0108 if isfield(model,'rxnComps')
-0109     rxnsToChange.rxnComps=model.rxnComps(J);
-0110 end
-0111 if isfield(model,'grRules')
-0112     rxnsToChange.grRules=model.grRules(J);
-0113 end
-0114 if isfield(model,'rxnFrom')
-0115     rxnsToChange.rxnFrom=model.rxnFrom(J);
-0116 end
-0117 if isfield(model,'rxnScores')
-0118     rxnsToChange.rxnScores=model.rxnScores(J);
-0119 end
-0120 if isfield(model,'rxnMiriams')
-0121     rxnsToChange.rxnMiriams=model.rxnMiriams(J);
-0122 end
-0123 if isfield(model,'rxnNotes')
-0124     rxnsToChange.rxnNotes=model.rxnNotes(J);
-0125 end
-0126 if isfield(model,'rxnReferences')
-0127     rxnsToChange.rxnReferences=model.rxnReferences(J);
-0128 end
-0129 if isfield(model,'rxnConfidenceScores')
-0130     rxnsToChange.rxnConfidenceScores=model.rxnConfidenceScores(J);
-0131 end
-0132 if isfield(model,'rxnDeltaG')
-0133     rxnsToChange.rxnDeltaG=model.rxnDeltaG(J);
-0134 end
-0135 if isfield(model,'pwys')
-0136     rxnsToChange.pwys=model.pwys(J);
-0137 end
-0138 
-0139 %Calculate the new order of reactions
-0140 order=ones(numel(model.rxns),1);
-0141 order(J)=0;
-0142 order=cumsum(order);
-0143 order(J)=order(end)+1:order(end)+numel(rxns);
-0144 
-0145 %Remove the original reactions
-0146 model=removeReactions(model,rxns);
-0147 
-0148 model=addRxns(model,rxnsToChange,eqnType,compartment,allowNewMets);
-0149 model=permuteModel(model,order,'rxns');
-0150 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/checkModelStruct.html b/doc/core/checkModelStruct.html deleted file mode 100644 index a25d6ed4e..000000000 --- a/doc/core/checkModelStruct.html +++ /dev/null @@ -1,517 +0,0 @@ - - - - Description of checkModelStruct - - - - - - - - - -
Home > core > checkModelStruct.m
- - - -

checkModelStruct -

- -

PURPOSE ^

-
checkModelStruct
- -

SYNOPSIS ^

-
function checkModelStruct(model,throwErrors,trimWarnings)
- -

DESCRIPTION ^

-
 checkModelStruct
-   Performs a number of checks to ensure that a model structure is ok
-
-   model           a model structure
-   throwErrors     true if the function should throw errors if
-                   inconsistencies are found. The alternative is to
-                   print warnings for all types of issues (optional, default true)
-   trimWarnings    true if only a maximal of 10 items should be displayed in
-                   a given error/warning (optional, default true)
-
-   NOTE: This is performed after importing a model from Excel or before
-   attempting to export a model to SBML format.
-
- Usage: checkModelStruct(model,throwErrors,trimWarnings)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 function checkModelStruct(model,throwErrors,trimWarnings)
-0002 % checkModelStruct
-0003 %   Performs a number of checks to ensure that a model structure is ok
-0004 %
-0005 %   model           a model structure
-0006 %   throwErrors     true if the function should throw errors if
-0007 %                   inconsistencies are found. The alternative is to
-0008 %                   print warnings for all types of issues (optional, default true)
-0009 %   trimWarnings    true if only a maximal of 10 items should be displayed in
-0010 %                   a given error/warning (optional, default true)
-0011 %
-0012 %   NOTE: This is performed after importing a model from Excel or before
-0013 %   attempting to export a model to SBML format.
-0014 %
-0015 % Usage: checkModelStruct(model,throwErrors,trimWarnings)
-0016 
-0017 if nargin<2
-0018     throwErrors=true;
-0019 end
-0020 if nargin<3
-0021     trimWarnings=true;
-0022 end
-0023 
-0024 %Missing elements
-0025 fields={'id';'name';'rxns';'mets';'S';'lb';'ub';'rev';'c';'b';'comps';'metComps'};
-0026 for i=1:numel(fields)
-0027     if ~isfield(model,fields{i})
-0028         EM=['The model is missing the "' fields{i} '" field'];
-0029         dispEM(EM,throwErrors);
-0030     end
-0031 end
-0032 
-0033 %Type check
-0034 if ~ischar(model.id)
-0035     EM='The "id" field must be a string';
-0036     dispEM(EM,throwErrors);
-0037 end
-0038 if ~ischar(model.name)
-0039     EM='The "name" field must be a string';
-0040     dispEM(EM,throwErrors);
-0041 end
-0042 if ~iscellstr(model.rxns)
-0043     EM='The "rxns" field must be a cell array of strings';
-0044     dispEM(EM,throwErrors);
-0045 end
-0046 if ~iscellstr(model.mets)
-0047     EM='The "mets" field must be a cell array of strings';
-0048     dispEM(EM,throwErrors);
-0049 end
-0050 if ~isnumeric(model.S)
-0051     EM='The "S" field must be of type "double"';
-0052     dispEM(EM,throwErrors);
-0053 end
-0054 if ~isnumeric(model.lb)
-0055     EM='The "lb" field must be of type "double"';
-0056     dispEM(EM,throwErrors);
-0057 end
-0058 if ~isnumeric(model.ub)
-0059     EM='The "ub" field must be of type "double"';
-0060     dispEM(EM,throwErrors);
-0061 end
-0062 if ~isnumeric(model.rev)
-0063     EM='The "rev" field must be of type "double"';
-0064     dispEM(EM,throwErrors);
-0065 end
-0066 if ~isnumeric(model.c)
-0067     EM='The "c" field must be of type "double"';
-0068     dispEM(EM,throwErrors);
-0069 end
-0070 if ~isnumeric(model.b)
-0071     EM='The "b" field must be of type "double"';
-0072     dispEM(EM,throwErrors);
-0073 end
-0074 if ~iscellstr(model.comps)
-0075     EM='The "comps" field must be a cell array of strings';
-0076     dispEM(EM,throwErrors);
-0077 end
-0078 if ~isnumeric(model.metComps)
-0079     EM='The "metComps" field must be of type "double"';
-0080     dispEM(EM,throwErrors);
-0081 end
-0082 if isfield(model,'compNames')
-0083     if ~iscellstr(model.compNames)
-0084         EM='The "compNames" field must be a cell array of strings';
-0085         dispEM(EM,throwErrors);
-0086     end
-0087 end
-0088 if isfield(model,'compOutside')
-0089     if ~iscellstr(model.compOutside)
-0090         EM='The "compOutside" field must be a cell array of strings';
-0091         dispEM(EM,throwErrors);
-0092     end
-0093 end
-0094 if isfield(model,'rxnNames')
-0095     if ~iscellstr(model.rxnNames)
-0096         EM='The "rxnNames" field must be a cell array of strings';
-0097         dispEM(EM,throwErrors);
-0098     end
-0099 end
-0100 if isfield(model,'metNames')
-0101     if ~iscellstr(model.metNames)
-0102         EM='The "metNames" field must be a cell array of strings';
-0103         dispEM(EM,throwErrors);
-0104     end
-0105 end
-0106 if isfield(model,'genes')
-0107     if ~iscellstr(model.genes)
-0108         EM='The "genes" field must be a cell array of strings';
-0109         dispEM(EM,throwErrors);
-0110     end
-0111 end
-0112 if isfield(model,'rxnGeneMat')
-0113     if ~isnumeric(model.rxnGeneMat)
-0114         EM='The "rxnGeneMat" field must be of type "double"';
-0115         dispEM(EM,throwErrors);
-0116     end
-0117 end
-0118 if isfield(model,'grRules')
-0119     if ~iscellstr(model.grRules)
-0120         EM='The "grRules" field must be a cell array of strings';
-0121         dispEM(EM,throwErrors);
-0122     end
-0123     if ~isfield(model,'genes')
-0124         EM='If "grRules" field exists, the model should also contain a "genes" field';
-0125         dispEM(EM,throwErrors);
-0126     else
-0127         %Erroneous grRules that start/end with OR/AND
-0128         EM='The following reaction(s) have grRules that start or end with ''OR'' or ''AND'':';
-0129         dispEM(EM,throwErrors,model.rxns(startsWith(model.grRules,{'or ','and '}) | endsWith(model.grRules,{' or',' and'})),trimWarnings);
-0130         %grRules that are not in genes field
-0131         geneList = getGenesFromGrRules(model.grRules);
-0132         geneList = setdiff(unique(geneList),model.genes);
-0133         if ~isempty(geneList)
-0134             problemGrRules = model.rxns(contains(model.grRules,geneList));
-0135             problemGrRules = strjoin(problemGrRules(:),'; ');
-0136             EM=['The reaction(s) "' problemGrRules '" contain the following genes in its "grRules" field, but these are not in the "genes" field:'];
-0137             dispEM(EM,throwErrors,geneList);
-0138         end
-0139     end
-0140 end
-0141 if isfield(model,'rxnComps')
-0142     if ~isnumeric(model.rxnComps)
-0143         EM='The "rxnComps" field must be of type "double"';
-0144         dispEM(EM,throwErrors);
-0145     end
-0146 end
-0147 if isfield(model,'inchis')
-0148     if ~iscellstr(model.inchis)
-0149         EM='The "inchis" field must be a cell array of strings';
-0150         dispEM(EM,throwErrors);
-0151     end
-0152 end
-0153 if isfield(model,'metSmiles')
-0154     if ~iscellstr(model.metSmiles)
-0155         EM='The "metSmiles" field must be a cell array of strings';
-0156         dispEM(EM,throwErrors);
-0157     end
-0158 end
-0159 if isfield(model,'metFormulas')
-0160     if ~iscellstr(model.metFormulas)
-0161         EM='The "metFormulas" field must be a cell array of strings';
-0162         dispEM(EM,throwErrors);
-0163     end
-0164 end
-0165 if isfield(model,'metCharges')
-0166     if ~isnumeric(model.metCharges)
-0167         EM='The "metCharges" field must be a double';
-0168         dispEM(EM,throwErrors);
-0169     end
-0170 end
-0171 if isfield(model,'metDeltaG')
-0172     if ~isnumeric(model.metDeltaG)
-0173         EM='The "metDeltaG" field must be a double';
-0174         dispEM(EM,throwErrors);
-0175     end
-0176 end
-0177 if isfield(model,'subSystems')
-0178     isNested  = any(cellfun(@(x) iscell(x), model.subSystems));
-0179     isCellStr = any(cellfun(@(x) ischar(x), model.subSystems));
-0180     if ~xor(isNested,isCellStr)
-0181         EM='The "subSystems" field must be a cell array of chars, *or* a cell array of cell arrays of chars';
-0182             dispEM(EM,throwErrors);
-0183     end
-0184 end
-0185 if isfield(model,'eccodes')
-0186     if ~iscellstr(model.eccodes)
-0187         EM='The "eccodes" field must be a cell array of strings';
-0188         dispEM(EM,throwErrors);
-0189     end
-0190 end
-0191 if isfield(model,'unconstrained')
-0192     if ~isnumeric(model.unconstrained)
-0193         EM='The "unconstrained" field must be of type "double"';
-0194         dispEM(EM,throwErrors);
-0195     end
-0196 end
-0197 if isfield(model,'rxnNotes')
-0198     if ~iscellstr(model.rxnNotes)
-0199         EM='The "rxnNotes" field must be a cell array of strings';
-0200         dispEM(EM,throwErrors);
-0201     end
-0202 end
-0203 if isfield(model,'rxnReferences')
-0204     if ~iscellstr(model.rxnReferences)
-0205         EM='The "rxnReferences" field must be a cell array of strings';
-0206         dispEM(EM,throwErrors);
-0207     end
-0208 end
-0209 if isfield(model,'rxnConfidenceScores')
-0210     if ~isnumeric(model.rxnConfidenceScores)
-0211         EM='The "rxnConfidenceScores" field must be a double';
-0212         dispEM(EM,throwErrors);
-0213     end
-0214 end
-0215 if isfield(model,'rxnDeltaG')
-0216     if ~isnumeric(model.rxnDeltaG)
-0217         EM='The "rxnDeltaG" field must be a double';
-0218         dispEM(EM,throwErrors);
-0219     end
-0220 end
-0221 
-0222 %Empty strings
-0223 if isempty(model.id)
-0224     EM='The "id" field cannot be empty';
-0225     dispEM(EM,throwErrors);
-0226 end
-0227 if any(cellfun(@isempty,model.rxns))
-0228     EM='The model contains empty reaction IDs';
-0229     dispEM(EM,throwErrors);
-0230 end
-0231 if any(cellfun(@isempty,model.mets))
-0232     EM='The model contains empty metabolite IDs';
-0233     dispEM(EM,throwErrors);
-0234 end
-0235 if any(cellfun(@isempty,model.comps))
-0236     EM='The model contains empty compartment IDs';
-0237     dispEM(EM,throwErrors);
-0238 end
-0239 EM='The following metabolites have empty names:';
-0240 dispEM(EM,throwErrors,model.mets(cellfun(@isempty,model.metNames)),trimWarnings);
-0241 
-0242 if isfield(model,'genes')
-0243     if any(cellfun(@isempty,model.genes))
-0244         EM='The model contains empty gene IDs';
-0245         dispEM(EM,throwErrors);
-0246     end
-0247 end
-0248 
-0249 %Validate format of ids
-0250 fields      = {'rxns';'mets';'comps';'genes'};
-0251 fieldNames  = {'reaction';'metabolite';'compartment';'gene'};
-0252 fieldPrefix = {'R_';'M_';'C_';'G_'};
-0253 for i=1:numel(fields)
-0254     try
-0255         numIDs = ~startsWith(model.(fields{i}),regexpPattern('^[a-zA-Z_]'));
-0256     catch
-0257         numIDs = [];
-0258     end
-0259     if any(numIDs)
-0260         EM = ['The following ' fieldNames{i} ' identifiers do not start '...
-0261             'with a letter or _ (conflicting with SBML specifications). '...
-0262             'This does not impact RAVEN functionality, but be aware that '...
-0263             'exportModel will automatically add ' fieldPrefix{i} ...
-0264             ' prefixes to all ' fieldNames{i} ' identifiers:'];
-0265         dispEM(EM,false,{model.(fields{i}){numIDs}},trimWarnings);
-0266     end
-0267 end
-0268 
-0269 %Duplicates
-0270 EM='The following reaction IDs are duplicates:';
-0271 dispEM(EM,throwErrors,model.rxns(duplicates(model.rxns)),trimWarnings);
-0272 EM='The following metabolite IDs are duplicates:';
-0273 dispEM(EM,throwErrors,model.mets(duplicates(model.mets)),trimWarnings);
-0274 EM='The following compartment IDs are duplicates:';
-0275 dispEM(EM,throwErrors,model.comps(duplicates(model.comps)),trimWarnings);
-0276 if isfield(model,'genes')
-0277     EM='The following genes are duplicates:';
-0278     dispEM(EM,throwErrors,model.genes(duplicates(model.genes)),trimWarnings);
-0279 end
-0280 metInComp=strcat(model.metNames,'[',model.comps(model.metComps),']');
-0281 EM='The following metabolites already exist in the same compartment:';
-0282 dispEM(EM,throwErrors,metInComp(duplicates(metInComp)),trimWarnings);
-0283 
-0284 %Elements never used (print only as warnings
-0285 EM='The following reactions are empty (no involved metabolites):';
-0286 dispEM(EM,false,model.rxns(~any(model.S,1)),trimWarnings);
-0287 EM='The following metabolites are never used in a reaction:';
-0288 dispEM(EM,false,model.mets(~any(model.S,2)),trimWarnings);
-0289 if isfield(model,'genes')
-0290     EM='The following genes are not associated to a reaction:';
-0291     dispEM(EM,false,model.genes(~any(model.rxnGeneMat,1)),trimWarnings);
-0292 end
-0293 I=true(numel(model.comps),1);
-0294 I(model.metComps)=false;
-0295 EM='The following compartments contain no metabolites:';
-0296 dispEM(EM,false,model.comps(I),trimWarnings);
-0297 
-0298 %Contradicting bounds
-0299 EM='The following reactions have contradicting bounds (lower bound is higher than upper bound):';
-0300 dispEM(EM,throwErrors,model.rxns(model.lb>model.ub),trimWarnings);
-0301 EM='The following reactions have lower and upper bounds that indicate reversibility, but are indicated as irreversible in model.rev:';
-0302 dispEM(EM,false,model.rxns(model.lb < 0 & model.ub > 0 & model.rev==0),trimWarnings);
-0303 
-0304 %Multiple or no objective functions not allowed in SBML L3V1 FBCv2
-0305 if numel(find(model.c))>1
-0306     EM='Multiple objective functions found. This might be intended, but results in FBCv2 non-compliant SBML file when exported';
-0307     dispEM(EM,false,model.rxns(find(model.c)),trimWarnings);
-0308 elseif ~any(model.c)
-0309     EM='No objective function found. This might be intended, but results in FBCv2 non-compliant SBML file when exported';
-0310     dispEM(EM,false);
-0311 end
-0312 
-0313 %Mapping of compartments
-0314 if isfield(model,'compOutside')
-0315     EM='The following compartments are in "compOutside" but not in "comps":';
-0316     dispEM(EM,throwErrors,setdiff(model.compOutside,[{''};model.comps]),trimWarnings);
-0317 end
-0318 
-0319 %Met names which start with number
-0320 I=false(numel(model.metNames),1);
-0321 for i=1:numel(model.metNames)
-0322     index=strfind(model.metNames{i},' ');
-0323     if any(index)
-0324         if any(str2double(model.metNames{i}(1:index(1)-1)))
-0325             I(i)=true;
-0326         end
-0327     end
-0328 end
-0329 EM='The following metabolite names begin with a number directly followed by space, which could potentially cause problems:';
-0330 dispEM(EM,false,model.metNames(I),trimWarnings);
-0331 
-0332 %Non-parseable composition
-0333 if isfield(model,'metFormulas')
-0334     [~, ~, exitFlag]=parseFormulas(model.metFormulas,true,false);
-0335     EM='The composition for the following metabolites could not be parsed:';
-0336     dispEM(EM,false,model.mets(exitFlag==-1),trimWarnings);
-0337 end
-0338 
-0339 %Check if there are metabolites with different names but the same MIRIAM
-0340 %codes
-0341 if isfield(model,'metMiriams')
-0342     miriams=containers.Map();
-0343     for i=1:numel(model.mets)
-0344         if ~isempty(model.metMiriams{i})
-0345             %Loop through and add for each miriam
-0346             for j=1:numel(model.metMiriams{i}.name)
-0347                 %Get existing metabolite indexes
-0348                 current=strcat(model.metMiriams{i}.name{j},'/',model.metMiriams{i}.value{j});
-0349                 if isKey(miriams,current)
-0350                     existing=miriams(current);
-0351                 else
-0352                     existing=[];
-0353                 end
-0354                 miriams(current)=[existing;i];
-0355             end
-0356         end
-0357     end
-0358     
-0359     %Get all keys
-0360     allMiriams=keys(miriams);
-0361     
-0362     hasMultiple=false(numel(allMiriams),1);
-0363     for i=1:numel(allMiriams)
-0364         if numel(miriams(allMiriams{i}))>1
-0365             %Check if they all have the same name
-0366             if numel(unique(model.metNames(miriams(allMiriams{i}))))>1
-0367                 if ~regexp(allMiriams{i},'^sbo\/SBO:') % SBO terms are expected to be multiple
-0368                     hasMultiple(i)=true;
-0369                 end                
-0370             end
-0371         end
-0372     end
-0373     
-0374     %Print output
-0375     EM='The following MIRIAM strings are associated to more than one unique metabolite name:';
-0376     dispEM(EM,false,allMiriams(hasMultiple),trimWarnings);
-0377 end
-0378 
-0379 %Check if there are metabolites with different names but the same InChI
-0380 %codes
-0381 if isfield(model,'inchis')
-0382     inchis=containers.Map();
-0383     for i=1:numel(model.mets)
-0384         if ~isempty(model.inchis{i})
-0385             %Get existing metabolite indexes
-0386             if isKey(inchis,model.inchis{i})
-0387                 existing=inchis(model.inchis{i});
-0388             else
-0389                 existing=[];
-0390             end
-0391             inchis(model.inchis{i})=[existing;i];
-0392         end
-0393     end
-0394     
-0395     %Get all keys
-0396     allInchis=keys(inchis);
-0397     
-0398     hasMultiple=false(numel(allInchis),1);
-0399     for i=1:numel(allInchis)
-0400         if numel(inchis(allInchis{i}))>1
-0401             %Check if they all have the same name
-0402             if numel(unique(model.metNames(inchis(allInchis{i}))))>1
-0403                 hasMultiple(i)=true;
-0404             end
-0405         end
-0406     end
-0407     
-0408     %Print output
-0409     EM='The following InChI strings are associated to more than one unique metabolite name:';
-0410     dispEM(EM,false,allInchis(hasMultiple),trimWarnings);
-0411 end
-0412 
-0413 % %Check if there are metabolites with different names but the same SMILES
-0414 % if isfield(model,'metSmiles')
-0415 %     metSmiles=containers.Map();
-0416 %     for i=1:numel(model.mets)
-0417 %         if ~isempty(model.metSmiles{i})
-0418 %             %Get existing metabolite indexes
-0419 %             if isKey(metSmiles,model.metSmiles{i})
-0420 %                 existing=metSmiles(model.metSmiles{i});
-0421 %             else
-0422 %                 existing=[];
-0423 %             end
-0424 %             metSmiles(model.metSmiles{i})=[existing;i];
-0425 %         end
-0426 %     end
-0427 %
-0428 %     %Get all keys
-0429 %     allmetSmiles=keys(metSmiles);
-0430 %
-0431 %     hasMultiple=false(numel(metSmiles),1);
-0432 %     for i=1:numel(metSmiles)
-0433 %         if numel(metSmiles(metSmiles{i}))>1
-0434 %             %Check if they all have the same name
-0435 %             if numel(unique(model.metNames(metSmiles(allmetSmiles{i}))))>1
-0436 %                 hasMultiple(i)=true;
-0437 %             end
-0438 %         end
-0439 %     end
-0440 %
-0441 %     %Print output
-0442 %     EM='The following metSmiles strings are associated to more than one unique metabolite name:';
-0443 %     dispEM(EM,false,allmetSmiles(hasMultiple),trimWarnings);
-0444 % end
-0445 end
-0446 
-0447 function I=duplicates(strings)
-0448 I=false(numel(strings),1);
-0449 [J, K]=unique(strings);
-0450 if numel(J)~=numel(strings)
-0451     L=1:numel(strings);
-0452     L(K)=[];
-0453     I(L)=true;
-0454 end
-0455 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/checkProduction.html b/doc/core/checkProduction.html deleted file mode 100644 index 47d2f41e9..000000000 --- a/doc/core/checkProduction.html +++ /dev/null @@ -1,242 +0,0 @@ - - - - Description of checkProduction - - - - - - - - - -
Home > core > checkProduction.m
- - - -

checkProduction -

- -

PURPOSE ^

-
checkProduction
- -

SYNOPSIS ^

-
function [notProduced, notProducedNames, neededForProductionMat,minToConnect,model]=checkProduction(model,checkNeededForProduction,excretionFromCompartments,printDetails)
- -

DESCRIPTION ^

-
 checkProduction
-   Checks which metabolites that can be produced from a model using the
-   specified constraints.
-
-   model                       a model structure
-   checkNeededForProduction    for each of the metabolites that could not
-                               be produced, include an artificial
-                               production reaction and calculate which new
-                               metabolites that could be produced as en
-                               effect of this (optional, default false)
-   excretionFromCompartments   cell array with compartment ids from which
-                               metabolites can be excreted (optional, default
-                               model.comps)
-   printDetails                print details to the screen (optional, default
-                               true)
-
-   notProduced                 cell array with metabolites that could not
-                               be produced
-   notProducedNames            cell array with names and compartments for
-                               metabolites that could not be produced
-   neededForProductionMat      matrix where n x m is true if metabolite n
-                               allows for production of metabolite m
-   minToConnect                structure with the minimal number of
-                               metabolites that need to be connected in
-                               order to be able to produce all other
-                               metabolites and which metabolites each of
-                               them connects
-   model                       updated model structure with excretion
-                               reactions added
-
-   The function is intended to be used to identify which metabolites must
-   be connected in order to have a fully connected network. It does so by
-   first identifying which metabolites could have a net production in the
-   network. Then it calculates which other metabolites must be able to
-   have net production in order to have production of all metabolites in
-   the network. So, if a network contains the equations A[external]->B,
-   C->D, and D->E it will identify that production of C will connect
-   the metabolites D and E.
-
- Usage: [notProduced, notProducedNames,neededForProductionMat,minToConnect,model]=...
-           checkProduction(model,checkNeededForProduction,...
-           excretionFromCompartments,printDetails)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function [notProduced, notProducedNames, neededForProductionMat,minToConnect,model]=checkProduction(model,checkNeededForProduction,excretionFromCompartments,printDetails)
-0002 % checkProduction
-0003 %   Checks which metabolites that can be produced from a model using the
-0004 %   specified constraints.
-0005 %
-0006 %   model                       a model structure
-0007 %   checkNeededForProduction    for each of the metabolites that could not
-0008 %                               be produced, include an artificial
-0009 %                               production reaction and calculate which new
-0010 %                               metabolites that could be produced as en
-0011 %                               effect of this (optional, default false)
-0012 %   excretionFromCompartments   cell array with compartment ids from which
-0013 %                               metabolites can be excreted (optional, default
-0014 %                               model.comps)
-0015 %   printDetails                print details to the screen (optional, default
-0016 %                               true)
-0017 %
-0018 %   notProduced                 cell array with metabolites that could not
-0019 %                               be produced
-0020 %   notProducedNames            cell array with names and compartments for
-0021 %                               metabolites that could not be produced
-0022 %   neededForProductionMat      matrix where n x m is true if metabolite n
-0023 %                               allows for production of metabolite m
-0024 %   minToConnect                structure with the minimal number of
-0025 %                               metabolites that need to be connected in
-0026 %                               order to be able to produce all other
-0027 %                               metabolites and which metabolites each of
-0028 %                               them connects
-0029 %   model                       updated model structure with excretion
-0030 %                               reactions added
-0031 %
-0032 %   The function is intended to be used to identify which metabolites must
-0033 %   be connected in order to have a fully connected network. It does so by
-0034 %   first identifying which metabolites could have a net production in the
-0035 %   network. Then it calculates which other metabolites must be able to
-0036 %   have net production in order to have production of all metabolites in
-0037 %   the network. So, if a network contains the equations A[external]->B,
-0038 %   C->D, and D->E it will identify that production of C will connect
-0039 %   the metabolites D and E.
-0040 %
-0041 % Usage: [notProduced, notProducedNames,neededForProductionMat,minToConnect,model]=...
-0042 %           checkProduction(model,checkNeededForProduction,...
-0043 %           excretionFromCompartments,printDetails)
-0044 
-0045 if nargin<2
-0046     checkNeededForProduction=false;
-0047 end
-0048 
-0049 if nargin<3
-0050     excretionFromCompartments=model.comps;
-0051 else
-0052     excretionFromCompartments=convertCharArray(excretionFromCompartments);
-0053 end
-0054 
-0055 if nargin<4
-0056     printDetails=true;
-0057 end
-0058 
-0059 %Add an exchange reaction for each metabolite in the allowed compartments
-0060 %and see if it can carry a flux
-0061 allowedMetIds=ismember(model.comps(model.metComps),excretionFromCompartments);
-0062 allowedMetIndexes=find(allowedMetIds);
-0063 [model, addedRxns]=addExchangeRxns(model,'out',allowedMetIndexes);
-0064 
-0065 canProduce=haveFlux(model,10^-5,addedRxns);
-0066 
-0067 notProduced=find(~canProduce);
-0068 minToConnect={};
-0069 if checkNeededForProduction==true
-0070     %For each of the metabolites that couldn't be produced allow uptake and
-0071     %check which of the other metabolites that couldn't be produced that
-0072     %can be produced
-0073     neededForProductionMat=false(numel(notProduced));
-0074     for i=1:numel(notProduced)
-0075         %Add uptake for this metabolite
-0076         if i>1
-0077             %Reset last iteration
-0078             model.S(:,numel(model.rxns)-numel(addedRxns)+notProduced(i-1))=model.S(:,numel(model.rxns)-numel(addedRxns)+notProduced(i-1))*-1;
-0079         end
-0080         %Change the production reaction to an uptake reaction
-0081         model.S(:,numel(model.rxns)-numel(addedRxns)+notProduced(i))=model.S(:,numel(model.rxns)-numel(addedRxns)+notProduced(i))*-1;
-0082         
-0083         %Test which of the metabolites that couldn't be produced that can
-0084         %be produced now
-0085         neededForProductionMat(i,:)=haveFlux(model,10^-5,addedRxns(notProduced));
-0086     end
-0087     %Calculate the smallest number of metabolites that must be connected to
-0088     %make everything connected and return their names
-0089     
-0090     %The algorithm is relatively straight forward. It finds the metabolite
-0091     %that connects the most unconnected metabolites (iteratively), adds it
-0092     %and removes the now connected metabolites until all are connected.
-0093     %This is not guaranteed to find the global minimum
-0094     neededForProdTemp=neededForProductionMat;
-0095     while 1==1
-0096         %Get all metabolites a metabolite makes connected
-0097         totalConnected=false(size(neededForProdTemp));
-0098         for i=1:numel(notProduced)
-0099             totalConnected(i,:)=neededForProdTemp(i,:);
-0100             
-0101             lastIter=0;
-0102             while 1==1
-0103                 [~, a]=find(neededForProdTemp(totalConnected(i,:),:));
-0104                 totalConnected(i,a)=true;
-0105                 if numel(a)==lastIter
-0106                     break; %No more connections were possible
-0107                 else
-0108                     lastIter=numel(a);
-0109                 end
-0110             end
-0111         end
-0112         [connections, mostConnected]=max(sum(totalConnected,2));
-0113         
-0114         if connections>0
-0115             %Add the most connected metabolite to the list and remove all
-0116             %metabolites that it's connected to
-0117             metID=allowedMetIndexes(notProduced(mostConnected));
-0118             entry=[model.metNames{metID},'[',model.comps{model.metComps(metID)},'] (connects ' num2str(connections) ' metabolites)'];
-0119             minToConnect=[minToConnect;entry];
-0120             neededForProdTemp(totalConnected(mostConnected,:),:)=false;
-0121             neededForProdTemp(:,totalConnected(mostConnected,:))=false;
-0122         else
-0123             break;
-0124         end
-0125     end
-0126 else
-0127     neededForProductionMat=[];
-0128 end
-0129 
-0130 notProducedNames=strcat(model.metNames(allowedMetIndexes(notProduced)),'[',model.comps(model.metComps(allowedMetIndexes(notProduced))),']');
-0131 
-0132 if printDetails==true
-0133     fprintf('The following metabolites could not be produced:\n');
-0134     [notProducedNamesTemp,perm]=sort(notProducedNames);
-0135     
-0136     if checkNeededForProduction==true
-0137         neededForProdTemp=neededForProductionMat(:,perm);
-0138         neededForProdTemp=neededForProdTemp(perm,:);
-0139         fprintf('\tIf the production of a metabolite is dependent on some other metabolites then those are printed under the name\n\n');
-0140     end
-0141     for i=1:numel(notProducedNamesTemp)
-0142         fprintf([notProducedNamesTemp{i} '\n']);
-0143         neededForProdTemp(i,i)=false; %Not neat to do this here. Prevent printing itself
-0144         if checkNeededForProduction==true
-0145             enablesProduction=find(neededForProdTemp(:,i));
-0146             if any(enablesProduction)
-0147                 for j=1:numel(enablesProduction)
-0148                     fprintf(['\t' notProducedNamesTemp{enablesProduction(j)} '\n']);
-0149                 end
-0150             end
-0151         end
-0152     end
-0153 end
-0154 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/checkRxn.html b/doc/core/checkRxn.html deleted file mode 100644 index 4169caa72..000000000 --- a/doc/core/checkRxn.html +++ /dev/null @@ -1,156 +0,0 @@ - - - - Description of checkRxn - - - - - - - - - -
Home > core > checkRxn.m
- - - -

checkRxn -

- -

PURPOSE ^

-
checkRxn
- -

SYNOPSIS ^

-
function report=checkRxn(model,rxn,cutoff,revDir,printReport)
- -

DESCRIPTION ^

-
 checkRxn
-   Checks which reactants in a reaction that can be synthesized and which
-   products that can be consumed. This is primarily for debugging
-   reactions which cannot have flux
-
-   model       a model structure
-   rxn         the id of one reaction to check
-   cutoff      minimal flux for successful production/consumption (optional,
-               default 10^-7)
-   revDir      true if the reaction should be reversed (optional, default
-               false)
-   printReport print a report (optional, default true)
-
-   report
-       reactants   array with reactant indexes
-       canMake     boolean array, true if the corresponding reactant can
-                   be synthesized by the rest of the metabolic network
-       products    array with product indexes
-       canConsume  boolean array, true if the corresponding product can
-                   be consumed by the rest of the metabolic network
-
- Usage: report=checkRxn(model,rxn,cutoff,revDir,printReport)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function report=checkRxn(model,rxn,cutoff,revDir,printReport)
-0002 % checkRxn
-0003 %   Checks which reactants in a reaction that can be synthesized and which
-0004 %   products that can be consumed. This is primarily for debugging
-0005 %   reactions which cannot have flux
-0006 %
-0007 %   model       a model structure
-0008 %   rxn         the id of one reaction to check
-0009 %   cutoff      minimal flux for successful production/consumption (optional,
-0010 %               default 10^-7)
-0011 %   revDir      true if the reaction should be reversed (optional, default
-0012 %               false)
-0013 %   printReport print a report (optional, default true)
-0014 %
-0015 %   report
-0016 %       reactants   array with reactant indexes
-0017 %       canMake     boolean array, true if the corresponding reactant can
-0018 %                   be synthesized by the rest of the metabolic network
-0019 %       products    array with product indexes
-0020 %       canConsume  boolean array, true if the corresponding product can
-0021 %                   be consumed by the rest of the metabolic network
-0022 %
-0023 % Usage: report=checkRxn(model,rxn,cutoff,revDir,printReport)
-0024 
-0025 rxn=char(rxn);
-0026 if nargin<3
-0027     cutoff=10^-7;
-0028 end
-0029 if nargin<4
-0030     revDir=false;
-0031 end
-0032 if isempty(cutoff)
-0033     cutoff=10^-7;
-0034 end
-0035 if nargin<5
-0036     printReport=true;
-0037 end
-0038 
-0039 [I, rxnID]=ismember(rxn,model.rxns);
-0040 
-0041 if ~I
-0042     EM='Reaction ID not found';
-0043     dispEM(EM);
-0044 end
-0045 
-0046 if revDir==false
-0047     report.reactants=find(model.S(:,rxnID)<0);
-0048     report.products=find(model.S(:,rxnID)>0);
-0049 else
-0050     report.reactants=find(model.S(:,rxnID)>0);
-0051     report.products=find(model.S(:,rxnID)<0);
-0052 end
-0053 report.canMake=false(numel(report.reactants),1);
-0054 report.canConsume=false(numel(report.products),1);
-0055 
-0056 %Remove this field as it would give an annoying note otherwise
-0057 if isfield(model,'rxnComps')
-0058     model=rmfield(model,'rxnComps');
-0059 end
-0060 
-0061 %There are several ways to do this. Here I choose to add the reactions one
-0062 %by one and checking their bounds. This might not be optimal
-0063 for i=1:numel(report.reactants)
-0064     [tempModel, testRxn]=addExchangeRxns(model,'out',report.reactants(i));
-0065     tempModel=setParam(tempModel,'obj',testRxn,1);
-0066     sol=solveLP(tempModel);
-0067     if sol.f>cutoff
-0068         report.canMake(i)=true;
-0069     else
-0070         if printReport==true
-0071             fprintf(['Failed to make ' model.metNames{report.reactants(i)} '[' model.comps{model.metComps(report.reactants(i))} ']\n']);
-0072         end
-0073     end
-0074 end
-0075 
-0076 for i=1:numel(report.products)
-0077     [tempModel, testRxn]=addExchangeRxns(model,'in',report.products(i));
-0078     tempModel=setParam(tempModel,'obj',testRxn,1);
-0079     sol=solveLP(tempModel);
-0080     if sol.f>cutoff
-0081         report.canConsume(i)=true;
-0082     else
-0083         if printReport==true
-0084             fprintf(['Failed to consume ' model.metNames{report.products(i)} '[' model.comps{model.metComps(report.products(i))} ']\n']);
-0085         end
-0086     end
-0087 end
-0088 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/checkTasks.html b/doc/core/checkTasks.html deleted file mode 100644 index a9ea73c64..000000000 --- a/doc/core/checkTasks.html +++ /dev/null @@ -1,351 +0,0 @@ - - - - Description of checkTasks - - - - - - - - - -
Home > core > checkTasks.m
- - - -

checkTasks -

- -

PURPOSE ^

-
checkTasks
- -

SYNOPSIS ^

-
function [taskReport, essentialRxns, taskStructure, essentialFluxes]=checkTasks(model,inputFile,printOutput,printOnlyFailed,getEssential,taskStructure)
- -

DESCRIPTION ^

-
 checkTasks
-   Performs a set of simulations as defined in a task file.
-
-   Input:
-   model           a model structure
-   inputFile       a task list in Excel format. See the function
-                   parseTaskList for details (optional if taskStructure is
-                   supplied)
-   printOutput     true if the results of the test should be displayed
-                   (optional, default true)
-   printOnlyFailed true if only tasks that failed should be displayed
-                   (optional, default false)
-   getEssential    true if the essential reactions should be calculated for
-                   all the tasks. This option is used with runINIT (optional,
-                   default false)
-   taskStructure   structure with the tasks, as from parseTaskList. If
-                   this is supplied then inputFile is ignored (optional)
-
-
-   Output:
-   taskReport          structure with the results
-       id              cell array with the id of the task
-       description     cell array with the description of the task
-       ok              boolean array with true if the task was successful
-   essentialRxns       MxN matrix with the essential reactions (M) for each
-                       task (N). An element is true if the corresponding
-                       reaction is essential in the corresponding task.
-                       Failed tasks and SHOULD FAIL tasks are ignored.
-                       This is used by the INIT algorithm (if tasks
-                       are supplied). If getEssential=false then
-                       essentialRxns=false(nRxns,nTasks)
-   taskStructure       structure with the tasks, as from parseTaskList
-   essentialFluxes     The fluxes of the essential rxns - same structure as essentialRxns
-   
-
-   This function is used for defining a set of tasks for a model to
-   perform. The tasks are defined by defining constraints on the model,
-   and if the problem is feasible, then the task is considered successful.
-   In general, each row can contain one constraint on uptakes, one
-   constraint on outputs, one new equation, and one change of reaction
-   bounds. If more bounds are needed to define the task, then several rows
-   can be used for each task.
-
- Usage: [taskReport, essentialReactions, taskStructure]=checkTasks(model,inputFile,...
-           printOutput,printOnlyFailed,getEssential,taskStructure)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function [taskReport, essentialRxns, taskStructure, essentialFluxes]=checkTasks(model,inputFile,printOutput,printOnlyFailed,getEssential,taskStructure)
-0002 % checkTasks
-0003 %   Performs a set of simulations as defined in a task file.
-0004 %
-0005 %   Input:
-0006 %   model           a model structure
-0007 %   inputFile       a task list in Excel format. See the function
-0008 %                   parseTaskList for details (optional if taskStructure is
-0009 %                   supplied)
-0010 %   printOutput     true if the results of the test should be displayed
-0011 %                   (optional, default true)
-0012 %   printOnlyFailed true if only tasks that failed should be displayed
-0013 %                   (optional, default false)
-0014 %   getEssential    true if the essential reactions should be calculated for
-0015 %                   all the tasks. This option is used with runINIT (optional,
-0016 %                   default false)
-0017 %   taskStructure   structure with the tasks, as from parseTaskList. If
-0018 %                   this is supplied then inputFile is ignored (optional)
-0019 %
-0020 %
-0021 %   Output:
-0022 %   taskReport          structure with the results
-0023 %       id              cell array with the id of the task
-0024 %       description     cell array with the description of the task
-0025 %       ok              boolean array with true if the task was successful
-0026 %   essentialRxns       MxN matrix with the essential reactions (M) for each
-0027 %                       task (N). An element is true if the corresponding
-0028 %                       reaction is essential in the corresponding task.
-0029 %                       Failed tasks and SHOULD FAIL tasks are ignored.
-0030 %                       This is used by the INIT algorithm (if tasks
-0031 %                       are supplied). If getEssential=false then
-0032 %                       essentialRxns=false(nRxns,nTasks)
-0033 %   taskStructure       structure with the tasks, as from parseTaskList
-0034 %   essentialFluxes     The fluxes of the essential rxns - same structure as essentialRxns
-0035 %
-0036 %
-0037 %   This function is used for defining a set of tasks for a model to
-0038 %   perform. The tasks are defined by defining constraints on the model,
-0039 %   and if the problem is feasible, then the task is considered successful.
-0040 %   In general, each row can contain one constraint on uptakes, one
-0041 %   constraint on outputs, one new equation, and one change of reaction
-0042 %   bounds. If more bounds are needed to define the task, then several rows
-0043 %   can be used for each task.
-0044 %
-0045 % Usage: [taskReport, essentialReactions, taskStructure]=checkTasks(model,inputFile,...
-0046 %           printOutput,printOnlyFailed,getEssential,taskStructure)
-0047 
-0048 if nargin<3 || isempty(printOutput)
-0049     printOutput=true;
-0050 end
-0051 if nargin<4 || isempty(printOnlyFailed)
-0052     printOnlyFailed=false;
-0053 end
-0054 if nargin<5 || isempty(getEssential)
-0055     getEssential=false;
-0056 end
-0057 
-0058 %Prepare the input model a little
-0059 model.b=zeros(numel(model.mets),2);
-0060 
-0061 modelMets=upper(strcat(model.metNames,'[',model.comps(model.metComps),']'));
-0062 if ~isfield(model,'unconstrained')
-0063     EM='Exchange metabolites should normally not be removed from the model when using checkTasks. Inputs and outputs are defined in the task file instead. Use importModel(file,false) to import a model with exchange metabolites remaining';
-0064     dispEM(EM,false);
-0065 end
-0066 
-0067 %Parse the task file
-0068 if nargin<6
-0069     taskStructure=parseTaskList(inputFile);
-0070 end
-0071 
-0072 essentialRxns=false(numel(model.rxns),numel(taskStructure));
-0073 essentialFluxes = NaN(numel(model.rxns),numel(taskStructure));
-0074 
-0075 tModel=model;
-0076 taskReport=[];
-0077 for i=1:numel(taskStructure)
-0078     taskReport.id{i,1}=taskStructure(i).id;
-0079     taskReport.description{i,1}=taskStructure(i).description;
-0080     %Set the inputs
-0081     if ~isempty(taskStructure(i).inputs)
-0082         [I, J]=ismember(upper(taskStructure(i).inputs),modelMets);
-0083         J=J(I); %Only keep the ones with matches
-0084         K=ismember(upper(taskStructure(i).inputs),'ALLMETS');
-0085         L=~cellfun('isempty',strfind(upper(taskStructure(i).inputs),'ALLMETSIN'));
-0086         %Check that all metabolites are either real metabolites or
-0087         %ALLMETS/ALLMETSIN
-0088         if ~all(I|K|L)
-0089             fprintf(['ERROR: Could not find all inputs in "[' taskStructure(i).id '] ' taskStructure(i).description '"\n']);
-0090             taskReport.ok(i,1)=false;
-0091             tModel=model;
-0092             continue;
-0093         end
-0094         if numel(J)~=numel(unique(J))
-0095             EM=['The constraints on some input(s) in "[' taskStructure(i).id '] ' taskStructure(i).description '" are defined more than one time'];
-0096             dispEM(EM);
-0097         end
-0098         %If all metabolites should be added
-0099         if any(K)
-0100             %Check if ALLMETS is the first metabolite. Otherwise print a
-0101             %warning since it will write over any other constraints that
-0102             %are set
-0103             if K(1)==0
-0104                 EM=['ALLMETS is used as an input in "[' taskStructure(i).id '] ' taskStructure(i).description '" but it it not the first metabolite in the list. Constraints defined for the metabolites before it will be over-written'];
-0105                 dispEM(EM,false);
-0106             end
-0107             %Use the first match of ALLMETS. There should only be one, but
-0108             %still..
-0109             tModel.b(:,1)=taskStructure(i).UBin(find(K,1))*-1;
-0110         end
-0111         %If metabolites in a specific compartment should be used
-0112         if any(L)
-0113             L=find(L);
-0114             for j=1:numel(L)
-0115                 %The compartment defined
-0116                 compartment=upper(taskStructure(i).inputs{L(j)}(11:end-1));
-0117                 %Check if it exists in the model
-0118                 C=find(ismember(upper(model.comps),compartment));
-0119                 if any(C)
-0120                     %Match to metabolites
-0121                     tModel.b(model.metComps==C,1)=taskStructure(i).UBin(L(j))*-1;
-0122                 else
-0123                     EM=['The compartment defined for ALLMETSIN in "[' taskStructure(i).id '] ' taskStructure(i).description '" does not exist'];
-0124                     dispEM(EM);
-0125                 end
-0126             end
-0127         end
-0128         %Then add the normal constraints
-0129         if any(J)
-0130             tModel.b(J,1)=taskStructure(i).UBin(I)*-1;
-0131             tModel.b(J,2)=taskStructure(i).LBin(I)*-1;
-0132         end
-0133     end
-0134     %Set the outputs
-0135     if ~isempty(taskStructure(i).outputs)
-0136         [I, J]=ismember(upper(taskStructure(i).outputs),modelMets);
-0137         J=J(I); %Only keep the ones with matches
-0138         K=ismember(upper(taskStructure(i).outputs),'ALLMETS');
-0139         L=~cellfun('isempty',strfind(upper(taskStructure(i).outputs),'ALLMETSIN'));
-0140         %Check that all metabolites are either real metabolites or
-0141         %ALLMETS/ALLMETSIN
-0142         if ~all(I|K|L)
-0143             fprintf(['ERROR: Could not find all outputs in "[' taskStructure(i).id '] ' taskStructure(i).description '"\n']);
-0144             taskReport.ok(i,1)=false;
-0145             tModel=model;
-0146             continue;
-0147         end
-0148         if numel(J)~=numel(unique(J))
-0149             EM=['The constraints on some output(s) in "[' taskStructure(i).id '] ' taskStructure(i).description '" are defined more than one time'];
-0150             dispEM(EM);
-0151         end
-0152         %If all metabolites should be added
-0153         if any(K)
-0154             %Check if ALLMETS is the first metabolite. Otherwise print a
-0155             %warning since it will write over any other constraints that
-0156             %are set
-0157             if K(1)==0
-0158                 EM=['ALLMETS is used as an output in "[' taskStructure(i).id '] ' taskStructure(i).description '" but it it not the first metabolite in the list. Constraints defined for the metabolites before it will be over-written'];
-0159                 dispEM(EM,false);
-0160             end
-0161             %Use the first match of ALLMETS. There should only be one, but
-0162             %still..
-0163             tModel.b(:,2)=taskStructure(i).UBout(find(K,1));
-0164         end
-0165         %If metabolites in a specific compartment should be used
-0166         if any(L)
-0167             L=find(L);
-0168             for j=1:numel(L)
-0169                 %The compartment defined
-0170                 compartment=upper(taskStructure(i).outputs{L(j)}(11:end-1));
-0171                 %Check if it exists in the model
-0172                 C=find(ismember(upper(model.comps),compartment));
-0173                 if any(C)
-0174                     %Match to metabolites
-0175                     tModel.b(model.metComps==C,2)=taskStructure(i).UBout(L(j));
-0176                 else
-0177                     EM=['The compartment defined for ALLMETSIN in "[' taskStructure(i).id '] ' taskStructure(i).description '" does not exist'];
-0178                     dispEM(EM);
-0179                 end
-0180             end
-0181         end
-0182         %Then add the normal constraints
-0183         if any(J)
-0184             %Verify that IN and OUT bounds are consistent. Cannot require
-0185             %that a metabolite is simultaneously input AND output at some
-0186             %nonzero flux.
-0187             I = find(I);  % otherwise indexing becomes confusing
-0188             nonzero_LBin = tModel.b(J,2) < 0;
-0189             nonzero_LBout = taskStructure(i).LBout(I) > 0;
-0190             if any(nonzero_LBin & nonzero_LBout)
-0191                 EM=['The IN LB and OUT LB in "[' taskStructure(i).id '] ' taskStructure(i).description '" cannot be nonzero for the same metabolite'];
-0192                 dispEM(EM);
-0193             end
-0194             tModel.b(J(nonzero_LBout),1)=taskStructure(i).LBout(I(nonzero_LBout));
-0195             tModel.b(J,2)=taskStructure(i).UBout(I);
-0196         end
-0197     end
-0198     %Add new rxns
-0199     if ~isempty(taskStructure(i).equations)
-0200         rxn.equations=taskStructure(i).equations;
-0201         rxn.lb=taskStructure(i).LBequ;
-0202         rxn.ub=taskStructure(i).UBequ;
-0203         rxn.rxns=strcat({'TEMPORARY_'},num2str((1:numel(taskStructure(i).equations))'));
-0204         %Allow for new metabolites to be added. This is because it should
-0205         %be possible to add, say, a whole new pathway
-0206         tModel=addRxns(tModel,rxn,3,[],true);
-0207     end
-0208     %Add changed bounds
-0209     if ~isempty(taskStructure(i).changed)
-0210         tModel=setParam(tModel,'lb',taskStructure(i).changed,taskStructure(i).LBrxn);
-0211         tModel=setParam(tModel,'ub',taskStructure(i).changed,taskStructure(i).UBrxn);
-0212     end
-0213     
-0214     %Solve and print
-0215     sol=solveLP(tModel);
-0216     if ~isempty(sol.x)
-0217         %assign the fluxes
-0218         essentialFluxes(:,i) = sol.x(1:numel(model.rxns));
-0219         
-0220         if ~taskStructure(i).shouldFail
-0221             taskReport.ok(i,1)=true;
-0222             if printOnlyFailed==false && printOutput==true
-0223                 fprintf(['PASS: [' taskStructure(i).id '] ' taskStructure(i).description '\n']);
-0224             end
-0225             %Calculate the essential reactions
-0226             if getEssential==true
-0227                 [~, taskEssential]=getEssentialRxns(tModel);
-0228                 %This is because there could be more reactions in tModel
-0229                 %than in model
-0230                 essentialRxns(taskEssential(taskEssential<=numel(model.rxns)),i)=true;
-0231             end
-0232         else
-0233             taskReport.ok(i,1)=false;
-0234             if printOutput==true
-0235                 fprintf(['PASS (should fail): [' taskStructure(i).id '] ' taskStructure(i).description '\n']);
-0236             end
-0237         end
-0238     else
-0239         if ~taskStructure(i).shouldFail
-0240             taskReport.ok(i,1)=false;
-0241             if printOutput==true
-0242                 fprintf(['FAIL: [' taskStructure(i).id '] ' taskStructure(i).description '\n']);
-0243             end
-0244         else
-0245             taskReport.ok(i,1)=true;
-0246             if printOnlyFailed==false && printOutput==true
-0247                 fprintf(['FAIL (should fail): [' taskStructure(i).id '] ' taskStructure(i).description '\n']);
-0248             end
-0249         end
-0250     end
-0251     if taskStructure(i).printFluxes && ~isempty(sol.x)
-0252         sol=solveLP(tModel,1);
-0253         if ~isempty(sol.x)
-0254             printFluxes(tModel,sol.x,false,10^-6,[],'%rxnID (%eqn):%flux\n');
-0255             fprintf('\n');
-0256         end
-0257     end
-0258     tModel=model;
-0259 end
-0260 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/compareMultipleModels.html b/doc/core/compareMultipleModels.html deleted file mode 100644 index 9a36fa00d..000000000 --- a/doc/core/compareMultipleModels.html +++ /dev/null @@ -1,521 +0,0 @@ - - - - Description of compareMultipleModels - - - - - - - - - -
Home > core > compareMultipleModels.m
- - - -

compareMultipleModels -

- -

PURPOSE ^

-
compareMultipleModels
- -

SYNOPSIS ^

-
function compStruct = compareMultipleModels(models,printResults,plotResults,groupVector,funcCompare,taskFile)
- -

DESCRIPTION ^

-
 compareMultipleModels
-   Compares two or more condition-specific models generated from the same
-   base model using high-dimensional comparisons in the reaction-space.
-
-   models              cell array of two or more models
-   printResults        true if the results should be printed on the screen
-                       (optional, default false)
-   plotResults         true if the results should be plotted
-                       (optional, default false)
-   groupVector         numeric vector or cell array for grouping similar 
-                       models, i.e. by tissue (optional, default, all models
-                       ungrouped)
-   funcCompare         logical, should a functional comparison be run
-                       (optional,default, false)
-   taskFile            string containing the name of the task file to use
-                       for the functional comparison (should be an .xls or 
-                       .xlsx file, required for functional comparison)
-
-   compStruct          structure that contains the comparison results
-       modelIDs        cell array of model ids
-       reactions       substructure containing reaction information
-           matrix          binary matrix composed of reactions (rows) in
-                           each model (column). This matrix is used as the
-                           input for the model comparisons.
-           IDs             list of the reactions contained in the reaction
-                           matrix.
-       subsystems      substructure containing subsystem information
-           matrix          matrix with comparison of number of rxns per
-                           subsystem
-           ID              vector consisting of names of all subsystems
-       structComp      matrix with pairwise comparisons of model structure
-                       based on (1-Hamming distance) between models
-       structCompMap   matrix with 3D tSNE (or MDS) mapping of model
-                       structures based on Hamming distances
-       funcComp        substructure containing function comparison results
-           matrix          matrix with PASS / FAIL (1 / 0) values for each
-                           task
-           tasks           vector containing names of all tasks
-
- Usage: compStruct=compareMultipleModels(models,printResults,...
-                       plotResults,groupVector,funcCompare,taskFile);
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 function compStruct = compareMultipleModels(models,printResults,plotResults,groupVector,funcCompare,taskFile)
-0002 % compareMultipleModels
-0003 %   Compares two or more condition-specific models generated from the same
-0004 %   base model using high-dimensional comparisons in the reaction-space.
-0005 %
-0006 %   models              cell array of two or more models
-0007 %   printResults        true if the results should be printed on the screen
-0008 %                       (optional, default false)
-0009 %   plotResults         true if the results should be plotted
-0010 %                       (optional, default false)
-0011 %   groupVector         numeric vector or cell array for grouping similar
-0012 %                       models, i.e. by tissue (optional, default, all models
-0013 %                       ungrouped)
-0014 %   funcCompare         logical, should a functional comparison be run
-0015 %                       (optional,default, false)
-0016 %   taskFile            string containing the name of the task file to use
-0017 %                       for the functional comparison (should be an .xls or
-0018 %                       .xlsx file, required for functional comparison)
-0019 %
-0020 %   compStruct          structure that contains the comparison results
-0021 %       modelIDs        cell array of model ids
-0022 %       reactions       substructure containing reaction information
-0023 %           matrix          binary matrix composed of reactions (rows) in
-0024 %                           each model (column). This matrix is used as the
-0025 %                           input for the model comparisons.
-0026 %           IDs             list of the reactions contained in the reaction
-0027 %                           matrix.
-0028 %       subsystems      substructure containing subsystem information
-0029 %           matrix          matrix with comparison of number of rxns per
-0030 %                           subsystem
-0031 %           ID              vector consisting of names of all subsystems
-0032 %       structComp      matrix with pairwise comparisons of model structure
-0033 %                       based on (1-Hamming distance) between models
-0034 %       structCompMap   matrix with 3D tSNE (or MDS) mapping of model
-0035 %                       structures based on Hamming distances
-0036 %       funcComp        substructure containing function comparison results
-0037 %           matrix          matrix with PASS / FAIL (1 / 0) values for each
-0038 %                           task
-0039 %           tasks           vector containing names of all tasks
-0040 %
-0041 % Usage: compStruct=compareMultipleModels(models,printResults,...
-0042 %                       plotResults,groupVector,funcCompare,taskFile);
-0043 
-0044 %% Stats toolbox required
-0045 if ~(exist('mdscale.m','file') && exist('pdist.m','file') && exist('squareform.m','file') && exist('tsne.m','file'))
-0046     error('The MATLAB Statistics and Machine Learning Toolbox is required for this function')
-0047 end
-0048 
-0049 %% Set up input defaults
-0050 if nargin < 2 || isempty(printResults)
-0051     printResults=false;
-0052 end
-0053 if nargin < 3 || isempty(plotResults)
-0054     plotResults=false;
-0055 end
-0056 if nargin < 4
-0057     groupVector = [];
-0058 elseif ~isnumeric(groupVector)
-0059     % convert strings to numeric groups
-0060     [groupNames,~,groupVector] = unique(groupVector);
-0061 else
-0062     % generate group names for vector of numbers
-0063     groupNames = arrayfun(@num2str,unique(groupVector),'UniformOutput',false);
-0064 end
-0065 if nargin < 5 || isempty(funcCompare)
-0066     funcCompare = false;
-0067 end
-0068 if nargin < 6
-0069     taskFile = [];
-0070 else
-0071     taskFile=char(taskFile);
-0072 end
-0073 if numel(models) <= 1
-0074     EM = 'Cannot compare only one model. Use printModelStats if you want a summary of a model';
-0075     dispEM(EM);
-0076 end
-0077 if isempty(taskFile) && funcCompare
-0078     EM = 'Cannot perform the functional comparison without a task file. Specify taskFile or set funcCompare to FALSE.';
-0079     dispEM(EM);
-0080 end
-0081 
-0082 %% Set up model ID structure
-0083 compStruct.modelIDs = {};
-0084 fprintf('\n Getting model IDs \n')    
-0085 for i = 1:numel(models)
-0086     if ~ischar(models{i}.id)  % to deal with non-character IDs (cells, strings, etc)
-0087         compStruct.modelIDs{i,1} = models{i}.id{1};
-0088     else
-0089         compStruct.modelIDs{i,1} = models{i}.id;
-0090     end
-0091 end
-0092 fprintf('*** Done \n\n')
-0093 
-0094 
-0095 %% Compare models structure & function based on high-dimensional methods
-0096 % Compare number of reactions in each subsystem in each model using a heatmap
-0097 field = 'subSystems';
-0098 fprintf('\n Comparing subsystem utilization \n')
-0099 if any(~cellfun(@(m) isfield(m,field),models))
-0100     fprintf('\nWARNING: At least one model does not contain the field "subSystems". \n')
-0101     fprintf('         Skipping subsystem comparison. \n\n')
-0102 else
-0103     %% Flatten model subSystems field
-0104     % Convert from cell array of cells to cell array of strings
-0105     % NOTE: this function currently only recognizes one subSystem per reaction;
-0106     %       additional subSystems will be ignored!
-0107     for i = 1:numel(models)
-0108         if any(cellfun(@(x) iscell(x), models{i}.subSystems));
-0109             cells = cellfun(@iscell,models{i}.subSystems);
-0110             models{i}.subSystems(cells) = cellfun(@(s) s{1}, models{i}.subSystems(cells), 'UniformOutput', false);
-0111         end
-0112     end
-0113     [id,compMat] = compareModelField(models,field);
-0114     compStruct.subsystems.ID = id;
-0115     compStruct.subsystems.matrix = compMat;
-0116     fprintf('*** Done \n\n')
-0117     
-0118     if printResults
-0119         % This could use some cleaning up
-0120         fprintf('*** Comparison of reaction subsystem populations:\n\n');
-0121         
-0122         nrow = min([15,numel(compStruct.subsystems.ID)]);
-0123         ncol = min([10,numel(compStruct.modelIDs)]);
-0124         summaryArray = [{field}, compStruct.modelIDs(1:ncol)'];
-0125         summaryArray = [summaryArray; [compStruct.subsystems.ID(1:nrow), ...
-0126             arrayfun(@num2str,compStruct.subsystems.matrix(1:nrow,1:ncol),'UniformOutput',false)]];
-0127         
-0128         charArray = [];
-0129         for i = 1:size(summaryArray,2)
-0130             charArray = [charArray, char(strcat(summaryArray(:,i),{'   '}))];
-0131         end
-0132         disp(charArray);
-0133         if numel(compStruct.subsystems.ID) > 15
-0134             fprintf('...\n');
-0135         end
-0136         fprintf('\n\n');
-0137     end
-0138     
-0139     if plotResults==true
-0140         % Plot all subsystems
-0141         figure;
-0142         plottingData = (compStruct.subsystems.matrix - mean(compStruct.subsystems.matrix,2))./mean(compStruct.subsystems.matrix,2);
-0143         color_map = redblue(length(0:.01:2));
-0144         h = genHeatMap(plottingData',compStruct.subsystems.ID,compStruct.modelIDs,'both','euclidean',color_map,[-1,1]);
-0145         title('Subsystem Coverage - all subsystems','FontSize',18,'FontWeight','bold')
-0146         
-0147         % Plot only subsystems with deviation from mean
-0148         keepSubs = (sum(plottingData~=0,2) ~= 0);
-0149         if sum(keepSubs) > 1
-0150             figure;
-0151             h_small = genHeatMap(plottingData(keepSubs,:)',compStruct.subsystems.ID(keepSubs),...
-0152                 compStruct.modelIDs,'both','euclidean',color_map,[-1,1]);
-0153             title('Subsystem Coverage','FontSize',18,'FontWeight','bold')
-0154             
-0155             % Plot enrichment in subsystems with deviation from mean
-0156             figure;
-0157             color_map_bw = [1 1 1;0 0 0];
-0158             h_enriched = genHeatMap(plottingData(keepSubs,:)',compStruct.subsystems.ID(keepSubs),...
-0159                 compStruct.modelIDs,'both','euclidean',color_map_bw,[-10^-4,10^-4]);
-0160             title('Subsystem Enrichment','FontSize',18,'FontWeight','bold')
-0161         end
-0162     end
-0163     
-0164 end
-0165 
-0166 % Compare overall reaction structure across all models using a heatmap
-0167 field = 'rxns';
-0168 fprintf('\n Comparing model reaction correlations \n')
-0169 
-0170 % Create binary matrix of reactions
-0171 [id,binary_matrix] = compareModelField(models,field);
-0172 compStruct.reactions.IDs = id;
-0173 compStruct.reactions.matrix = binary_matrix;
-0174 
-0175 % calculate hamming similarity
-0176 compStruct.structComp = 1-squareform(pdist(binary_matrix','hamming'));
-0177 fprintf('*** Done \n\n')
-0178 if plotResults == true
-0179     color_map = [ones(100,1) linspace(1,0,100)' linspace(1,0,100)'];
-0180     figure;
-0181     h = genHeatMap(compStruct.structComp,compStruct.modelIDs,compStruct.modelIDs,'both','euclidean',color_map);
-0182     title('Structural Similarity','FontSize',18,'FontWeight','bold')
-0183 end
-0184 
-0185 % Compare overall reaction structure across all models using tSNE projection
-0186 rng(42) % For consistency
-0187 fprintf('\n Comparing model reaction structures \n')
-0188 if exist('tsne') > 0
-0189     proj_coords = tsne(double(binary_matrix'),'Distance','hamming','NumDimensions',3); % 3D
-0190     compStruct.structCompMap = proj_coords;
-0191     axis_labels = {'tSNE 1';'tSNE 2';'tSNE 3'};
-0192 else % Seems odd to use mdscale if tsne is not found, as both are
-0193      % distributed with stats toolbox. If tsne is not present, then also
-0194      % mdscale is missing. Anyway, will leave this for now.
-0195     [proj_coords,stress,disparities] = mdscale(pdist(double(binary_matrix'),'hamming'),3);
-0196     compStruct.structCompMap = proj_coords;
-0197     axis_labels = {'MDS 1';'MDS 2';'MDS 3'};
-0198 end
-0199 fprintf('*** Done \n\n')
-0200 
-0201 % plot structure comparison results
-0202 if plotResults == true
-0203     figure; hold on;
-0204     if ~isempty(groupVector)
-0205         color_data = groupVector;
-0206         if length(groupNames) <= 7
-0207             % "lines" colormap only has 7 unique colors
-0208             color_palette = lines(length(groupNames));
-0209         else
-0210             color_palette = parula(length(groupNames));
-0211         end
-0212         colormap(color_palette);
-0213     else
-0214         color_data = 'k';
-0215     end
-0216     scatter3(proj_coords(:,1),proj_coords(:,2),proj_coords(:,3),35,color_data,'filled');
-0217     view(135,25);  % to make it obvious that it is a 3D plot
-0218     xlabel(axis_labels{1}); ylabel(axis_labels{2}); zlabel(axis_labels{3});
-0219     set(gca,'FontSize',14,'LineWidth',1.25);
-0220     title('Structural Comparison','FontSize',18,'FontWeight','bold')
-0221     
-0222     % add legend
-0223     if ~isempty(groupVector)
-0224         for i = 1:length(groupNames)
-0225             h(i) = scatter3([],[],[],35,color_palette(i,:),'filled');
-0226         end
-0227         legend(h,groupNames);
-0228     end
-0229 end
-0230 
-0231 % Compare model functions by assessing their capacity to perform tasks
-0232 if funcCompare == true && ~isempty(taskFile)
-0233     fprintf('\n Checking model performance on specified tasks. \n')
-0234     taskStructure=parseTaskList(taskFile);
-0235     for i = 1:numel(models)
-0236         fprintf('\n Checking model # %.0f \n',i)
-0237         taskReport{i} = checkTasks(models{i},[],false,false,false,taskStructure);
-0238     end    
-0239     
-0240     % Save results
-0241     taskMatrix = zeros(length(taskReport{1}.ok),numel(taskReport));
-0242         for i = 1:numel(taskReport)
-0243             taskMatrix(:,i) = taskReport{i}.ok;
-0244         end
-0245     compStruct.funcComp.matrix = taskMatrix;
-0246     compStruct.funcComp.tasks = taskReport{1}.description;
-0247     fprintf('*** Done \n\n')
-0248    
-0249     % Plot results
-0250     if plotResults == true
-0251         figure;
-0252         color_map_bw = [1 1 1;0 0 0];
-0253         h_enriched = genHeatMap(taskMatrix,compStruct.modelIDs,...
-0254             taskReport{1}.description,'both','euclidean',color_map_bw,[0,1]);
-0255         title('Functional Comparison - All Tasks','FontSize',18,'FontWeight','bold')
-0256         
-0257         figure;
-0258         color_map_bw = [1 1 1;0 0 0];
-0259         h_enriched = genHeatMap(taskMatrix(intersect(find(sum(taskMatrix,2)~=numel(models)),find(sum(taskMatrix,2)~=0)),:),...
-0260             compStruct.modelIDs,taskReport{1}.description(intersect(find(sum(taskMatrix,2)~=numel(models)),find(sum(taskMatrix,2)~=0))),...
-0261             'both','euclidean',color_map_bw,[0,1]);
-0262         title('Functional Similarity','FontSize',18,'FontWeight','bold')
-0263     end
-0264 end
-0265 
-0266 end
-0267 
-0268 %% Additional Functions
-0269 
-0270 function [id,compMat] = compareModelField(models,field)
-0271     % Generates a list of unique field entries and a matrix quantifying the
-0272     % number of appearances of each field entry in each model
-0273     
-0274     % get unique list of field entries
-0275     hasfield = cellfun(@(m) isfield(m,field),models);
-0276     id = cellfun(@(m) m.(field),models(hasfield),'UniformOutput',false);
-0277     id = unique(vertcat(id{:}));
-0278     
-0279     % assemble matrix comparing frequency of each entry in each model
-0280     compMat = zeros(numel(id),numel(models));
-0281     for i = 1:numel(models)
-0282         [~,entryIndex] = ismember(models{i}.(field),id);  % get index of each field entry in the unique id list
-0283         compMat(:,i) = histcounts(entryIndex, 0.5:1:(numel(id)+0.5));  % determine the frequency at which each index appears
-0284     end
-0285 end
-0286 
-0287 
-0288 function h = genHeatMap(data,colnames,rownames,clust_dim,clust_dist,col_map,col_bounds,grid_color)
-0289 %genHeatMap  Generate a heatmap for a given matrix of data.
-0290 %
-0291 % Usage:
-0292 %
-0293 %   genHeatMap(data,colnames,rownames,clust_dim,clust_dist,col_map,col_bounds,grid_color);
-0294 %
-0295 % Inputs:
-0296 %
-0297 % data        Numerical matrix.
-0298 %
-0299 % colnames    Cell array of data column names.
-0300 %
-0301 % rownames    Cell array of data row names.
-0302 %
-0303 % clust_dim   'none' - the data will be plotted as provided (DEFAULT)
-0304 %             'rows' - cluster/rearrange the rows based on distance
-0305 %             'cols' - cluster/rearrange the columns based on distance
-0306 %             'both' - cluster/rearrange rows and columns based on distance
-0307 %
-0308 % clust_dist  Distance metric to be used for clustering, ignored if
-0309 %             clust_dim is 'none'. Options are the same as those for
-0310 %             distance in, e.g., PDIST ('euclidean', 'hamming', etc.).
-0311 %             (DEFAULT = 'euclidean')
-0312 %
-0313 % col_map     Colormap, provided as string (e.g., 'parula', 'hot', 'etc.')
-0314 %             or an Nx3 RGB matrix of N colors.
-0315 %             (DEFAULT = 'hot')
-0316 %
-0317 % col_bounds  A 2-element vector with min and max values, to manually set
-0318 %             the bounds of the colormap.
-0319 %             (DEFAULT = min/max of data).
-0320 %
-0321 % grid_color  Color of the grid surrounding the heatmap cells.
-0322 %             (DEFAULT = 'none')
-0323 %
-0324 %
-0325 
-0326 % handle input arguments
-0327 if nargin < 4 || isempty(clust_dim)
-0328     clust_dim = 'none';
-0329 elseif ~ismember(clust_dim,{'none','rows','cols','both'})
-0330     error('%s is not a valid CLUST_DIM option. Choose "none", "rows", "cols", or "both".',clust_dim);
-0331 end
-0332 if nargin < 5 || isempty(clust_dist)
-0333     clust_dist = 'euclidean';
-0334 end
-0335 if nargin < 6 || isempty(col_map)
-0336     col_map = 'hot';
-0337 end
-0338 if nargin < 7 || isempty(col_bounds)
-0339     col_bounds = [min(data(:)),max(data(:))];
-0340 end
-0341 if nargin < 8
-0342     grid_color = 'none';
-0343 end
-0344 
-0345 % perform hierarchical clustering to sort rows (if specified)
-0346 linkage_method = 'average';
-0347 if ismember(clust_dim,{'rows','both'})
-0348     L = linkage(data,linkage_method,clust_dist);
-0349     row_ind = optimalleaforder(L,pdist(data,clust_dist));
-0350 else
-0351     row_ind = 1:size(data,1);
-0352 end
-0353 % perform hierarchical clustering to sort columns (if specified)
-0354 if ismember(clust_dim,{'cols','both'})
-0355     L = linkage(data',linkage_method,clust_dist);
-0356     col_ind = optimalleaforder(L,pdist(data',clust_dist));
-0357 else
-0358     col_ind = 1:size(data,2);
-0359 end
-0360 
-0361 % reorder data matrix according to clustering results
-0362 sortdata = data(row_ind,col_ind);
-0363 sortrows = rownames(row_ind);
-0364 sortcols = colnames(col_ind);
-0365 
-0366 % check if data is square matrix with identical row and column names
-0367 if (length(colnames) == length(rownames)) && all(strcmp(colnames,rownames))
-0368     % flip data so the diagonal is from upper left to lower right
-0369     sortdata = fliplr(sortdata);
-0370     sortcols = flipud(sortcols);
-0371 end
-0372 
-0373 % pad data matrix with zeros (pcolor cuts off last row and column)
-0374 sortdata(end+1,end+1) = 0;
-0375 
-0376 % generate pcolor plot
-0377 a = axes;
-0378 set(a,'YAxisLocation','Right','XTick',[],'YTick', (1:size(sortdata,1))+0.5,'YTickLabels',sortrows);
-0379 set(a,'TickLength',[0 0],'XLim',[1 size(sortdata,2)],'YLim',[1 size(sortdata,1)]);
-0380 hold on
-0381 
-0382 h = pcolor(sortdata);
-0383 set(h,'EdgeColor',grid_color);
-0384 set(gca,'XTick', (1:size(sortdata,2))+0.5);
-0385 set(gca,'YTick', (1:size(sortdata,1))+0.5);
-0386 set(gca,'XTickLabels',sortcols,'YTickLabels',sortrows);
-0387 set(gca,'XTickLabelRotation',90);
-0388 colormap(col_map);
-0389 
-0390 if ~isempty(col_bounds)
-0391     caxis(col_bounds);
-0392 end
-0393 
-0394 end
-0395 
-0396 
-0397 function c = redblue(m)
-0398 %REDBLUE    Shades of red and blue color map
-0399 %   REDBLUE(M), is an M-by-3 matrix that defines a colormap.
-0400 %   The colors begin with bright blue, range through shades of
-0401 %   blue to white, and then through shades of red to bright red.
-0402 %   REDBLUE, by itself, is the same length as the current figure's
-0403 %   colormap. If no figure exists, MATLAB creates one.
-0404 %
-0405 %   For example, to reset the colormap of the current figure:
-0406 %
-0407 %             colormap(redblue)
-0408 %
-0409 %   See also HSV, GRAY, HOT, BONE, COPPER, PINK, FLAG,
-0410 %   COLORMAP, RGBPLOT.
-0411 if nargin < 1, m = size(get(gcf,'colormap'),1); end
-0412 
-0413 if (mod(m,2) == 0)
-0414     % From [0 0 1] to [1 1 1], then [1 1 1] to [1 0 0];
-0415     m1 = m*0.5;
-0416     r = (0:m1-1)'/max(m1-1,1);
-0417     g = r;
-0418     r = [r; ones(m1,1)];
-0419     g = [g; flipud(g)];
-0420     b = flipud(r);
-0421 else
-0422     % From [0 0 1] to [1 1 1] to [1 0 0];
-0423     m1 = floor(m*0.5);
-0424     r = (0:m1-1)'/max(m1,1);
-0425     g = r;
-0426     r = [r; ones(m1+1,1)];
-0427     g = [g; 1; flipud(g)];
-0428     b = flipud(r);
-0429 end
-0430 
-0431 c = [r g b];
-0432 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/compareRxnsGenesMetsComps.html b/doc/core/compareRxnsGenesMetsComps.html deleted file mode 100644 index 8fd6da1bb..000000000 --- a/doc/core/compareRxnsGenesMetsComps.html +++ /dev/null @@ -1,247 +0,0 @@ - - - - Description of compareRxnsGenesMetsComps - - - - - - - - - -
Home > core > compareRxnsGenesMetsComps.m
- - - -

compareRxnsGenesMetsComps -

- -

PURPOSE ^

-
compareRxnsGenesMetsComps
- -

SYNOPSIS ^

-
function compStruct=compareRxnsGenesMetsComps(models,printResults)
- -

DESCRIPTION ^

-
 compareRxnsGenesMetsComps
-   Compares two or more models with respect to overlap in terms of genes,
-   reactions, metabolites and compartments.
-
-   models              cell array of two or more models
-   printResults        true if the results should be printed on the screen
-                       (optional, default false)
-
-   compStruct          structure that contains the comparison
-       modelIDs        cell array of model ids
-       rxns            These contain the comparison for each field. 'equ' are
-                       the equations after sorting and 'uEqu' are the
-                       equations when not taking compartmentalization into acount
-       mets
-       genes
-       eccodes
-       metNames
-       equ
-       uEqu
-           comparison    binary matrix where each row indicate which models are
-                       included in the comparison
-           nElements   vector with the number of elements for each
-                       comparison
-
- Usage: compStruct=compareRxnsGenesMetsComps(models,printResults)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 function compStruct=compareRxnsGenesMetsComps(models,printResults)
-0002 % compareRxnsGenesMetsComps
-0003 %   Compares two or more models with respect to overlap in terms of genes,
-0004 %   reactions, metabolites and compartments.
-0005 %
-0006 %   models              cell array of two or more models
-0007 %   printResults        true if the results should be printed on the screen
-0008 %                       (optional, default false)
-0009 %
-0010 %   compStruct          structure that contains the comparison
-0011 %       modelIDs        cell array of model ids
-0012 %       rxns            These contain the comparison for each field. 'equ' are
-0013 %                       the equations after sorting and 'uEqu' are the
-0014 %                       equations when not taking compartmentalization into acount
-0015 %       mets
-0016 %       genes
-0017 %       eccodes
-0018 %       metNames
-0019 %       equ
-0020 %       uEqu
-0021 %           comparison    binary matrix where each row indicate which models are
-0022 %                       included in the comparison
-0023 %           nElements   vector with the number of elements for each
-0024 %                       comparison
-0025 %
-0026 % Usage: compStruct=compareRxnsGenesMetsComps(models,printResults)
-0027 
-0028 if nargin<2
-0029     printResults=true;
-0030 end
-0031 
-0032 if numel(models)<=1
-0033     EM='Cannot compare only one model. Use printModelStats if you want a summary of a model';
-0034     dispEM(EM);
-0035 end
-0036 
-0037 compStruct.modelIDs={};
-0038 for i=1:numel(models)
-0039     compStruct.modelIDs=[compStruct.modelIDs;models{i}.id];
-0040     models{i}.equ=constructEquations(models{i},models{i}.rxns,true,true,true);
-0041     models{i}.uEqu=constructEquations(models{i},models{i}.rxns,false,true,true);
-0042 end
-0043 
-0044 field='rxns';
-0045 compStruct.rxns.comparison=getToCheck(models,field);
-0046 compStruct.rxns.nElements=checkStuff(getElements(models,field),compStruct.rxns.comparison);
-0047 if printResults==true
-0048     fprintf('*** Comparison of reaction IDs:\n');
-0049     printList(models,compStruct.rxns.comparison,compStruct.rxns.nElements);
-0050     fprintf('\n\n');
-0051 end
-0052 
-0053 field='mets';
-0054 compStruct.mets.comparison=getToCheck(models,field);
-0055 compStruct.mets.nElements=checkStuff(getElements(models,field),compStruct.mets.comparison);
-0056 if printResults==true
-0057     fprintf('*** Comparison of metabolite IDs:\n');
-0058     printList(models,compStruct.mets.comparison,compStruct.mets.nElements);
-0059     fprintf('\n\n');
-0060 end
-0061 
-0062 field='genes';
-0063 compStruct.genes.comparison=getToCheck(models,field);
-0064 compStruct.genes.nElements=checkStuff(getElements(models,field),compStruct.genes.comparison);
-0065 if printResults==true
-0066     fprintf('*** Comparison of gene IDs:\n');
-0067     printList(models,compStruct.genes.comparison,compStruct.genes.nElements);
-0068     fprintf('\n\n');
-0069 end
-0070 
-0071 field='eccodes';
-0072 compStruct.eccodes.comparison=getToCheck(models,field);
-0073 compStruct.eccodes.nElements=checkStuff(getElements(models,field),compStruct.eccodes.comparison);
-0074 if printResults==true
-0075     fprintf('*** Comparison of ec-numbers:\n');
-0076     printList(models,compStruct.eccodes.comparison,compStruct.eccodes.nElements);
-0077     fprintf('\n\n');
-0078 end
-0079 
-0080 field='metNames';
-0081 compStruct.metNames.comparison=getToCheck(models,field);
-0082 compStruct.metNames.nElements=checkStuff(getElements(models,field),compStruct.metNames.comparison);
-0083 if printResults==true
-0084     fprintf('*** Comparison of metabolite names:\n');
-0085     printList(models,compStruct.metNames.comparison,compStruct.metNames.nElements);
-0086     fprintf('\n\n');
-0087 end
-0088 
-0089 field='equ';
-0090 compStruct.equ.comparison=getToCheck(models,field);
-0091 compStruct.equ.nElements=checkStuff(getElements(models,field),compStruct.equ.comparison);
-0092 if printResults==true
-0093     fprintf('*** Comparison of equations with compartment:\n');
-0094     printList(models,compStruct.equ.comparison,compStruct.equ.nElements);
-0095     fprintf('\n\n');
-0096 end
-0097 
-0098 field='uEqu';
-0099 compStruct.uEqu.comparison=getToCheck(models,field);
-0100 compStruct.uEqu.nElements=checkStuff(getElements(models,field),compStruct.uEqu.comparison);
-0101 if printResults==true
-0102     fprintf('*** Comparison of equations without compartment:\n');
-0103     printList(models,compStruct.uEqu.comparison,compStruct.uEqu.nElements);
-0104     fprintf('\n\n');
-0105 end
-0106 end
-0107 
-0108 function A=getElements(models,field)
-0109 A={};
-0110 for i=1:numel(models)
-0111     if isfield(models{i},field)
-0112         A=[A;{models{i}.(field)}];
-0113     end
-0114 end
-0115 end
-0116 
-0117 function toCheck=getToCheck(models,field)
-0118 %Get all the combinations that should be checked for overlap (including the
-0119 %single ones)
-0120 toCheckA=[];
-0121 I=find(cellfun(@checkField,models));
-0122 nI=numel(I);
-0123 for i=nI:-1:1
-0124     combs=combnk(1:nI,i);
-0125     toAdd=false(size(combs,1),nI);
-0126     for j=1:size(combs,1)
-0127         toAdd(j,combs(j,:))=true;
-0128     end
-0129     toCheckA=[toCheckA;toAdd];
-0130 end
-0131 
-0132 %If not all of the models have the required field
-0133 toCheck=false(size(toCheckA,1),numel(models));
-0134 toCheck(:,I)=toCheckA;
-0135 
-0136 %Ugly thing to get around parameters
-0137     function I=checkField(A)
-0138         I=isfield(A,field);
-0139     end
-0140 end
-0141 
-0142 function printList(models,toCheck,nElements)
-0143 %To guess how many spaces that are needed to align
-0144 firstLen=[];
-0145 for i=1:size(toCheck,1)
-0146     label=[];
-0147     I=find(toCheck(i,:));
-0148     for j=1:numel(I)
-0149         label=[label models{I(j)}.id '/'];
-0150     end
-0151     if i==1
-0152         firstLen=numel(label);
-0153     end
-0154     nSpaces=firstLen-numel(label);
-0155     fprintf([label(1:end-1) '  ' repmat(sprintf(' '),1,nSpaces) num2str(nElements(i)) '\n']);
-0156 end
-0157 end
-0158 
-0159 function nElements=checkStuff(A,toCheck)
-0160 %Now loop through the toCheck matrix, starting with the combination with
-0161 %the most models. Only elements that weren't in iteration n are considered
-0162 %in iteration n+1.
-0163 nElements=zeros(size(toCheck,1),1);
-0164 alreadyChecked=[];
-0165 for i=1:size(toCheck,1)
-0166     I=find(toCheck(i,:));
-0167     inCommon=setdiff(A{I(1)},alreadyChecked);
-0168     for j=2:numel(I)
-0169         inCommon=intersect(inCommon,A{I(j)});
-0170     end
-0171     alreadyChecked=union(alreadyChecked,inCommon);
-0172     nElements(i)=numel(inCommon);
-0173 end
-0174 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/constructEquations.html b/doc/core/constructEquations.html deleted file mode 100644 index aa6eb6d07..000000000 --- a/doc/core/constructEquations.html +++ /dev/null @@ -1,182 +0,0 @@ - - - - Description of constructEquations - - - - - - - - - -
Home > core > constructEquations.m
- - - -

constructEquations -

- -

PURPOSE ^

-
constructEquations
- -

SYNOPSIS ^

-
function equationStrings=constructEquations(model,rxns,useComps,sortRevRxns,sortMetNames,useMetID,useFormula,useRevField)
- -

DESCRIPTION ^

-
 constructEquations
-   Construct equation strings for reactions
-
- Input:
-   model             a model structure
-   rxns              either a cell array of reaction IDs, a logical vector
-                     with the same number of elements as reactions in the
-                     model, or a vector of reaction indexes (optional, default
-                     model.rxns)
-   useComps          include the compartment of each metabolite (optional,
-                     default true)
-   sortRevRxns       sort reversible reactions so that the metabolite that
-                     is first in the lexiographic order is a reactant
-                     (optional, default false)
-   sortMetNames      sort the metabolite names in the equation. Uses
-                     compartment even if useComps is false (optional, default
-                     false)
-   useMetID          use metabolite ID in generated equations (optional,
-                     default false)
-   useFormula        use metabolite formula in generated equations (optional,
-                     default false)
-   useRevField       use the model.rev field to indicate reaction
-                     reversibility, alternatively this is determined from
-                     the model.ub and model.lb fields (optional, default true)
-
- Output:
-   equationStrings   a cell array with equations
-
- If useRevField is false, then reactions should be organized in their
- forward direction (e.g. ub = 1000 and lb = -1000/0) for the 
- reversibility to be correctly determined.
-
- Usage: equationStrings = constructEquations(model, rxns, useComps,...
-           sortRevRxns, sortMetNames, useMetID, useFormula, useRevField)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function equationStrings=constructEquations(model,rxns,useComps,sortRevRxns,sortMetNames,useMetID,useFormula,useRevField)
-0002 % constructEquations
-0003 %   Construct equation strings for reactions
-0004 %
-0005 % Input:
-0006 %   model             a model structure
-0007 %   rxns              either a cell array of reaction IDs, a logical vector
-0008 %                     with the same number of elements as reactions in the
-0009 %                     model, or a vector of reaction indexes (optional, default
-0010 %                     model.rxns)
-0011 %   useComps          include the compartment of each metabolite (optional,
-0012 %                     default true)
-0013 %   sortRevRxns       sort reversible reactions so that the metabolite that
-0014 %                     is first in the lexiographic order is a reactant
-0015 %                     (optional, default false)
-0016 %   sortMetNames      sort the metabolite names in the equation. Uses
-0017 %                     compartment even if useComps is false (optional, default
-0018 %                     false)
-0019 %   useMetID          use metabolite ID in generated equations (optional,
-0020 %                     default false)
-0021 %   useFormula        use metabolite formula in generated equations (optional,
-0022 %                     default false)
-0023 %   useRevField       use the model.rev field to indicate reaction
-0024 %                     reversibility, alternatively this is determined from
-0025 %                     the model.ub and model.lb fields (optional, default true)
-0026 %
-0027 % Output:
-0028 %   equationStrings   a cell array with equations
-0029 %
-0030 % If useRevField is false, then reactions should be organized in their
-0031 % forward direction (e.g. ub = 1000 and lb = -1000/0) for the
-0032 % reversibility to be correctly determined.
-0033 %
-0034 % Usage: equationStrings = constructEquations(model, rxns, useComps,...
-0035 %           sortRevRxns, sortMetNames, useMetID, useFormula, useRevField)
-0036 
-0037 if nargin<2 || isempty(rxns)
-0038     rxns=model.rxns;
-0039 elseif ~islogical(rxns) && ~isnumeric(rxns)
-0040     rxns=convertCharArray(rxns);
-0041 end
-0042 if nargin<3
-0043     useComps=true;
-0044 end
-0045 if nargin<4
-0046     sortRevRxns=false;
-0047 end
-0048 if nargin<5
-0049     sortMetNames=false;
-0050 end
-0051 if nargin<6
-0052     useMetID=false;
-0053 end
-0054 if nargin<7
-0055     useFormula=false;
-0056 end
-0057 if nargin<8
-0058     useRevField=true;
-0059 end
-0060 
-0061 %Sort reversible equations
-0062 if sortRevRxns==true
-0063     model=sortModel(model);
-0064 end
-0065 
-0066 %Sort metabolite names, including compartment
-0067 if sortMetNames==true
-0068     model=sortModel(model,false,true);
-0069 end
-0070 
-0071 Rindexes=getIndexes(model,rxns,'rxns');
-0072 
-0073 equationStrings=cell(numel(Rindexes),1);
-0074 
-0075 for i=1:numel(Rindexes)
-0076     Mindexes=find(model.S(:,Rindexes(i)));
-0077     %Define metabolites by id, formula or name, and with or without compartment:
-0078     if useMetID==true && useFormula==false
-0079         mets = model.mets(Mindexes);
-0080     elseif useMetID==false && useFormula==true
-0081         mets = strcat('[',model.metFormulas(Mindexes),']');
-0082     elseif useMetID==true && useFormula==true
-0083         error('Arguments useMetID and useFormula cannot be both TRUE!');
-0084     else
-0085         mets = model.metNames(Mindexes);
-0086     end
-0087     if useComps==true
-0088         comps = model.comps(model.metComps(Mindexes));
-0089         mets  = strcat(mets,'[',comps,']');
-0090     end
-0091     %Define stoich coeffs and reversibility:
-0092     stoichCoeffs = model.S(Mindexes,Rindexes(i));
-0093     if useRevField == true
-0094         isrev        = model.rev(Rindexes(i))==1;
-0095     else
-0096         isrev        = model.lb(Rindexes(i))<0 & model.ub(Rindexes(i))>0;
-0097     end
-0098     
-0099     %Construct equation:
-0100     equationStrings{i} = buildEquation(mets,stoichCoeffs,isrev);
-0101 end
-0102 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/constructS.html b/doc/core/constructS.html deleted file mode 100644 index 0ba99957d..000000000 --- a/doc/core/constructS.html +++ /dev/null @@ -1,250 +0,0 @@ - - - - Description of constructS - - - - - - - - - -
Home > core > constructS.m
- - - -

constructS -

- -

PURPOSE ^

-
constructS
- -

SYNOPSIS ^

-
function [S, mets, badRxns, reversible]=constructS(equations,mets,rxns)
- -

DESCRIPTION ^

-
 constructS
-   Constructs a stoichiometric matrix from a cell array of equations
-
-   equations   cell array of equations on the form 'A + 2 B <=> 3 C',
-               where <=> indicates reversible and => irreversible reactions
-   mets        cell array of metabolites. All metabolites in the equations
-               must be present in the list (optional, default generated from
-               the equations)
-   rxns        cell array of reaction ids. This is only used for printing
-               reaction ids instead of equations in warnings/errors (optional,
-               default [])
-
-   S           the resulting stoichiometric matrix mets cell array with
-               metabolites that corresponds to the order in the S matrix
-   badRxns     boolean vector with the reactions that have one or more
-               metabolites as both substrate and product. An example would
-               be the phosphotransferase ATP + ADP <=> ADP + ATP. In the
-               stoichiometric matrix this equals to an empty reaction
-               which can be problematic
-   reversible  boolean vector with true if the equation is reversible
-
- Usage: [S, mets, badRxns, reversible]=constructS(equations,mets)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 function [S, mets, badRxns, reversible]=constructS(equations,mets,rxns)
-0002 % constructS
-0003 %   Constructs a stoichiometric matrix from a cell array of equations
-0004 %
-0005 %   equations   cell array of equations on the form 'A + 2 B <=> 3 C',
-0006 %               where <=> indicates reversible and => irreversible reactions
-0007 %   mets        cell array of metabolites. All metabolites in the equations
-0008 %               must be present in the list (optional, default generated from
-0009 %               the equations)
-0010 %   rxns        cell array of reaction ids. This is only used for printing
-0011 %               reaction ids instead of equations in warnings/errors (optional,
-0012 %               default [])
-0013 %
-0014 %   S           the resulting stoichiometric matrix mets cell array with
-0015 %               metabolites that corresponds to the order in the S matrix
-0016 %   badRxns     boolean vector with the reactions that have one or more
-0017 %               metabolites as both substrate and product. An example would
-0018 %               be the phosphotransferase ATP + ADP <=> ADP + ATP. In the
-0019 %               stoichiometric matrix this equals to an empty reaction
-0020 %               which can be problematic
-0021 %   reversible  boolean vector with true if the equation is reversible
-0022 %
-0023 % Usage: [S, mets, badRxns, reversible]=constructS(equations,mets)
-0024 
-0025 equations=convertCharArray(equations);
-0026 switch nargin
-0027     case 2
-0028         mets=convertCharArray(mets);
-0029     case 3
-0030         rxns=convertCharArray(rxns);
-0031 end
-0032 
-0033 badRxns=false(numel(equations),1);
-0034 
-0035 %Check that no equations are too short to have reversibility data
-0036 I=cellfun(@numel,equations);
-0037 I=find(I<4,1);
-0038 if any(I)
-0039     if isempty(rxns)
-0040         EM=['The following equation does not have reversibility data: ' equations{I} ];
-0041         dispEM(EM);
-0042     else
-0043         EM=['The reaction ' rxns{I} ' does not have reversibility data'];
-0044         dispEM(EM);
-0045     end
-0046 end
-0047 
-0048 %Makes life a little easier
-0049 equations=strtrim(equations);
-0050 equations=fixEquations(equations);
-0051 
-0052 if nargin<2
-0053     mets=parseRxnEqu(equations);
-0054 end
-0055 if nargin<3
-0056     rxns=[];
-0057 end
-0058 
-0059 %Get which reactions are reversible
-0060 reversible=cellfun(@any,strfind(equations,' <=> '));
-0061 
-0062 %Make them all reversible. This is not all that neat, but nevermind
-0063 equations=strrep(equations,' => ',' <=> ');
-0064 
-0065 %Replace the the plus signs with some weird character that will be used for
-0066 %parsing
-0067 equations=strrep(equations,' + ', '€');
-0068 
-0069 %Generate the stoichiometric matrix
-0070 S=zeros(numel(mets),numel(equations));
-0071 
-0072 %Keep track of coefficients to be added to S-matrix
-0073 metsToS = cell(100000,1);
-0074 rxnsToS = zeros(100000,1);
-0075 coefToS = zeros(100000,1);
-0076 newEntry = 1;
-0077 %Loop through the equations and add the info to the S matrix
-0078 for i=1:numel(equations)
-0079     %Start by finding the position of the (=> or <=>)
-0080     arrowIndex=strfind(equations{i},' <=> ');
-0081     
-0082     if numel(arrowIndex)~=1
-0083         if isempty(rxns)
-0084             EM=['The following equation does not have reversibility data: ' equations{i} ];
-0085             dispEM(EM);
-0086         else
-0087             EM=['The reaction ' rxns{i} ' does not have reversibility data'];
-0088             dispEM(EM);
-0089         end
-0090     end
-0091     
-0092     reactants=regexp(equations{i}(1:arrowIndex-1),'€','split');
-0093     products=regexp(equations{i}(arrowIndex+5:end),'€','split');
-0094     
-0095     %If the splitting character is at the end (if exchange rxns), then an
-0096     %empty string will exist together with the real ones. Remove it
-0097     reactants(cellfun(@isempty,reactants))=[];
-0098     products(cellfun(@isempty,products))=[];
-0099     
-0100     %A vector where an element is -1 is the corresponding metabolite is a
-0101     %reactant and 1 if it's a product
-0102     multiplyWith=[ones(numel(reactants),1)*-1; ones(numel(products),1)];
-0103     
-0104     metabolites=strtrim([reactants products]);
-0105     
-0106     %Now loop through the reactants and see if the metabolite has a
-0107     %coefficient (it will look as 'number name')
-0108     for j=1:numel(metabolites)
-0109         space=strfind(metabolites{j},' ');
-0110         
-0111         if isempty(space)
-0112             %No coefficient
-0113             coeff=1;
-0114             name=metabolites{j};
-0115         else
-0116             coeff=str2double(metabolites{j}(1:space(1)));
-0117             
-0118             %If it was not a coefficiant
-0119             if isnan(coeff)
-0120                 coeff=1;
-0121                 name=strtrim(metabolites{j});
-0122             else
-0123                 name=strtrim(metabolites{j}(space(1)+1:end));
-0124             end
-0125         end
-0126         
-0127         %Find the name in the mets list [a b]=ismember(name,mets);
-0128         metsToS{newEntry}=name;
-0129         rxnsToS(newEntry)=i;
-0130         coefToS(newEntry)=coeff*multiplyWith(j);
-0131         newEntry=newEntry+1;
-0132     end
-0133 end
-0134 %Remove unused fields
-0135 metsToS(newEntry:end)=[];
-0136 rxnsToS(newEntry:end)=[];
-0137 coefToS(newEntry:end)=[];
-0138 
-0139 %Match to mets array
-0140 [metsPresent,metsLoc]=ismember(metsToS,mets);
-0141 
-0142 %Find badRxns
-0143 [~,I]=unique([rxnsToS,metsLoc],'rows','stable');
-0144 x=1:length(rxnsToS);
-0145 x(I)=[];
-0146 x=unique(rxnsToS(x));
-0147 badRxns(x)=true;
-0148 
-0149 if any(~metsPresent)
-0150     if isempty(rxns)
-0151         error(['Could not find the following metabolites in the metabolite list: ',...
-0152         strjoin(unique(metsToS(~metsPresent)),', ')],'')
-0153     else
-0154         missingMet = find(~metsPresent);
-0155         missingMet = strcat(metsToS(missingMet),' (reaction:',rxns(rxnsToS(missingMet)),')\n');
-0156         missingMet = strjoin(missingMet,'');
-0157         error(['Could not find the following metabolites (reaction indicated) in the metabolite list: \n' ...
-0158             missingMet '%s'],'');
-0159     end
-0160 end
-0161 linearIndices=sub2ind(size(S),metsLoc,rxnsToS);
-0162 S(linearIndices)=coefToS;
-0163 S=sparse(S);
-0164 end
-0165 
-0166 function equ=fixEquations(equ)
-0167 %If the equation starts with "=>" or "<=>" then add a space again. This is
-0168 %an alternative way to represent uptake reactions. The opposite way for
-0169 %producing reactions
-0170 equ=equ(:);
-0171 for i=1:numel(equ)
-0172     if strcmp(equ{i}(1:2),'=>') || strcmp(equ{i}(1:3),'<=>')
-0173         equ{i}=[' ' equ{i}];
-0174     else
-0175         if strcmp(equ{i}(end-1:end),'=>') || strcmp(equ{i}(end-2:end),'<=>')
-0176             equ{i}=[equ{i} ' '];
-0177         end
-0178     end
-0179 end
-0180 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/consumeSomething.html b/doc/core/consumeSomething.html deleted file mode 100644 index 77930041e..000000000 --- a/doc/core/consumeSomething.html +++ /dev/null @@ -1,263 +0,0 @@ - - - - Description of consumeSomething - - - - - - - - - -
Home > core > consumeSomething.m
- - - -

consumeSomething -

- -

PURPOSE ^

-
consumeSomething
- -

SYNOPSIS ^

-
function [solution, metabolite]=consumeSomething(model,ignoreMets,isNames,minNrFluxes,params,ignoreIntBounds)
- -

DESCRIPTION ^

-
 consumeSomething
-   Tries to consume any metabolite using as few reactions as possible.
-   The intended use is when you want to make sure that you model cannot
-   consume anything without producing something. It is intended to be used
-   with no active exchange reactions.
-
-   model           a model structure
-   ignoreMets      either a cell array of metabolite IDs, a logical vector
-                   with the same number of elements as metabolites in the model,
-                   of a vector of indexes for metabolites to exclude from
-                   this analysis (optional, default [])
-   isNames         true if the supplied mets represent metabolite names
-                   (as opposed to IDs). This is a way to delete
-                   metabolites in several compartments at once without
-                   knowing the exact IDs. This only works if ignoreMets
-                   is a cell array (optional, default false)
-   minNrFluxes     solves the MILP problem of minimizing the number of
-                   fluxes instead of the sum. Slower, but can be
-                   used if the sum gives too many fluxes (optional, default
-                   false)
-   params          *obsolete option*
-   ignoreIntBounds    true if internal bounds (including reversibility)
-                   should be ignored. Exchange reactions are not affected.
-                   This can be used to find unbalanced solutions which are
-                   not possible using the default constraints (optional,
-                   default false)
-
-   solution        flux vector for the solution
-   metabolite      the index of the metabolite(s) which was consumed. If
-                   possible only one metabolite is reported, but there are
-                   situations where metabolites can only be consumed in
-                   pairs (or more)
-
-   NOTE: This works by forcing at least 1 unit of "any metabolites" to be
-   consumed and then minimize for the sum of fluxes. If more than one
-   metabolite is consumed, it picks one of them to be consumed and then
-   minimizes for the sum of fluxes.
-
- Usage: [solution, metabolite]=consumeSomething(model,ignoreMets,isNames,...
-               minNrFluxes,params,ignoreIntBounds)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function [solution, metabolite]=consumeSomething(model,ignoreMets,isNames,minNrFluxes,params,ignoreIntBounds)
-0002 % consumeSomething
-0003 %   Tries to consume any metabolite using as few reactions as possible.
-0004 %   The intended use is when you want to make sure that you model cannot
-0005 %   consume anything without producing something. It is intended to be used
-0006 %   with no active exchange reactions.
-0007 %
-0008 %   model           a model structure
-0009 %   ignoreMets      either a cell array of metabolite IDs, a logical vector
-0010 %                   with the same number of elements as metabolites in the model,
-0011 %                   of a vector of indexes for metabolites to exclude from
-0012 %                   this analysis (optional, default [])
-0013 %   isNames         true if the supplied mets represent metabolite names
-0014 %                   (as opposed to IDs). This is a way to delete
-0015 %                   metabolites in several compartments at once without
-0016 %                   knowing the exact IDs. This only works if ignoreMets
-0017 %                   is a cell array (optional, default false)
-0018 %   minNrFluxes     solves the MILP problem of minimizing the number of
-0019 %                   fluxes instead of the sum. Slower, but can be
-0020 %                   used if the sum gives too many fluxes (optional, default
-0021 %                   false)
-0022 %   params          *obsolete option*
-0023 %   ignoreIntBounds    true if internal bounds (including reversibility)
-0024 %                   should be ignored. Exchange reactions are not affected.
-0025 %                   This can be used to find unbalanced solutions which are
-0026 %                   not possible using the default constraints (optional,
-0027 %                   default false)
-0028 %
-0029 %   solution        flux vector for the solution
-0030 %   metabolite      the index of the metabolite(s) which was consumed. If
-0031 %                   possible only one metabolite is reported, but there are
-0032 %                   situations where metabolites can only be consumed in
-0033 %                   pairs (or more)
-0034 %
-0035 %   NOTE: This works by forcing at least 1 unit of "any metabolites" to be
-0036 %   consumed and then minimize for the sum of fluxes. If more than one
-0037 %   metabolite is consumed, it picks one of them to be consumed and then
-0038 %   minimizes for the sum of fluxes.
-0039 %
-0040 % Usage: [solution, metabolite]=consumeSomething(model,ignoreMets,isNames,...
-0041 %               minNrFluxes,params,ignoreIntBounds)
-0042 
-0043 if nargin<2
-0044     ignoreMets=[];
-0045 elseif ~islogical(ignoreMets) && ~isnumeric(ignoreMets)
-0046     ignoreMets=convertCharArray(ignoreMets);
-0047 end
-0048 if nargin<3
-0049     isNames=false;
-0050 end
-0051 if nargin<4
-0052     minNrFluxes=false;
-0053 end
-0054 if nargin<5
-0055     params.relGap=0.8;
-0056 end
-0057 if nargin<6
-0058     ignoreIntBounds=false;
-0059 end
-0060 
-0061 if isNames==true && ~isempty(ignoreMets)
-0062     %Check that metsToRemove is a cell array
-0063     if iscellstr(ignoreMets)==false
-0064         EM='Must supply a cell array of strings if isNames=true';
-0065         dispEM(EM);
-0066     end
-0067 end
-0068 
-0069 if isNames==false
-0070     indexesToIgnore=getIndexes(model,ignoreMets,'mets');
-0071 else
-0072     indexesToIgnore=[];
-0073     for i=1:numel(ignoreMets)
-0074         indexesToIgnore=[indexesToIgnore;find(strcmp(ignoreMets(i),model.metNames))];
-0075     end
-0076 end
-0077 
-0078 %Change all internal reactions to be unbounded in both directions
-0079 if ignoreIntBounds==true
-0080     [~, I]=getExchangeRxns(model);
-0081     nonExc=true(numel(model.rxns),1);
-0082     nonExc(I)=false;
-0083     model=setParam(model,'lb',nonExc,-1000);
-0084     model=setParam(model,'ub',nonExc,1000);
-0085     model=setParam(model,'rev',nonExc,1);
-0086 end
-0087 
-0088 solution=[];
-0089 metabolite=[];
-0090 
-0091 nRxns=numel(model.rxns);
-0092 nMets=numel(model.mets);
-0093 
-0094 %Add uptake reactions for all metabolites
-0095 model.S=[model.S speye(nMets)];
-0096 
-0097 %Add so that they all consume a fake metabolite
-0098 model.S=[model.S;[sparse(1,nRxns) ones(1,nMets)*-1]];
-0099 
-0100 %Change so that the ignoreMets have a coefficient 0 in their reactions.
-0101 %Does not remove the actual reaction to make mapping easier later
-0102 model.S(:,indexesToIgnore+nRxns)=0;
-0103 
-0104 %Add an uptake reaction for this last fake metabolite
-0105 model.S(size(model.S,1),size(model.S,2)+1)=1;
-0106 model.b=[model.b;zeros(1,size(model.b,2))];
-0107 model.lb=[model.lb;zeros(nMets,1);1];
-0108 model.ub=[model.ub;inf(nMets+1,1)];
-0109 model.rev=[model.rev;zeros(nMets+1,1)];
-0110 model.c=zeros(size(model.S,2),1);
-0111 
-0112 %Add padding to the reaction annotation to prevent an error in solveLP
-0113 padding=1:numel(model.rev);
-0114 padding=num2cell(padding)';
-0115 padding=cellfun(@num2str,padding,'uniformoutput',false);
-0116 model.rxns=padding;
-0117 model.rxnNames=padding;
-0118 model.eccodes=padding;
-0119 model.rxnMiriams=padding;
-0120 model.grRules=padding;
-0121 if isfield(model,'genes')
-0122     model.rxnGeneMat=sparse(numel(model.rev),numel(model.genes));
-0123 end
-0124 model.subSystems=padding;
-0125 model.rxnFrom=padding;
-0126 model.rxnComps=ones(numel(model.rev),1);
-0127 model.rxnNotes=padding;
-0128 model.rxnReferences=padding;
-0129 model.rxnConfidenceScores=NaN(numel(model.rev),1);
-0130 
-0131 sol=solveLP(model,1);
-0132 if any(sol.x)
-0133     %It could be that several metabolites were consumed in order to get the
-0134     %best solution. The setdiff is to avoid including the last fake
-0135     %metabolite
-0136     I=setdiff(find(sol.x(nRxns+1:end)>0.1),size(model.S,1));
-0137     
-0138     if any(I) %This should always be true
-0139         %Change the coefficients so that only the first is consumed. This
-0140         %is not always possible, but it is tested for since it it results
-0141         %in more easily interpretable results
-0142         
-0143         oldS=model.S;
-0144         foundSingle=false;
-0145         %Test if any of the metabolites could be consumed on their own
-0146         for i=1:numel(I)
-0147             model.S=oldS;
-0148             J=nRxns+1:numel(model.lb)-1;
-0149             J(I(i))=[];
-0150             model.S(:,J)=0;
-0151             sol=solveLP(model);
-0152             if any(sol.x)
-0153                 foundSingle=true;
-0154                 break;
-0155             end
-0156         end
-0157         %This means that there was no metabolite which could be consumed on
-0158         %its own. Then let all the consumeable metabolites be consumed.
-0159         if foundSingle==false
-0160             model.S=oldS;
-0161         end
-0162         if minNrFluxes==true
-0163             %Has to add names for the rxns to prevent an error in
-0164             %minNrFluxes
-0165             model.rxns=cell(numel(model.lb),1);
-0166             model.rxns(:)={'TEMP'};
-0167             model.mets=cell(size(model.b,1),1);
-0168             model.mets(:)={'TEMP'};
-0169             sol=solveLP(model,3,params);
-0170         else
-0171             sol=solveLP(model,1);
-0172         end
-0173         solution=sol.x(1:nRxns);
-0174         metabolite=find(sol.x(nRxns+1:end-1)>0.1);
-0175     end
-0176 end
-0177 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/contractModel.html b/doc/core/contractModel.html deleted file mode 100644 index 260bdc3e0..000000000 --- a/doc/core/contractModel.html +++ /dev/null @@ -1,251 +0,0 @@ - - - - Description of contractModel - - - - - - - - - -
Home > core > contractModel.m
- - - -

contractModel -

- -

PURPOSE ^

-
contractModel
- -

SYNOPSIS ^

-
function [reducedModel, removedRxns, indexedDuplicateRxns]=contractModel(model,distReverse,mets)
- -

DESCRIPTION ^

-
 contractModel
-   Contracts a model by grouping all identical reactions. Similar to the
-   deleteDuplicates part in simplifyModel but more care is taken here
-   when it comes to gene associations. If the duplicated reactions have
-   '_EXP_*' suffixes (where * is a digit), then the model is assumed to
-   have been passed through expandModel, and these suffixes are removed
-   here.
-
-   model                  a model structure
-   distReverse            distinguish reactions with same metabolites
-                          but different reversibility as different
-                          reactions (optional, default true)
-   mets                   string or cell array of strings with metabolite
-                          identifiers, whose involved reactions should be
-                          checked for duplication (optional, by default all
-                          reactions are considered) (option is used by
-                          replaceMets)
-
-   reducedModel           a model structure without duplicate reactions
-   removedRxns            cell array for the removed duplicate reactions
-   indexedDuplicateRxns   indexed cell array for the removed duplicate
-                          reactions (multiple valuess separated by semicolon)
-
-   NOTE: This code might not work for advanced grRules strings
-         that involve nested expressions of 'and' and 'or'.
-
- Usage: [reducedModel, removedRxns, indexedDuplicateRxns]=contractModel(model,distReverse,mets)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 function [reducedModel, removedRxns, indexedDuplicateRxns]=contractModel(model,distReverse,mets)
-0002 % contractModel
-0003 %   Contracts a model by grouping all identical reactions. Similar to the
-0004 %   deleteDuplicates part in simplifyModel but more care is taken here
-0005 %   when it comes to gene associations. If the duplicated reactions have
-0006 %   '_EXP_*' suffixes (where * is a digit), then the model is assumed to
-0007 %   have been passed through expandModel, and these suffixes are removed
-0008 %   here.
-0009 %
-0010 %   model                  a model structure
-0011 %   distReverse            distinguish reactions with same metabolites
-0012 %                          but different reversibility as different
-0013 %                          reactions (optional, default true)
-0014 %   mets                   string or cell array of strings with metabolite
-0015 %                          identifiers, whose involved reactions should be
-0016 %                          checked for duplication (optional, by default all
-0017 %                          reactions are considered) (option is used by
-0018 %                          replaceMets)
-0019 %
-0020 %   reducedModel           a model structure without duplicate reactions
-0021 %   removedRxns            cell array for the removed duplicate reactions
-0022 %   indexedDuplicateRxns   indexed cell array for the removed duplicate
-0023 %                          reactions (multiple valuess separated by semicolon)
-0024 %
-0025 %   NOTE: This code might not work for advanced grRules strings
-0026 %         that involve nested expressions of 'and' and 'or'.
-0027 %
-0028 % Usage: [reducedModel, removedRxns, indexedDuplicateRxns]=contractModel(model,distReverse,mets)
-0029 
-0030 if nargin<2
-0031     distReverse=true;
-0032 end
-0033 
-0034 %First sort the model so that reversible reactions are in the same
-0035 %direction
-0036 modelS=sortModel(model);
-0037 
-0038 %Get a list of duplicate reactions
-0039 if distReverse
-0040     x=[modelS.S; model.rev']';
-0041 else
-0042     x=modelS.S';
-0043 end
-0044 if nargin>2
-0045     toCheck = getIndexes(model,mets,'mets');
-0046     [~, toCheck] = find(modelS.S(toCheck,:));
-0047     x = [x, (1:size(x,1))']; % Make all other rxns unique by additional column
-0048     x(toCheck,end) = 0;
-0049 end
-0050 
-0051 [~,I,J] = unique(x,'rows','first');
-0052 
-0053 %Initialize cell array of indexedDuplicateRxns
-0054 indexedDuplicateRxns=cell(numel(model.rxns),1);
-0055 indexedDuplicateRxns(:)={''};
-0056 
-0057 duplicateRxns=setdiff(1:numel(model.rxns),I);
-0058 mergeTo=I(J(duplicateRxns));
-0059 
-0060 mergedRxns=unique(mergeTo);
-0061 
-0062 %Now add all the info from this one. Print a warning if they have different
-0063 %bounds or objective function coefficients. Uses the widest bounds and
-0064 %largest magnitude of objective coefficient
-0065 for i=1:numel(mergedRxns)
-0066     duplRxn=transpose([mergedRxns(i),duplicateRxns(mergeTo==mergedRxns(i))]);
-0067     if numel(unique(model.lb(duplRxn)))>1
-0068         EM=['Duplicates of reaction ' model.rxns{mergedRxns(i)} ' have different lower bound. Uses the most negative/smallest lower bound'];
-0069         dispEM(EM,false);
-0070         model.lb(mergedRxns(i))=min(model.lb(duplRxn));
-0071     end
-0072     if numel(unique(model.ub(duplRxn)))>1
-0073         EM=['Duplicates of reaction ' model.rxns{mergedRxns(i)} ' have different upper bound. Uses the most positive/largest upper bound'];
-0074         dispEM(EM,false);
-0075         model.ub(mergedRxns(i))=max(model.ub(duplRxn));
-0076     end
-0077     if numel(unique(model.c(duplRxn)))>1
-0078         EM=['Duplicates of reaction ' model.rxns{mergedRxns(i)} ' has a different objective function coefficient. Uses the largest coefficient'];
-0079         dispEM(EM,false);
-0080         model.c(mergedRxns(i))=max(model.c(duplRxn));
-0081     end
-0082     if isfield(model,'grRules') && any(~isempty(model.grRules(duplRxn)))
-0083         rules=model.grRules(duplRxn);
-0084         allRules={};
-0085         for j=1:numel(rules)
-0086             rules{j}=ignoreORinComplex(rules{j});
-0087             allRules=[allRules regexp(rules{j},' or ','split')];
-0088         end
-0089         allRules=unique(allRules);
-0090         allRules=strrep(allRules,'__OR__',' or ');
-0091         andRules=contains(allRules,' and ');
-0092         allRules(andRules)=strcat('(',allRules(andRules),')');
-0093         if numel(allRules)==1
-0094             model.grRules{mergedRxns(i)}=allRules{1};
-0095         else
-0096             model.grRules{mergedRxns(i)}=strjoin(allRules,' or ');
-0097         end
-0098     end    
-0099     if isfield(model,'eccodes') && any(~isempty(model.eccodes(duplRxn)))
-0100         codes=model.eccodes(duplRxn);
-0101         allCodes={};
-0102         for j=1:numel(codes)
-0103             allCodes=[allCodes regexp(codes{j},';','split')];
-0104         end
-0105         allCodes=unique(allCodes);
-0106         if numel(allCodes)==1
-0107             model.eccodes{mergedRxns(i)}=allCodes{1};
-0108         else
-0109             model.eccodes{mergedRxns(i)}=strjoin(allCodes,';');
-0110         end
-0111     end
-0112     %Generate indexedDuplicateRxns cell array
-0113     if numel(duplRxn)==2
-0114         indexedDuplicateRxns{duplRxn(1)}=model.rxns{duplRxn(2)};
-0115     else
-0116         indexedDuplicateRxns{duplRxn(1)}=strjoin(model.rxns(duplRxn(2:end)),';');
-0117     end
-0118     %If all reactions have _EXP_* (where * is digit) as suffix, then the
-0119     %model had passed through expandModel(), and these suffixes are removed.
-0120     if all(~cellfun(@isempty,regexp(model.rxns(duplRxn),'_EXP_\d+$')))
-0121         model.rxns(duplRxn(1))=regexprep(model.rxns(duplRxn(1)),'_EXP_\d+$','');
-0122     end
-0123 end
-0124 
-0125 %Delete the duplicate reactions
-0126 reducedModel=removeReactions(model,duplicateRxns);
-0127 removedRxns=model.rxns(duplicateRxns);
-0128 [~, index]=ismember(reducedModel.rxns,model.rxns);
-0129 indexedDuplicateRxns=indexedDuplicateRxns(index);
-0130 
-0131 if isfield(reducedModel,'rxnGeneMat')
-0132     %Fix grRules and reconstruct rxnGeneMat
-0133     [grRules,rxnGeneMat] = standardizeGrRules(reducedModel,true);
-0134     reducedModel.grRules = grRules;
-0135     reducedModel.rxnGeneMat = rxnGeneMat;
-0136 end
-0137 end
-0138 
-0139 function grRule = ignoreORinComplex(grRule)
-0140 %In a grRule, if OR relationship is nested in an AND relationship, then
-0141 %obfuscate the OR before splitting isoenzymes
-0142 grRule=['(' grRule ')'];
-0143 brOpen=strfind(grRule,'(');
-0144 brClose=strfind(grRule,')');
-0145 andPos=strfind(grRule,' and ');
-0146 %Find opening bracket closest before AND
-0147 stillCapturing = 0;
-0148 for i=1:numel(andPos)
-0149     searchPos = andPos(i);
-0150     while stillCapturing == 0
-0151         closestOpen = brOpen(max(find(brOpen<searchPos)));
-0152         inbetweenClose = brClose(brClose<searchPos & brClose>closestOpen);
-0153         if ~isempty(inbetweenClose)
-0154             searchPos=max(inbetweenClose);
-0155         else
-0156             stillCapturing = 1;
-0157             beginPos = closestOpen;
-0158         end
-0159     end
-0160     stillCapturing = 0;
-0161     searchPos = andPos(i);
-0162     while stillCapturing == 0
-0163         closestClose = brClose(min(find(brClose>searchPos)));
-0164         inbetweenOpen = brOpen(brOpen>searchPos & brOpen<closestOpen);
-0165         if ~isempty(inbetweenOpen)
-0166             searchPos=min(closestClose);
-0167         else
-0168             stillCapturing = 1;
-0169             endPos = closestClose;
-0170         end
-0171     end
-0172     replacePart=regexprep(grRule(beginPos:endPos),' or ','__OR__');
-0173     grRule=strrep(grRule,grRule(beginPos:endPos),replacePart);
-0174 end
-0175 grRule=grRule(2:end-1);
-0176 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/convertCharArray.html b/doc/core/convertCharArray.html deleted file mode 100644 index f2f5bae0c..000000000 --- a/doc/core/convertCharArray.html +++ /dev/null @@ -1,84 +0,0 @@ - - - - Description of convertCharArray - - - - - - - - - -
Home > core > convertCharArray.m
- - - -

convertCharArray -

- -

PURPOSE ^

-
convertCharArray
- -

SYNOPSIS ^

-
function inputConverted = convertCharArray(funcInput)
- -

DESCRIPTION ^

-
convertCharArray
-   Converts input to make sure it is a cell array of character vectors.
-   String arrays are transformed into character vectors, and if only one
-   character vector is given. Output is always a cell array, also if only
-   one character vector is given as input.
-
-   Input:
-   funcInput          function input that should be checked
-
-   Output:
-   inputConverted      cell array of character vectors
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function inputConverted = convertCharArray(funcInput)
-0002 %convertCharArray
-0003 %   Converts input to make sure it is a cell array of character vectors.
-0004 %   String arrays are transformed into character vectors, and if only one
-0005 %   character vector is given. Output is always a cell array, also if only
-0006 %   one character vector is given as input.
-0007 %
-0008 %   Input:
-0009 %   funcInput          function input that should be checked
-0010 %
-0011 %   Output:
-0012 %   inputConverted      cell array of character vectors
-0013 %
-0014 
-0015 if ~isempty(funcInput)
-0016     if ischar(funcInput) || isstring(funcInput)
-0017         inputConverted = {char(funcInput)};
-0018     elseif ~iscell(funcInput) && ~(all(cellfun(@ischar, funcInput)) || all(cellfun(@isstring, funcInput)))
-0019         error([inputname(1) ' should be a (cell array of) character vector(s)'])
-0020     else
-0021         inputConverted = cellstr(funcInput);
-0022     end
-0023 else
-0024     inputConverted=[];
-0025 end
-0026 end
-0027
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/convertToIrrev.html b/doc/core/convertToIrrev.html deleted file mode 100644 index 2e2817afa..000000000 --- a/doc/core/convertToIrrev.html +++ /dev/null @@ -1,182 +0,0 @@ - - - - Description of convertToIrrev - - - - - - - - - -
Home > core > convertToIrrev.m
- - - -

convertToIrrev -

- -

PURPOSE ^

-
convertToIrrev
- -

SYNOPSIS ^

-
function [irrevModel,matchRev,rev2irrev,irrev2rev]=convertToIrrev(model,rxns)
- -

DESCRIPTION ^

-
 convertToIrrev
-   Converts a model to irreversible form
-
- Input:
-   model         a model structure
-   rxns          cell array with the reactions so split (if reversible)
-                 (optional, default model.rxns)
-
- Output:
-   irrevModel    a model structure where reversible reactions have
-                 been split into one forward and one reverse reaction
-   matchRev      matching forward reaction to its backward reaction
-   rev2irrev     forward and backward reactions for reversible reactions
-   irrev2rev     matching all reactions back to original model
-
-   The reverse reactions are saved as 'rxnID_REV'. A warning is shown if
-   some reaction identifiers already end with '_REV'.
-
- Usage: [irrevModel,matchRev,rev2irrev,irrev2rev]=convertToIrrev(model,rxns)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function [irrevModel,matchRev,rev2irrev,irrev2rev]=convertToIrrev(model,rxns)
-0002 % convertToIrrev
-0003 %   Converts a model to irreversible form
-0004 %
-0005 % Input:
-0006 %   model         a model structure
-0007 %   rxns          cell array with the reactions so split (if reversible)
-0008 %                 (optional, default model.rxns)
-0009 %
-0010 % Output:
-0011 %   irrevModel    a model structure where reversible reactions have
-0012 %                 been split into one forward and one reverse reaction
-0013 %   matchRev      matching forward reaction to its backward reaction
-0014 %   rev2irrev     forward and backward reactions for reversible reactions
-0015 %   irrev2rev     matching all reactions back to original model
-0016 %
-0017 %   The reverse reactions are saved as 'rxnID_REV'. A warning is shown if
-0018 %   some reaction identifiers already end with '_REV'.
-0019 %
-0020 % Usage: [irrevModel,matchRev,rev2irrev,irrev2rev]=convertToIrrev(model,rxns)
-0021 
-0022 if nargin<2
-0023     I=true(numel(model.rxns),1);
-0024 else
-0025     rxns=convertCharArray(rxns);
-0026     I=getIndexes(model,rxns,'rxns',true);
-0027 end
-0028 
-0029 irrevModel=model;
-0030 
-0031 revIndexesBool=model.rev~=0 & I;
-0032 revIndexes=find(revIndexesBool);
-0033 numOrigRxns=numel(model.rxns);
-0034 numRevRxns=numel(revIndexes);
-0035 
-0036 if any(revIndexesBool)
-0037     irrevModel.S=[model.S,model.S(:,revIndexes)*-1];
-0038     irrevModel.rev(revIndexes)=0;
-0039     irrevModel.rev=[irrevModel.rev;zeros(numRevRxns,1)];
-0040     
-0041     %Get the limits for all normal and reversible rxns
-0042     ubNormal=irrevModel.ub;
-0043     ubNormal(revIndexes(ubNormal(revIndexes)<0))=0;
-0044     lbNormal=irrevModel.lb;
-0045     lbNormal(revIndexes(lbNormal(revIndexes)<0))=0;
-0046     ubRev=irrevModel.lb(revIndexes)*-1;
-0047     ubRev(ubRev<0)=0;
-0048     lbRev=irrevModel.ub(revIndexes)*-1;
-0049     lbRev(lbRev<0)=0;
-0050     irrevModel.ub=[ubNormal;ubRev];
-0051     irrevModel.lb=[lbNormal;lbRev];
-0052     
-0053     %The objective coefficents should be zero for the backwards reversible
-0054     %reactions unless they were negative in the original. In that case they
-0055     %should be positive for the backwards reversible and deleted from the
-0056     %original
-0057     irrevC=zeros(numRevRxns,1);
-0058     
-0059     if any(irrevModel.c(revIndexes)<0)
-0060         originalC=irrevModel.c(revIndexes);
-0061         irrevC(irrevModel.c(revIndexes)<0)=originalC(originalC<0)*-1;
-0062         irrevModel.c(irrevModel.c<0 & revIndexesBool)=0;
-0063     end
-0064     irrevModel.c=[irrevModel.c;irrevC];
-0065     
-0066     irrevModel.rxns=[irrevModel.rxns;strcat(irrevModel.rxns(revIndexes),'_REV')];
-0067     irrevModel.rxnNames=[irrevModel.rxnNames;strcat(irrevModel.rxnNames(revIndexes),' (reversible)')];
-0068     
-0069     if isfield(irrevModel,'grRules')
-0070         irrevModel.grRules=[irrevModel.grRules;irrevModel.grRules(revIndexes,:)];
-0071     end
-0072     if isfield(irrevModel,'rxnMiriams')
-0073         irrevModel.rxnMiriams=[irrevModel.rxnMiriams;irrevModel.rxnMiriams(revIndexes,:)];
-0074     end
-0075     if isfield(irrevModel,'rxnGeneMat')
-0076         irrevModel.rxnGeneMat=[irrevModel.rxnGeneMat;irrevModel.rxnGeneMat(revIndexes,:)];
-0077     end
-0078     if isfield(irrevModel,'subSystems')
-0079         irrevModel.subSystems=[irrevModel.subSystems;irrevModel.subSystems(revIndexes)];
-0080     end
-0081     if isfield(irrevModel,'eccodes')
-0082         irrevModel.eccodes=[irrevModel.eccodes;irrevModel.eccodes(revIndexes)];
-0083     end
-0084     if isfield(irrevModel,'rxnComps')
-0085         irrevModel.rxnComps=[irrevModel.rxnComps;irrevModel.rxnComps(revIndexes)];
-0086     end
-0087     if isfield(irrevModel,'rxnFrom')
-0088         irrevModel.rxnFrom=[irrevModel.rxnFrom;irrevModel.rxnFrom(revIndexes)];
-0089     end
-0090     if isfield(irrevModel,'rxnScores')
-0091         irrevModel.rxnScores=[irrevModel.rxnScores;irrevModel.rxnScores(revIndexes)];
-0092     end
-0093     if isfield(irrevModel,'rxnNotes')
-0094         irrevModel.rxnNotes=[irrevModel.rxnNotes;irrevModel.rxnNotes(revIndexes)];
-0095     end
-0096     if isfield(irrevModel,'rxnConfidenceScores')
-0097         irrevModel.rxnConfidenceScores=[irrevModel.rxnConfidenceScores;irrevModel.rxnConfidenceScores(revIndexes)];
-0098     end
-0099     if isfield(irrevModel,'rxnDeltaG')
-0100         irrevModel.rxnDeltaG=[irrevModel.rxnDeltaG;-irrevModel.rxnDeltaG(revIndexes)]; % Invert dG for reversed rxns
-0101     end
-0102     if isfield(irrevModel,'rxnReferences')
-0103         irrevModel.rxnReferences=[irrevModel.rxnReferences;irrevModel.rxnReferences(revIndexes)];
-0104     end
-0105 end
-0106     % Additional output
-0107     if nargout>1
-0108         irrev2rev = [transpose(1:numOrigRxns);revIndexes];
-0109         rev2irrev = num2cell(transpose(1:numOrigRxns));
-0110         newIdxs   = [revIndexes transpose(1:numRevRxns)];
-0111         for i=1:numRevRxns
-0112             rev2irrev{revIndexes(i)} = newIdxs(i,:);
-0113         end
-0114         matchRev  = zeros(numel(irrev2rev),1);
-0115         matchRev(revIndexes) = (1:numRevRxns)+numOrigRxns;
-0116     end
-0117 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/copyToComps.html b/doc/core/copyToComps.html deleted file mode 100644 index 33b17a6e0..000000000 --- a/doc/core/copyToComps.html +++ /dev/null @@ -1,175 +0,0 @@ - - - - Description of copyToComps - - - - - - - - - -
Home > core > copyToComps.m
- - - -

copyToComps -

- -

PURPOSE ^

-
copyToComps
- -

SYNOPSIS ^

-
function model=copyToComps(model,toComps,rxns,deleteOriginal,compNames,compOutside)
- -

DESCRIPTION ^

-
 copyToComps
-   Copies reactions to new compartment(s)
-
-   model           a model structure
-   toComps         cell array of compartment ids. If there is no match
-                   to model.comps then it is added as a new compartment
-                   (see below for details)
-   rxns            either a cell array of reaction IDs, a logical vector 
-                   with the same number of elements as reactions in the model,
-                   or a vector of indexes to remove (optional, default
-                   model.rxns)
-   deleteOriginal  true if the original reactions should be removed
-                   (making it move the reactions instead) (optional, default
-                   false)
-   compNames       cell array of compartment names. This is used if new
-                   compartments should be added (optional, default toComps)
-   compOutside     cell array of the id (as in comps) for the compartment
-                   surrounding each of the compartments. This is used if
-                   new compartments should be added (optional, default all {''})
-
-   model           an updated model structure
-
-   NOTE: New reactions and metabolites will be named as "id_toComps(i)".
-
- Usage: model=copyToComps(model,toComps,rxns,deleteOriginal,compNames,compOutside)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function model=copyToComps(model,toComps,rxns,deleteOriginal,compNames,compOutside)
-0002 % copyToComps
-0003 %   Copies reactions to new compartment(s)
-0004 %
-0005 %   model           a model structure
-0006 %   toComps         cell array of compartment ids. If there is no match
-0007 %                   to model.comps then it is added as a new compartment
-0008 %                   (see below for details)
-0009 %   rxns            either a cell array of reaction IDs, a logical vector
-0010 %                   with the same number of elements as reactions in the model,
-0011 %                   or a vector of indexes to remove (optional, default
-0012 %                   model.rxns)
-0013 %   deleteOriginal  true if the original reactions should be removed
-0014 %                   (making it move the reactions instead) (optional, default
-0015 %                   false)
-0016 %   compNames       cell array of compartment names. This is used if new
-0017 %                   compartments should be added (optional, default toComps)
-0018 %   compOutside     cell array of the id (as in comps) for the compartment
-0019 %                   surrounding each of the compartments. This is used if
-0020 %                   new compartments should be added (optional, default all {''})
-0021 %
-0022 %   model           an updated model structure
-0023 %
-0024 %   NOTE: New reactions and metabolites will be named as "id_toComps(i)".
-0025 %
-0026 % Usage: model=copyToComps(model,toComps,rxns,deleteOriginal,compNames,compOutside)
-0027 
-0028 arguments
-0029     model (1,1) struct
-0030     toComps {emptyOrTextOrCellOfText}
-0031     rxns = model.rxns
-0032     deleteOriginal {emptyOrLogicalScalar} = false
-0033     compNames {emptyOrTextOrCellOfText} = toComps
-0034     compOutside {emptyOrTextOrCellOfText} = '';
-0035 end
-0036 
-0037 if nargin >= 3 && ~islogical(rxns) && ~isnumeric(rxns)
-0038     rxns = convertCharArray(rxns);
-0039 end
-0040 if nargin >= 5
-0041     compNames=convertCharArray(compNames);
-0042 end
-0043 if nargin >= 6
-0044     compOutside=convertCharArray(compOutside);
-0045     if length(compOutside) ~= length(compNames)
-0046         error('compOutside and compNames should be of equal size.');
-0047     end
-0048 end
-0049 
-0050 originalID=model.id;
-0051 originalName=model.name;
-0052 
-0053 rxns=getIndexes(model,rxns,'rxns');
-0054 
-0055 for i=1:numel(toComps)
-0056     %Check if the compartment exists, otherwise add it
-0057     [I,J]=ismember(toComps(i),model.comps);
-0058     if I==false
-0059         model.comps=[model.comps;toComps(i)];
-0060         model.compNames=[model.compNames;compNames(i)];
-0061         if isfield(model,'compOutside')
-0062             model.compOutside=[model.compOutside;compOutside(i)];
-0063         end
-0064         if isfield(model,'compMiriams')
-0065             model.compMiriams=[model.compMiriams;cell(1,1)];
-0066         end
-0067         J=numel(model.comps);
-0068     end
-0069     %Copy the reactions by making a model structure with only them, then
-0070     %change the localization, and finally merge with the original model
-0071     modelToAdd=model;
-0072     modelToAdd=removeReactions(modelToAdd,setdiff(1:numel(model.rxns),rxns),true,true);
-0073     modelToAdd.rxns=strcat(modelToAdd.rxns,'_',toComps(i));
-0074     modelToAdd.mets=strcat(modelToAdd.mets,'_',toComps(i));
-0075     modelToAdd.comps=modelToAdd.comps(J);
-0076     modelToAdd.compNames=modelToAdd.compNames(J);
-0077     if isfield(modelToAdd,'compOutside')
-0078         modelToAdd.compOutside=modelToAdd.compOutside(J);
-0079     end
-0080     if isfield(modelToAdd,'compMiriams')
-0081         modelToAdd.compMiriams=modelToAdd.compMiriams(J);
-0082     end
-0083     modelToAdd.metComps=ones(numel(modelToAdd.mets),1);
-0084     if isfield(modelToAdd,'metFrom')
-0085         modelToAdd = rmfield(modelToAdd,'metFrom');
-0086     end
-0087     if isfield(modelToAdd,'rxnFrom')
-0088         modelToAdd = rmfield(modelToAdd,'rxnFrom');
-0089     end
-0090     if isfield(modelToAdd,'geneFrom')
-0091         modelToAdd = rmfield(modelToAdd,'geneFrom');
-0092     end
-0093   
-0094     %Merge the models
-0095     model=mergeModels({model;modelToAdd},'metNames',[],true);
-0096 end
-0097 
-0098 if deleteOriginal==true
-0099     model=removeReactions(model,rxns,true,true,true); %Also delete unused compartments
-0100 end
-0101 
-0102 model.id=originalID;
-0103 model.name=originalName;
-0104 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/deleteUnusedGenes.html b/doc/core/deleteUnusedGenes.html deleted file mode 100644 index 6a9bd7b12..000000000 --- a/doc/core/deleteUnusedGenes.html +++ /dev/null @@ -1,111 +0,0 @@ - - - - Description of deleteUnusedGenes - - - - - - - - - -
Home > core > deleteUnusedGenes.m
- - - -

deleteUnusedGenes -

- -

PURPOSE ^

-
deleteUnusedGenes
- -

SYNOPSIS ^

-
function reducedModel=deleteUnusedGenes(model,verbose)
- -

DESCRIPTION ^

-
 deleteUnusedGenes
-   Deletes all genes that are not associated to any reaction
-
-   model           a model structure
-   verbose         0 for silent; 1 for printing number of deleted genes;
-                   2 for printing the list of deleted genes (optional, default 1)
-
-   reducedModel    an updated model structure
-
- Usage: reducedModel=deleteUnusedGenes(model)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function reducedModel=deleteUnusedGenes(model,verbose)
-0002 % deleteUnusedGenes
-0003 %   Deletes all genes that are not associated to any reaction
-0004 %
-0005 %   model           a model structure
-0006 %   verbose         0 for silent; 1 for printing number of deleted genes;
-0007 %                   2 for printing the list of deleted genes (optional, default 1)
-0008 %
-0009 %   reducedModel    an updated model structure
-0010 %
-0011 % Usage: reducedModel=deleteUnusedGenes(model)
-0012 
-0013 if nargin<2
-0014     verbose=1;
-0015 end
-0016 reducedModel=model;
-0017 
-0018 %Find all genes that are not used
-0019 [~, b]=find(reducedModel.rxnGeneMat);
-0020 toKeep=false(numel(reducedModel.genes),1);
-0021 toKeep(b)=true;
-0022 
-0023 switch verbose
-0024     case 1
-0025         disp('Number of unused genes removed from the model:')
-0026         disp(numel(toKeep(~toKeep)))
-0027     case 2
-0028         disp('The following genes were removed from the model:')
-0029         disp(reducedModel.genes(~toKeep))
-0030     case 0
-0031 end
-0032         
-0033 reducedModel.genes=reducedModel.genes(toKeep);
-0034 reducedModel.rxnGeneMat=reducedModel.rxnGeneMat(:,toKeep);
-0035 
-0036 if isfield(reducedModel,'geneShortNames')
-0037     reducedModel.geneShortNames=reducedModel.geneShortNames(toKeep);
-0038 end
-0039 
-0040 if isfield(reducedModel,'proteins')
-0041     reducedModel.proteins=reducedModel.proteins(toKeep);
-0042 end
-0043 
-0044 if isfield(reducedModel,'geneMiriams')
-0045     reducedModel.geneMiriams=reducedModel.geneMiriams(toKeep);
-0046 end
-0047 
-0048 if isfield(reducedModel,'geneFrom')
-0049     reducedModel.geneFrom=reducedModel.geneFrom(toKeep);
-0050 end
-0051 
-0052 if isfield(reducedModel,'geneComps')
-0053     reducedModel.geneComps=reducedModel.geneComps(toKeep);
-0054 end
-0055 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/dispEM.html b/doc/core/dispEM.html deleted file mode 100644 index 745229f22..000000000 --- a/doc/core/dispEM.html +++ /dev/null @@ -1,115 +0,0 @@ - - - - Description of dispEM - - - - - - - - - -
Home > core > dispEM.m
- - - -

dispEM -

- -

PURPOSE ^

-
dispEM
- -

SYNOPSIS ^

-
function dispEM(string,throwErrors,toList,trimWarnings)
- -

DESCRIPTION ^

-
 dispEM
-   Helper function to print warning/errors
-
-   string          the warning/error to show. "WARNING: " is appended automatically
-                   if a warning
-   throwErrors     true if the function should throw an error (optional, default true)
-   toList          a cell array of items to list. If supplied, then the
-                   string will be printed followed by each element in
-                   toList. If it is supplied but empty then nothing is
-                   printed (optional, default {})
-   trimWarnings    true if only a maximal of 10 items should be displayed in
-                   a given error/warning (optional, default true)
-
- Usage: dispEM(string,throwErrors,toList,trimWarnings)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function dispEM(string,throwErrors,toList,trimWarnings)
-0002 % dispEM
-0003 %   Helper function to print warning/errors
-0004 %
-0005 %   string          the warning/error to show. "WARNING: " is appended automatically
-0006 %                   if a warning
-0007 %   throwErrors     true if the function should throw an error (optional, default true)
-0008 %   toList          a cell array of items to list. If supplied, then the
-0009 %                   string will be printed followed by each element in
-0010 %                   toList. If it is supplied but empty then nothing is
-0011 %                   printed (optional, default {})
-0012 %   trimWarnings    true if only a maximal of 10 items should be displayed in
-0013 %                   a given error/warning (optional, default true)
-0014 %
-0015 % Usage: dispEM(string,throwErrors,toList,trimWarnings)
-0016 
-0017 if nargin<2
-0018     throwErrors=true;
-0019 end
-0020 if nargin<3
-0021     toList=[];
-0022 elseif isempty(toList)
-0023     return;
-0024 else
-0025     toList=convertCharArray(toList);
-0026 end
-0027 if nargin<4
-0028     trimWarnings=true;
-0029 end
-0030 if numel(toList)>10 && trimWarnings==true
-0031     toList{10}=['...and ' num2str(numel(toList)-9) ' more'];
-0032     toList(11:end)=[];
-0033 end
-0034 if throwErrors==false
-0035     errorText=['WARNING: ' string '\n'];
-0036     % Wrap text to command window size
-0037     sz = get(0, 'CommandWindowSize');
-0038     errorText = textwrap({errorText},sz(1));
-0039     errorText = strjoin(errorText,'\n');
-0040 else
-0041     errorText=[string '\n'];
-0042 end
-0043 if ~isempty(toList)
-0044     for i=1:numel(toList)
-0045         errorText=[errorText '\t' toList{i} '\n'];
-0046     end
-0047 end
-0048 if throwErrors==false
-0049     %Escape special characters, required for fprintf
-0050     errorText=regexprep(errorText,'(\\|\%|'')(\\n)$','\\$0');
-0051     fprintf([errorText '\n']);
-0052 else
-0053     throw(MException('',errorText));
-0054 end
-0055 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/expandModel.html b/doc/core/expandModel.html deleted file mode 100644 index 6f4e866d8..000000000 --- a/doc/core/expandModel.html +++ /dev/null @@ -1,212 +0,0 @@ - - - - Description of expandModel - - - - - - - - - -
Home > core > expandModel.m
- - - -

expandModel -

- -

PURPOSE ^

-
expandModel
- -

SYNOPSIS ^

-
function [newModel, rxnToCheck]=expandModel(model)
- -

DESCRIPTION ^

-
 expandModel
-   Expands a model which uses several gene associations for one reaction.
-   Each such reaction is split into several reactions, each under the control
-   of only one gene.
-  
- Input:
-   model       model structure
- 
- Output:
-   newModel    model structure with separate reactions for iso-enzymes, where
-               the reaction ids are renamed as to id_EXP_1, id_EXP_2, etc. 
-   rxnToCheck  cell array with original reaction identifiers for those
-               that contained nested and/or-relationships in grRules.
-
-   NOTE: grRules strings that involve nested expressions of 'and' and 'or'
-         might not be parsed correctly if they are not standardized (if the
-         standardizeGrRules functions was not first run on the model). For
-         those reactions, it is therefore advisable to inspect the reactions in
-         rxnToCheck to confirm correct model expansion.
-
- Usage: [newModel, rxnToCheck]=expandModel(model)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function [newModel, rxnToCheck]=expandModel(model)
-0002 % expandModel
-0003 %   Expands a model which uses several gene associations for one reaction.
-0004 %   Each such reaction is split into several reactions, each under the control
-0005 %   of only one gene.
-0006 %
-0007 % Input:
-0008 %   model       model structure
-0009 %
-0010 % Output:
-0011 %   newModel    model structure with separate reactions for iso-enzymes, where
-0012 %               the reaction ids are renamed as to id_EXP_1, id_EXP_2, etc.
-0013 %   rxnToCheck  cell array with original reaction identifiers for those
-0014 %               that contained nested and/or-relationships in grRules.
-0015 %
-0016 %   NOTE: grRules strings that involve nested expressions of 'and' and 'or'
-0017 %         might not be parsed correctly if they are not standardized (if the
-0018 %         standardizeGrRules functions was not first run on the model). For
-0019 %         those reactions, it is therefore advisable to inspect the reactions in
-0020 %         rxnToCheck to confirm correct model expansion.
-0021 %
-0022 % Usage: [newModel, rxnToCheck]=expandModel(model)
-0023 
-0024 %Check how many reactions we will create (the number of or:s in the GPRs).
-0025 %This way, we can preallocate all fields and save much computation time
-0026 
-0027 numOrs = count(model.grRules, ' or ');
-0028 toAdd = sum(numOrs);
-0029 prevNumRxns = length(model.rxns);
-0030 rxnToCheck={};
-0031 if toAdd > 0
-0032     %Calculate indices to expand
-0033     %For example, if a reaction with index x has 2 or:s, meaning it has 3
-0034     %reactions after the split, we should add two copies of this reaction
-0035     %For fields that should just be copied to the new reactions, we just keep
-0036     %track of that there are two copies, i.e., we add x x to this vector.
-0037     %That is exactly what repelem does for us.
-0038     cpyIndices = repelem(1:prevNumRxns, numOrs);
-0039     
-0040     %Copy all fields that should just be copied
-0041     model.S=[model.S model.S(:,cpyIndices)];
-0042     model.rxnNames=[model.rxnNames;model.rxnNames(cpyIndices)];
-0043     model.lb=[model.lb;model.lb(cpyIndices)];
-0044     model.ub=[model.ub;model.ub(cpyIndices)];
-0045     model.rev=[model.rev;model.rev(cpyIndices)];
-0046     model.c=[model.c;model.c(cpyIndices)];
-0047     if isfield(model,'subSystems')
-0048         model.subSystems=[model.subSystems;model.subSystems(cpyIndices)];
-0049     end
-0050     if isfield(model,'eccodes')
-0051         model.eccodes=[model.eccodes;model.eccodes(cpyIndices)];
-0052     end
-0053     if isfield(model,'equations')
-0054         model.equations=[model.equations;model.equations(cpyIndices)];
-0055     end
-0056     if isfield(model,'rxnMiriams')
-0057         model.rxnMiriams=[model.rxnMiriams;model.rxnMiriams(cpyIndices)];
-0058     end
-0059     if isfield(model,'rxnComps')
-0060         model.rxnComps=[model.rxnComps;model.rxnComps(cpyIndices)];
-0061     end
-0062     if isfield(model,'rxnFrom')
-0063         model.rxnFrom=[model.rxnFrom;model.rxnFrom(cpyIndices)];
-0064     end
-0065     if isfield(model,'rxnNotes')
-0066         model.rxnNotes=[model.rxnNotes;model.rxnNotes(cpyIndices)];
-0067     end
-0068     if isfield(model,'rxnReferences')
-0069         model.rxnReferences=[model.rxnReferences;model.rxnReferences(cpyIndices)];
-0070     end
-0071     if isfield(model,'rxnConfidenceScores')
-0072         model.rxnConfidenceScores=[model.rxnConfidenceScores;model.rxnConfidenceScores(cpyIndices)];
-0073     end
-0074     if isfield(model,'rxnDeltaG')
-0075         model.rxnDeltaG=[model.rxnDeltaG;model.rxnDeltaG(cpyIndices)];
-0076     end
-0077     
-0078     %now expand the more complex fields - will be filled in later
-0079     model.rxns=[model.rxns;cell(toAdd,1)];
-0080     model.grRules=[model.grRules;cell(toAdd,1)];
-0081     model.rxnGeneMat=[model.rxnGeneMat;sparse(toAdd,size(model.rxnGeneMat,2))];
-0082     
-0083     %Loop throught those reactions and fill in the expanded data
-0084     nextIndex = prevNumRxns + 1;
-0085     for i=1:prevNumRxns
-0086         if (numOrs(i) > 0)
-0087             %Check that it doesn't contain nested 'and' and 'or' relations and
-0088             %print a warning if it does
-0089             if ~isempty(strfind(model.grRules{i},' and '))
-0090                 rxnToCheck{end+1,1}=model.rxns{i};
-0091             end
-0092 
-0093             %Get rid of all '(' and ')' since I'm not looking at complex stuff
-0094             %anyways
-0095             geneString=model.grRules{i};
-0096             geneString=strrep(geneString,'(','');
-0097             geneString=strrep(geneString,')','');
-0098             geneString=strrep(geneString,' or ',';');
-0099 
-0100             %Split the string into gene names
-0101             geneNames=regexp(geneString,';','split');
-0102 
-0103             %Update the reaction to only use the first gene
-0104             model.grRules{i}=['(' geneNames{1} ')'];
-0105             %Find the gene in the gene list If ' and ' relationship, first
-0106             %split the genes
-0107             model.rxnGeneMat(i,:)=0;
-0108             if ~isempty(strfind(geneNames(1),' and '))
-0109                 andGenes=regexp(geneNames{1},' and ','split');
-0110                 model.rxnGeneMat(i,ismember(model.genes,andGenes)) = 1;
-0111             else
-0112                 [~, index]=ismember(geneNames(1),model.genes);
-0113                 model.rxnGeneMat(i,index)=1;
-0114             end
-0115 
-0116             %Insert the reactions at the end of the model and without
-0117             %allocating space. This is not nice, but ok for now
-0118             for j=2:numel(geneNames)
-0119                 ind = nextIndex+j-2;
-0120                 model.rxns{ind}=[model.rxns{i} '_EXP_' num2str(j)];
-0121                 
-0122                 model.grRules{ind}=['(' geneNames{j} ')'];
-0123 
-0124                 if ~isempty(strfind(geneNames(j),' and '))
-0125                     andGenes=regexp(geneNames{j},' and ','split');
-0126                     model.rxnGeneMat(ind,ismember(model.genes,andGenes)) = 1;
-0127                 else
-0128                     model.rxnGeneMat(ind,ismember(model.genes,geneNames(j))) = 1;
-0129                 end
-0130             end
-0131             model.rxns{i}=[model.rxns{i}, '_EXP_1'];
-0132             nextIndex = nextIndex + numOrs(i);
-0133         end        
-0134     end
-0135     newModel=model;
-0136 else
-0137     %There are no reactions to expand, return the model as is
-0138     newModel=model;
-0139 end
-0140 
-0141 %Fix grRules and reconstruct rxnGeneMat
-0142 [grRules,rxnGeneMat] = standardizeGrRules(newModel,true);
-0143 newModel.grRules = grRules;
-0144 newModel.rxnGeneMat = rxnGeneMat;
-0145 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/fillGaps.html b/doc/core/fillGaps.html deleted file mode 100644 index ba68613ac..000000000 --- a/doc/core/fillGaps.html +++ /dev/null @@ -1,325 +0,0 @@ - - - - Description of fillGaps - - - - - - - - - -
Home > core > fillGaps.m
- - - -

fillGaps -

- -

PURPOSE ^

-
fillGaps
- -

SYNOPSIS ^

-
function [newConnected, cannotConnect, addedRxns, newModel, exitFlag]=fillGaps(model,models,allowNetProduction,useModelConstraints,supressWarnings,rxnScores)
- -

DESCRIPTION ^

-
 fillGaps
-   Uses template model(s) to fill gaps in a model
-
-   model               a model structure that may contains gaps to be filled
-   models              a cell array of reference models or a model structure.
-                       The gaps will be filled using reactions from these models
-   allowNetProduction  true if net production of all metabolites is
-                       allowed. A reaction can be unable to carry flux because one of
-                       the reactants is unavailable or because one of the
-                       products can't be further processed. If this
-                       parameter is true, only the first type of
-                       unconnectivity is considered (optional, default false)
-   useModelConstraints true if the constraints specified in the model
-                       structure should be used. If false then reactions
-                       included from the template model(s) so that as many
-                       reactions as possible in model can carry flux
-                       (optional, default false)
-   supressWarnings     false if warnings should be displayed (optional, default
-                       false)
-   rxnScores           array with scores for each of the reactions in the
-                       reference model(s). If more than one model is supplied,
-                       then rxnScores should be a cell array of vectors.
-                       The solver will try to maximize the sum of the
-                       scores for the included reactions (optional, default
-                       is -1 for all reactions)
-
-   newConnected        cell array with the reactions that could be
-                       connected. This is not calulated if
-                       useModelConstraints is true
-   cannotConnect       cell array with reactions that could not be
-                       connected. This is not calculated if
-                       useModelConstraints is true
-   addedRxns           cell array with the reactions that were added from
-                       "models"
-   newModel            the model with reactions added to fill gaps
-   exitFlag            1: optimal solution found
-                      -1: no feasible solution found
-                      -2: optimization time out
-
-   This method works by merging the model to the reference model(s) and
-   checking which reactions can carry flux. All reactions that can't
-   carry flux are removed (cannotConnect).
-   If useModelConstraints is false it then solves the MILP problem of
-   minimizing the number of active reactions from the reference models
-   that are required to have flux in all the reactions in model. This
-   requires that the input model has exchange reactions present for the
-   nutrients that are needed for its metabolism. If useModelConstraints is
-   true then the problem is to include as few reactions as possible from
-   the reference models in order to satisfy the model constraints.
-   The intended use is that the user can attempt a general gap-filling using
-   useModelConstraint=false or a more targeted gap-filling by setting
-   constraints in the model structure and then use
-   useModelConstraints=true. Say that the user want to include reactions
-   so that all biomass components can be synthesized. He/she could then
-   define a biomass equation and set the lower bound to >0. Running this
-   function with useModelConstraints=true would then give the smallest set
-   of reactions that have to be included in order for the model to produce
-   biomass.
-
- Usage: [newConnected, cannotConnect, addedRxns, newModel, exitFlag]=...
-           fillGaps(model,models,allowNetProduction,useModelConstraints,...
-           supressWarnings,rxnScores,params)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function [newConnected, cannotConnect, addedRxns, newModel, exitFlag]=fillGaps(model,models,allowNetProduction,useModelConstraints,supressWarnings,rxnScores)
-0002 % fillGaps
-0003 %   Uses template model(s) to fill gaps in a model
-0004 %
-0005 %   model               a model structure that may contains gaps to be filled
-0006 %   models              a cell array of reference models or a model structure.
-0007 %                       The gaps will be filled using reactions from these models
-0008 %   allowNetProduction  true if net production of all metabolites is
-0009 %                       allowed. A reaction can be unable to carry flux because one of
-0010 %                       the reactants is unavailable or because one of the
-0011 %                       products can't be further processed. If this
-0012 %                       parameter is true, only the first type of
-0013 %                       unconnectivity is considered (optional, default false)
-0014 %   useModelConstraints true if the constraints specified in the model
-0015 %                       structure should be used. If false then reactions
-0016 %                       included from the template model(s) so that as many
-0017 %                       reactions as possible in model can carry flux
-0018 %                       (optional, default false)
-0019 %   supressWarnings     false if warnings should be displayed (optional, default
-0020 %                       false)
-0021 %   rxnScores           array with scores for each of the reactions in the
-0022 %                       reference model(s). If more than one model is supplied,
-0023 %                       then rxnScores should be a cell array of vectors.
-0024 %                       The solver will try to maximize the sum of the
-0025 %                       scores for the included reactions (optional, default
-0026 %                       is -1 for all reactions)
-0027 %
-0028 %   newConnected        cell array with the reactions that could be
-0029 %                       connected. This is not calulated if
-0030 %                       useModelConstraints is true
-0031 %   cannotConnect       cell array with reactions that could not be
-0032 %                       connected. This is not calculated if
-0033 %                       useModelConstraints is true
-0034 %   addedRxns           cell array with the reactions that were added from
-0035 %                       "models"
-0036 %   newModel            the model with reactions added to fill gaps
-0037 %   exitFlag            1: optimal solution found
-0038 %                      -1: no feasible solution found
-0039 %                      -2: optimization time out
-0040 %
-0041 %   This method works by merging the model to the reference model(s) and
-0042 %   checking which reactions can carry flux. All reactions that can't
-0043 %   carry flux are removed (cannotConnect).
-0044 %   If useModelConstraints is false it then solves the MILP problem of
-0045 %   minimizing the number of active reactions from the reference models
-0046 %   that are required to have flux in all the reactions in model. This
-0047 %   requires that the input model has exchange reactions present for the
-0048 %   nutrients that are needed for its metabolism. If useModelConstraints is
-0049 %   true then the problem is to include as few reactions as possible from
-0050 %   the reference models in order to satisfy the model constraints.
-0051 %   The intended use is that the user can attempt a general gap-filling using
-0052 %   useModelConstraint=false or a more targeted gap-filling by setting
-0053 %   constraints in the model structure and then use
-0054 %   useModelConstraints=true. Say that the user want to include reactions
-0055 %   so that all biomass components can be synthesized. He/she could then
-0056 %   define a biomass equation and set the lower bound to >0. Running this
-0057 %   function with useModelConstraints=true would then give the smallest set
-0058 %   of reactions that have to be included in order for the model to produce
-0059 %   biomass.
-0060 %
-0061 % Usage: [newConnected, cannotConnect, addedRxns, newModel, exitFlag]=...
-0062 %           fillGaps(model,models,allowNetProduction,useModelConstraints,...
-0063 %           supressWarnings,rxnScores,params)
-0064 
-0065 %If the user only supplied a single template model
-0066 if ~iscell(models)
-0067     models={models};
-0068 end
-0069 
-0070 if nargin<3
-0071     allowNetProduction=false;
-0072 end
-0073 if nargin<4
-0074     useModelConstraints=false;
-0075 end
-0076 if nargin<5
-0077     supressWarnings=false;
-0078 end
-0079 if nargin<6
-0080     rxnScores=cell(numel(models),1);
-0081     for i=1:numel(models)
-0082         rxnScores{i}=ones(numel(models{i}.rxns),1)*-1;
-0083     end
-0084 end
-0085 if isempty(rxnScores)
-0086     rxnScores=cell(numel(models),1);
-0087     for i=1:numel(models)
-0088         rxnScores{i}=ones(numel(models{i}.rxns),1)*-1;
-0089     end
-0090 end
-0091 if nargin<7
-0092     params=struct();
-0093 end
-0094 
-0095 if ~iscell(rxnScores)
-0096     rxnScores={rxnScores};
-0097 end
-0098 
-0099 models=models(:);
-0100 rxnScores=rxnScores(:);
-0101 
-0102 %Check if the original model has an unconstrained field. If so, give a
-0103 %warning
-0104 if supressWarnings==false
-0105     if isfield(model,'unconstrained')
-0106         EM='This algorithm is meant to function on a model with exchange reactions for uptake and excretion of metabolites. The current model still has the "unconstrained" field';
-0107         dispEM(EM,false);
-0108     else
-0109         if isempty(getExchangeRxns(model,'both'))
-0110             fprintf('NOTE: This algorithm is meant to function on a model with exchange reactions for uptake and excretion of metabolites. The current model does not seem to contain any such reactions.\n');
-0111         end
-0112     end
-0113 end
-0114 
-0115 %Simplify the template models to remove constrained rxns. At the same time,
-0116 %check that the id of the template models isn't the same as the model. That
-0117 %would cause an error further down
-0118 for i=1:numel(models)
-0119     models{i}.rxnScores=rxnScores{i};
-0120     models{i}=simplifyModel(models{i},false,false,true);
-0121     if strcmpi(models{i}.id,model.id)
-0122         EM='The reference model(s) cannot have the same id as the model';
-0123         dispEM(EM);
-0124     end
-0125 end
-0126 
-0127 %This is a rather ugly solution to the issue that it's a bit tricky to keep
-0128 %track of which scores belong to which reactions. This requires that
-0129 %removeReactions and mergeModels are modified to check for the new field.
-0130 model.rxnScores=zeros(numel(model.rxns),1);
-0131 
-0132 %First merge all models into one big one
-0133 allModels=mergeModels([{model};models],'metNames',true);
-0134 
-0135 %Add that net production is ok
-0136 if allowNetProduction==true
-0137     %A second column in model.b means that the b field is lower and upper
-0138     %bound on the RHS.
-0139     model.b=[model.b(:,1) inf(numel(model.mets),1)];
-0140     allModels.b=[allModels.b(:,1) inf(numel(allModels.mets),1)];
-0141 end
-0142 
-0143 if useModelConstraints==true
-0144     newConnected={};
-0145     cannotConnect={};
-0146     
-0147     %Check that the input model isn't solveable without any input
-0148     sol=solveLP(model);
-0149     if ~isempty(sol.f)
-0150         addedRxns={};
-0151         newModel=model;
-0152         exitFlag=1;
-0153         return;
-0154     end
-0155     
-0156     %Then check that the merged model is solveable
-0157     sol=solveLP(allModels);
-0158     if isempty(sol.f)
-0159         EM='There are no reactions in the template model(s) that can make the model constraints satisfied';
-0160         dispEM(EM);
-0161     end
-0162     
-0163     %Remove dead ends for speed reasons. This has to be done here and
-0164     %duplicate below because there is otherwise a risk that a reaction
-0165     %which is constrained to something relevant is removed
-0166     allModels=simplifyModel(allModels,false,false,false,true,false,false,false,[],true);
-0167     allModels.c(:)=0;
-0168 else
-0169     %Remove dead ends for speed reasons
-0170     allModels=simplifyModel(allModels,false,false,false,true,false,false,false,[],true);
-0171     allModels.c(:)=0;
-0172     
-0173     %If model constraints shouldn't be used, then determine which reactions
-0174     %to force to have flux
-0175     
-0176     %Get the reactions that can carry flux in the original model
-0177     originalFlux=haveFlux(model,1);
-0178     
-0179     %For the ones that can't carry flux, see if they can do so in the
-0180     %merged model
-0181     toCheck=intersect(allModels.rxns(strcmp(allModels.rxnFrom,model.id)),model.rxns(~originalFlux));
-0182     
-0183     %Get the ones that still cannot carry flux
-0184     I=haveFlux(allModels,1,toCheck);
-0185     
-0186     %Get the reactions that can't carry flux in the original model, but can
-0187     %in the merged one
-0188     K=toCheck(I);
-0189     
-0190     %This is a temporary thing to only look at the non-reversible rxns.
-0191     %This is because all reversible rxns can have a flux in the
-0192     %irreversible model format that is used by getMinNrFluxes
-0193     [~, I]=ismember(K,model.rxns);
-0194     K(model.rev(I)~=0)=[];
-0195     
-0196     %Constrain all reactions in the original model to have a flux
-0197     allModels.lb(ismember(allModels.rxns,K))=0.1;
-0198     
-0199     %Return stuff
-0200     newConnected=K;
-0201     cannotConnect=setdiff(model.rxns(~originalFlux),newConnected);
-0202 end
-0203 
-0204 %Then minimize for the number of fluxes used. The fixed rxns doesn't need
-0205 %to participate
-0206 templateRxns=find(~strcmp(allModels.rxnFrom,model.id));
-0207 [~, J, exitFlag]=getMinNrFluxes(allModels,templateRxns,params,allModels.rxnScores(templateRxns));
-0208 
-0209 %Remove everything except for the added ones
-0210 I=true(numel(allModels.rxns),1);
-0211 I(templateRxns(J))=false;
-0212 addedModel=removeReactions(allModels,I,true,true,true);
-0213 
-0214 newModel=mergeModels({model;addedModel},'metNames',true);
-0215 addedRxns=setdiff(newModel.rxns,model.rxns);
-0216 newModel=rmfield(newModel,'rxnScores');
-0217 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/findGeneDeletions.html b/doc/core/findGeneDeletions.html deleted file mode 100644 index cb115c6ea..000000000 --- a/doc/core/findGeneDeletions.html +++ /dev/null @@ -1,293 +0,0 @@ - - - - Description of findGeneDeletions - - - - - - - - - -
Home > core > findGeneDeletions.m
- - - -

findGeneDeletions -

- -

PURPOSE ^

-
findGeneDeletions
- -

SYNOPSIS ^

-
function [genes, fluxes, originalGenes, details, grRatioMuts]=findGeneDeletions(model,testType,analysisType,refModel,oeFactor)
- -

DESCRIPTION ^

-
 findGeneDeletions
-   Deletes genes, optimizes the model, and keeps track of the resulting
-   fluxes. This is used for identifying gene deletion targets.
-
-   model           a model structure
-   testType        single/double gene deletions/over expressions. Over
-                   expression only available if using MOMA
-                   'sgd'   single gene deletion
-                   'dgd'   double gene deletion
-                   'sgo'   single gene over expression
-                   'dgo'   double gene over expression
-                   (optional, default 'sgd')
-   analysisType    determines whether to use FBA ('fba') or MOMA ('moma')
-                   in the optimization. (optional, default 'fba')
-   refModel        MOMA works by fitting the flux distributions of two
-                   models to be as similar as possible. The most common
-                   application is where you have a reference model where
-                   some of the fluxes are constrained from experimental
-                   data. This model is required when using MOMA
-   oeFactor        a factor by which the fluxes should be increased if a
-                   gene is overexpressed (optional, default 10)
-
-   genes           a matrix with the genes that were deleted in each
-                   optimization (the gene indexes in originalGenes). Each
-                   row corresponds to a column in fluxes
-   fluxes          a matrix with the resulting fluxes. Double deletions
-                   that result in an unsolvable problem have all zero
-                   flux. Single deletions that result in an unsolvable
-                   problem are indicated in details instead
-   originalGenes   simply the genes in the input model. Included for
-                   simple presentation of the output
-   details         not all genes will be deleted in all analyses. It is
-                   for example not necessary to delete genes for dead end
-                   reactions. This is a vector with details about
-                   each gene in originalGenes and why or why not it was
-                   deleted
-                   1: Was deleted/overexpressed
-                   2: Proved lethal in sgd (single gene deletion)
-                   3: - redundant, no longer used -
-                   4: Involved in dead-end reaction
-   grRatioMuts     growth rate ratio between mutated strain and wild type,
-                   matches the originalGenes(genes) mutants. Note that
-                   this does not directly map to model.genes, as is the case
-                   for COBRA getEssentialGenes. However, this can be 
-                   obtained by afterwards running:
-                       grRatio=zeros(1,numel(model.genes));
-                       grRatio(genes)=grRatioMuts;
-
- Usage: [genes, fluxes, originalGenes, details, grRatioMuts]=findGeneDeletions(model,testType,analysisType,...
-           refModel,oeFactor)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function [genes, fluxes, originalGenes, details, grRatioMuts]=findGeneDeletions(model,testType,analysisType,refModel,oeFactor)
-0002 % findGeneDeletions
-0003 %   Deletes genes, optimizes the model, and keeps track of the resulting
-0004 %   fluxes. This is used for identifying gene deletion targets.
-0005 %
-0006 %   model           a model structure
-0007 %   testType        single/double gene deletions/over expressions. Over
-0008 %                   expression only available if using MOMA
-0009 %                   'sgd'   single gene deletion
-0010 %                   'dgd'   double gene deletion
-0011 %                   'sgo'   single gene over expression
-0012 %                   'dgo'   double gene over expression
-0013 %                   (optional, default 'sgd')
-0014 %   analysisType    determines whether to use FBA ('fba') or MOMA ('moma')
-0015 %                   in the optimization. (optional, default 'fba')
-0016 %   refModel        MOMA works by fitting the flux distributions of two
-0017 %                   models to be as similar as possible. The most common
-0018 %                   application is where you have a reference model where
-0019 %                   some of the fluxes are constrained from experimental
-0020 %                   data. This model is required when using MOMA
-0021 %   oeFactor        a factor by which the fluxes should be increased if a
-0022 %                   gene is overexpressed (optional, default 10)
-0023 %
-0024 %   genes           a matrix with the genes that were deleted in each
-0025 %                   optimization (the gene indexes in originalGenes). Each
-0026 %                   row corresponds to a column in fluxes
-0027 %   fluxes          a matrix with the resulting fluxes. Double deletions
-0028 %                   that result in an unsolvable problem have all zero
-0029 %                   flux. Single deletions that result in an unsolvable
-0030 %                   problem are indicated in details instead
-0031 %   originalGenes   simply the genes in the input model. Included for
-0032 %                   simple presentation of the output
-0033 %   details         not all genes will be deleted in all analyses. It is
-0034 %                   for example not necessary to delete genes for dead end
-0035 %                   reactions. This is a vector with details about
-0036 %                   each gene in originalGenes and why or why not it was
-0037 %                   deleted
-0038 %                   1: Was deleted/overexpressed
-0039 %                   2: Proved lethal in sgd (single gene deletion)
-0040 %                   3: - redundant, no longer used -
-0041 %                   4: Involved in dead-end reaction
-0042 %   grRatioMuts     growth rate ratio between mutated strain and wild type,
-0043 %                   matches the originalGenes(genes) mutants. Note that
-0044 %                   this does not directly map to model.genes, as is the case
-0045 %                   for COBRA getEssentialGenes. However, this can be
-0046 %                   obtained by afterwards running:
-0047 %                       grRatio=zeros(1,numel(model.genes));
-0048 %                       grRatio(genes)=grRatioMuts;
-0049 %
-0050 % Usage: [genes, fluxes, originalGenes, details, grRatioMuts]=findGeneDeletions(model,testType,analysisType,...
-0051 %           refModel,oeFactor)
-0052 
-0053 originalModel=model;
-0054 if nargin<5
-0055     oeFactor=10;
-0056 end
-0057 if nargin<2
-0058     testType='sgd';
-0059 else
-0060     testType=char(testType);
-0061 end
-0062 
-0063 %Check that the test type is correct
-0064 if ~strcmpi(testType,'sgd') && ~strcmpi(testType,'dgd') && ~strcmpi(testType,'sgo') && ~strcmpi(testType,'dgo')
-0065     EM='Incorrect test type';
-0066     dispEM(EM);
-0067 end
-0068 
-0069 %Check that the analysis type is correct
-0070 if nargin<3
-0071     analysisType = 'fba';
-0072 else
-0073     analysisType=char(analysisType);
-0074     if ~any(strcmpi(analysisType,{'fba','moma'}))
-0075         EM='Incorrect analysis type';
-0076         dispEM(EM);
-0077     end
-0078 end
-0079 
-0080 if (strcmpi(testType,'sgo') || strcmpi(testType,'dgo')) && strcmpi(analysisType,'fba')
-0081     EM='Over expression is only available when using MOMA';
-0082     dispEM(EM);
-0083 end
-0084 
-0085 if strcmpi(analysisType,'moma') && nargin<4
-0086     EM='A reference model must be supplied when using MOMA';
-0087     dispEM(EM);
-0088 end
-0089 
-0090 originalGenes=model.genes;
-0091 details=zeros(numel(model.genes),1);
-0092 
-0093 %First simplify the model to reduce the size
-0094 model=simplifyModel(model,true,false,true,true);
-0095 model=removeReactions(model,{},true,true); %Removes unused genes
-0096 details(~ismember(originalGenes,model.genes))=4;
-0097 
-0098 [~, geneMapping]=ismember(model.genes,originalGenes);
-0099 growthWT=solveLP(model);
-0100 growthWT=growthWT.f;
-0101 
-0102 %Do single deletion/over expression. This is done here since the double
-0103 %deletion depends on which single deletions prove lethal (to reduce the
-0104 %size of the system)
-0105 if strcmpi(testType,'sgd') || strcmpi(testType,'sgo') || strcmpi(testType,'dgd')
-0106     fluxes=zeros(numel(model.rxns),numel(model.genes));
-0107     grRatioMuts=zeros(1,numel(model.genes));
-0108     for i=1:numel(model.genes)
-0109         if strcmpi(testType,'sgd') || strcmpi(testType,'dgd')
-0110             %Constrain all reactions involving the gene to 0
-0111             tempModel=removeGenes(model,i,false,false,false);
-0112         else
-0113             %To over express a gene, the stoichiometry of the corresponding
-0114             %reactions are changed so that the same flux leads to a higher
-0115             %production
-0116             tempModel=model;
-0117             I=find(model.rxnGeneMat(:,i));
-0118             tempModel.S(:,I)=tempModel.S(:,I).*oeFactor;
-0119         end
-0120         if strcmpi(analysisType,'fba') || strcmpi(testType,'dgd')
-0121             sol=solveLP(tempModel);
-0122         else
-0123             [fluxA, ~, flag]=qMOMA(tempModel,refModel);
-0124             sol.x=fluxA;
-0125             sol.stat=flag;
-0126         end
-0127         
-0128         %If the optimization terminated successfully
-0129         if sol.stat==1
-0130             fluxes(:,i)=sol.x;
-0131             grRatioMuts(i)=sol.f/growthWT;
-0132             details(geneMapping(i))=1;
-0133         else
-0134             fluxes(:,i)=0;
-0135             grRatioMuts(i)=0;
-0136             details(geneMapping(i))=2;
-0137         end
-0138     end
-0139     genes=geneMapping;
-0140 end
-0141 
-0142 %Now do for DGO. This is rather straight forward since it is always
-0143 %solvable and it doesn't matter if there are iso-enzymes
-0144 if strcmpi(testType,'dgo')
-0145     genesToModify=nchoosek(1:numel(model.genes),2);
-0146     genes=geneMapping(genesToModify);
-0147     %Since I assume that this is never lethal I set the details already
-0148     details(geneMapping)=1;
-0149     
-0150     fluxes=sparse(numel(model.rxns),size(genesToModify,1));
-0151     for i=1:size(genesToModify,1)
-0152         I=find(model.rxnGeneMat(:,genesToModify(i,:)));
-0153         %To over express a gene, the stoichiometry of the corresponding
-0154         %reactions are changed so that the same flux leads to a higher
-0155         %production
-0156         tempModel=model;
-0157         tempModel.S(:,I)=tempModel.S(:,I).*oeFactor;
-0158         fluxA=qMOMA(tempModel,refModel);
-0159         fluxes(:,i)=fluxA;
-0160         grRatioMuts(i)=fluxA(logical(model.c))/growthWT;
-0161     end
-0162 end
-0163 
-0164 %For double deletions FBA or MOMA
-0165 if strcmpi(testType,'dgd')
-0166     %This is a little lazy but it's fine. Check which genes have already
-0167     %been deleted in 'sgd' analysis.
-0168     [~, I]=ismember(originalGenes(details==1),model.genes);
-0169     genesToModify=nchoosek(I,2);
-0170     genes=geneMapping(genesToModify);
-0171     grRatioMuts=zeros(1,numel(genes));
-0172     fluxes=sparse(numel(model.rxns),size(genesToModify,1));
-0173     for i=1:size(genesToModify,1)
-0174         tempModel=removeGenes(model,genesToModify(i,:),false,false,false);
-0175         
-0176         if strcmpi(analysisType,'fba')
-0177             sol=solveLP(tempModel);
-0178         else
-0179             [fluxA, ~, flag]=qMOMA(tempModel,refModel);
-0180             sol.x=fluxA;
-0181             sol.stat=flag;
-0182         end
-0183         
-0184         if sol.stat==1
-0185             fluxes(:,i)=sol.x;
-0186             grRatioMuts(i)=sol.f/growthWT;
-0187         end
-0188     end
-0189 end
-0190 
-0191 %Map back to the old model
-0192 [~, I]=ismember(model.rxns,originalModel.rxns);
-0193 temp=fluxes;
-0194 fluxes=sparse(numel(originalModel.rxns),size(temp,2));
-0195 fluxes(I,:)=temp;
-0196 end
-0197
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/findRAVENroot.html b/doc/core/findRAVENroot.html deleted file mode 100644 index df783a87b..000000000 --- a/doc/core/findRAVENroot.html +++ /dev/null @@ -1,78 +0,0 @@ - - - - Description of findRAVENroot - - - - - - - - - -
Home > core > findRAVENroot.m
- - - -

findRAVENroot -

- -

PURPOSE ^

-
findRAVENroot
- -

SYNOPSIS ^

-
function [ravenPath, prevDir] = findRAVENroot()
- -

DESCRIPTION ^

-
 findRAVENroot
-   Finds the root of the RAVEN directory, first by  by searching for the path to
-   RAVEN2.png. Can also record the current directory, in case a function will
-   use the ravenPath to navigate to a precise folder, and it should return to
-   the previous directory afterwards. See e.g. optimizeProb calling glpk.
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function [ravenPath, prevDir] = findRAVENroot()
-0002 % findRAVENroot
-0003 %   Finds the root of the RAVEN directory, first by  by searching for the path to
-0004 %   RAVEN2.png. Can also record the current directory, in case a function will
-0005 %   use the ravenPath to navigate to a precise folder, and it should return to
-0006 %   the previous directory afterwards. See e.g. optimizeProb calling glpk.
-0007 
-0008 ST=dbstack('-completenames');
-0009 prevDir = pwd();
-0010 if ispref('RAVEN','ravenPath')
-0011     ravenPath = getpref('RAVEN','ravenPath');
-0012 else
-0013     ravenPath = ST(strcmp({ST.name},'findRAVENroot')).file;
-0014     rootFound = 0;
-0015     while rootFound == 0
-0016         isRoot = isfile(fullfile(ravenPath,'RAVEN2.png'));
-0017         if isRoot
-0018             rootFound = 1;
-0019         else
-0020             ravenPathOld = ravenPath;
-0021             ravenPath = fileparts(ravenPath);
-0022             if strcmp(ravenPathOld,ravenPath)
-0023                 error('Cannot find the RAVEN root directory. Make sure you have not removed the RAVEN2.png file from your RAVEN installation.')
-0024             end
-0025         end
-0026     end
-0027 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/fitParameters.html b/doc/core/fitParameters.html deleted file mode 100644 index 6e19da4ba..000000000 --- a/doc/core/fitParameters.html +++ /dev/null @@ -1,199 +0,0 @@ - - - - Description of fitParameters - - - - - - - - - -
Home > core > fitParameters.m
- - - -

fitParameters -

- -

PURPOSE ^

-
fitParameters
- -

SYNOPSIS ^

-
function [parameters, fitnessScore, exitFlag, newModel]=fitParameters(model,xRxns,xValues,rxnsToFit,valuesToFit,parameterPositions,fitToRatio,initialGuess,plotFitting)
- -

DESCRIPTION ^

-
 fitParameters
-   Fits parameters such as maintenance ATP by quadratic programming
-
-   model                 a model structure
-   xRxns                 cell array with the IDs of the reactions that will be
-                         fixed for each data point
-   xValues               matrix with the corresponding values for each
-                         xRxns (columns are reactions)
-   rxnsToFit             cell array with the IDs of reactions that will be fitted to
-   valuesToFit           matrix with the corresponding values for each
-                         rxnsToFit (columns are reactions)
-   parameterPositions    stucture that determines where the parameters are in the
-                         stoichiometric matrix. Contains the fields:
-       position          cell array of vectors where each element contains
-                         the positions in the S-matrix for that parameter
-       isNegative        cell array of vectors where the elements are true
-                         if that position should be the negative of the
-                         fitted value (to differentiate between
-                         production/consumption)
-    fitToRatio            if the ratio of simulated to measured values should
-                         be fitted instead of the absolute value. Used to prevent
-                         large fluxes from having too large impact (optional,
-                         default true)
-   initialGuess          initial guess of the parameters (optional)
-   plotFitting           true if the resulting fitting should be plotted
-                         (optional, default false)
-
-   parameters            fitted parameters in the same order as in
-                         parameterPositions
-   fitnessScore          the correponding residual sum of squares
-   newModel              updated model structure with the fitted parameters
-
- Usage: [parameters, fitnessScore, exitFlag, newModel]=fitParameters(model,...
-           xRxns,xValues,rxnsToFit,valuesToFit,parameterPositions,fitToRatio,...
-           initialGuess,plotFitting)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 function [parameters, fitnessScore, exitFlag, newModel]=fitParameters(model,xRxns,xValues,rxnsToFit,valuesToFit,parameterPositions,fitToRatio,initialGuess,plotFitting)
-0002 % fitParameters
-0003 %   Fits parameters such as maintenance ATP by quadratic programming
-0004 %
-0005 %   model                 a model structure
-0006 %   xRxns                 cell array with the IDs of the reactions that will be
-0007 %                         fixed for each data point
-0008 %   xValues               matrix with the corresponding values for each
-0009 %                         xRxns (columns are reactions)
-0010 %   rxnsToFit             cell array with the IDs of reactions that will be fitted to
-0011 %   valuesToFit           matrix with the corresponding values for each
-0012 %                         rxnsToFit (columns are reactions)
-0013 %   parameterPositions    stucture that determines where the parameters are in the
-0014 %                         stoichiometric matrix. Contains the fields:
-0015 %       position          cell array of vectors where each element contains
-0016 %                         the positions in the S-matrix for that parameter
-0017 %       isNegative        cell array of vectors where the elements are true
-0018 %                         if that position should be the negative of the
-0019 %                         fitted value (to differentiate between
-0020 %                         production/consumption)
-0021 %    fitToRatio            if the ratio of simulated to measured values should
-0022 %                         be fitted instead of the absolute value. Used to prevent
-0023 %                         large fluxes from having too large impact (optional,
-0024 %                         default true)
-0025 %   initialGuess          initial guess of the parameters (optional)
-0026 %   plotFitting           true if the resulting fitting should be plotted
-0027 %                         (optional, default false)
-0028 %
-0029 %   parameters            fitted parameters in the same order as in
-0030 %                         parameterPositions
-0031 %   fitnessScore          the correponding residual sum of squares
-0032 %   newModel              updated model structure with the fitted parameters
-0033 %
-0034 % Usage: [parameters, fitnessScore, exitFlag, newModel]=fitParameters(model,...
-0035 %           xRxns,xValues,rxnsToFit,valuesToFit,parameterPositions,fitToRatio,...
-0036 %           initialGuess,plotFitting)
-0037 
-0038 if nargin<7
-0039     fitToRatio=true;
-0040 end
-0041 if nargin<8
-0042     initialGuess=ones(numel(parameterPositions.position),1);
-0043 end
-0044 if isempty(initialGuess)
-0045     initialGuess=ones(numel(parameterPositions.position),1);
-0046 end
-0047 if nargin<9
-0048     plotFitting=false;
-0049 end
-0050 
-0051 xRxns=convertCharArray(xRxns);
-0052 rxnsToFit=convertCharArray(rxnsToFit);
-0053 
-0054 %Find the indexes of reactions that will be fitted
-0055 [I, rxnsToFitIndexes]=ismember(rxnsToFit,model.rxns);
-0056 
-0057 if ~all(I)
-0058     EM='Could not find all reactions in rxnsToFit';
-0059     dispEM(EM);
-0060 end
-0061 
-0062 %Find the indexes of reactions that will be used for constraints.
-0063 [I, xRxnsIndexes]=ismember(xRxns,model.rxns);
-0064 
-0065 if ~all(I)
-0066     EM='Could not find all reactions in xRxns';
-0067     dispEM(EM);
-0068 end
-0069 
-0070 [parameters, fitnessScore, exitFlag]=fminsearch(@(parameters) getRSS(parameters,model,xRxnsIndexes,xValues,rxnsToFitIndexes,valuesToFit,parameterPositions,fitToRatio),initialGuess);
-0071 
-0072 parameters=abs(parameters);
-0073 
-0074 if plotFitting==true
-0075     %Set the resulting parameters
-0076     [~, resultingFluxes, newModel]=getRSS(parameters,model,xRxnsIndexes,xValues,rxnsToFitIndexes,valuesToFit,parameterPositions,true);
-0077     plot(xValues,valuesToFit,'o',xValues,resultingFluxes,'-*');
-0078 end
-0079 end
-0080 
-0081 function [rss, resultingFluxes, newModel]=getRSS(parameters,model,xRxnsIndexes,xValues,rxnsToFitIndexes,valuesToFit,parameterPositions,fitToRatio)
-0082 parameters=abs(parameters);
-0083 
-0084 %Set the parameters at the positions specified in parameterPositions
-0085 for i=1:numel(parameterPositions.position)
-0086     %Set positive
-0087     model.S(parameterPositions.position{i}(parameterPositions.isNegative{i}==false))=parameters(i);
-0088     
-0089     %Set negative
-0090     model.S(parameterPositions.position{i}(parameterPositions.isNegative{i}==true))=parameters(i)*-1;
-0091 end
-0092 
-0093 %Also return an updated model
-0094 newModel=model;
-0095 
-0096 %Loop through each data point, set xRxns to xValues and calculate the sum
-0097 %of squares for the rxnsToFit
-0098 rss=0;
-0099 resultingFluxes=[];
-0100 for i=1:size(xValues,1)
-0101     %Fix for more xRxns!
-0102     model.lb(xRxnsIndexes)=xValues(i,:);
-0103     model.ub(xRxnsIndexes)=xValues(i);
-0104     
-0105     sol=solveLP(model);
-0106     
-0107     %Calculate the rss
-0108     if fitToRatio==false
-0109         rs=sol.x(rxnsToFitIndexes)'-valuesToFit(i,:);
-0110     else
-0111         rs=sol.x(rxnsToFitIndexes)'./valuesToFit(i,:)-ones(1,size(valuesToFit,2));
-0112     end
-0113     rss=rss+rs*rs';
-0114     resultingFluxes=[resultingFluxes sol.x(rxnsToFitIndexes)];
-0115 end
-0116 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/fitTasks.html b/doc/core/fitTasks.html deleted file mode 100644 index 03cc88954..000000000 --- a/doc/core/fitTasks.html +++ /dev/null @@ -1,409 +0,0 @@ - - - - Description of fitTasks - - - - - - - - - -
Home > core > fitTasks.m
- - - -

fitTasks -

- -

PURPOSE ^

-
fitTasks
- -

SYNOPSIS ^

-
function [outModel, addedRxns]=fitTasks(model,refModel,inputFile,printOutput,rxnScores,taskStructure)
- -

DESCRIPTION ^

-
 fitTasks
-   Fills gaps in a model by including reactions from a reference model,
-   so that the resulting model can perform all the tasks in a task list
-
-   Input:
-   model           model structure
-   refModel        reference model from which to include reactions
-   inputFile       a task list in Excel format. See the function
-                   parseTaskList for details (optional if taskStructure is
-                   supplied)
-   printOutput     true if the results of the test should be displayed
-                   (optional, default true)
-   rxnScores       scores for each of the reactions in the reference
-                   model. Only negative scores are allowed. The solver will
-                   try to maximize the sum of the scores for the included
-                   reactions (optional, default is -1 for all reactions)
-   taskStructure   structure with the tasks, as from parseTaskList. If
-                   this is supplied then inputFile is ignored (optional)
-
-
-   Output:
-   outModel        model structure with reactions added to perform the
-                   tasks
-   addedRxns       MxN matrix with the added reactions (M) from refModel
-                   for each task (N). An element is true if the corresponding
-                   reaction is added in the corresponding task.
-                   Failed tasks and SHOULD FAIL tasks are ignored
-
-   This function fills gaps in a model by using a reference model, so
-   that the resulting model can perform a list of metabolic tasks. The
-   gap-filling is done in a task-by-task manner, rather than solving for
-   all tasks at once. This means that the order of the tasks could influence
-   the result.
-
- Usage: [outModel, addedRxns]=fitTasks(model,refModel,inputFile,printOutput,...
-           rxnScores,taskStructure)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function [outModel, addedRxns]=fitTasks(model,refModel,inputFile,printOutput,rxnScores,taskStructure)
-0002 % fitTasks
-0003 %   Fills gaps in a model by including reactions from a reference model,
-0004 %   so that the resulting model can perform all the tasks in a task list
-0005 %
-0006 %   Input:
-0007 %   model           model structure
-0008 %   refModel        reference model from which to include reactions
-0009 %   inputFile       a task list in Excel format. See the function
-0010 %                   parseTaskList for details (optional if taskStructure is
-0011 %                   supplied)
-0012 %   printOutput     true if the results of the test should be displayed
-0013 %                   (optional, default true)
-0014 %   rxnScores       scores for each of the reactions in the reference
-0015 %                   model. Only negative scores are allowed. The solver will
-0016 %                   try to maximize the sum of the scores for the included
-0017 %                   reactions (optional, default is -1 for all reactions)
-0018 %   taskStructure   structure with the tasks, as from parseTaskList. If
-0019 %                   this is supplied then inputFile is ignored (optional)
-0020 %
-0021 %
-0022 %   Output:
-0023 %   outModel        model structure with reactions added to perform the
-0024 %                   tasks
-0025 %   addedRxns       MxN matrix with the added reactions (M) from refModel
-0026 %                   for each task (N). An element is true if the corresponding
-0027 %                   reaction is added in the corresponding task.
-0028 %                   Failed tasks and SHOULD FAIL tasks are ignored
-0029 %
-0030 %   This function fills gaps in a model by using a reference model, so
-0031 %   that the resulting model can perform a list of metabolic tasks. The
-0032 %   gap-filling is done in a task-by-task manner, rather than solving for
-0033 %   all tasks at once. This means that the order of the tasks could influence
-0034 %   the result.
-0035 %
-0036 % Usage: [outModel, addedRxns]=fitTasks(model,refModel,inputFile,printOutput,...
-0037 %           rxnScores,taskStructure)
-0038 
-0039 if nargin<4
-0040     printOutput=true;
-0041 end
-0042 if nargin<5
-0043     rxnScores=ones(numel(refModel.rxns),1)*-1;
-0044 end
-0045 if isempty(rxnScores)
-0046     rxnScores=ones(numel(refModel.rxns),1)*-1;
-0047 end
-0048 if nargin<6
-0049     taskStructure=[];
-0050 end
-0051 
-0052 if isempty(taskStructure) && ~isfile(inputFile)
-0053     error('Task file %s cannot be found',string(inputFile));
-0054 end
-0055 
-0056 if strcmpi(model.id,refModel.id)
-0057     fprintf('NOTE: The model and reference model have the same IDs. The ID for the reference model was set to "refModel" in order to keep track of the origin of reactions.\n');
-0058     refModel.id='refModel';
-0059 end
-0060 
-0061 if any(rxnScores>=0)
-0062     EM='Only negative values are allowed in rxnScores';
-0063     dispEM(EM);
-0064 end
-0065 
-0066 %Prepare the input models a little
-0067 model.b=zeros(numel(model.mets),2);
-0068 modelMets=upper(strcat(model.metNames,'[',model.comps(model.metComps),']'));
-0069 %This is the mets in the reference model. Used if the tasks involve
-0070 %metabolites that doesn't exist in the model
-0071 largeModelMets=upper(strcat(refModel.metNames,'[',refModel.comps(refModel.metComps),']'));
-0072 
-0073 if ~isfield(model,'unconstrained')
-0074     EM='Exchange metabolites should normally not be removed from the model when using checkTasks. Inputs and outputs are defined in the task file instead. Use importModel(file,false) to import a model with exchange metabolites remaining';
-0075     dispEM(EM,false);
-0076 end
-0077 
-0078 if isempty(taskStructure)
-0079     taskStructure=parseTaskList(inputFile);
-0080 end
-0081 
-0082 tModel=model;
-0083 addedRxns=false(numel(refModel.rxns),numel(taskStructure));
-0084 supressWarnings=false;
-0085 nAdded=0;
-0086 for i=1:numel(taskStructure)
-0087     if ~taskStructure(i).shouldFail
-0088         %Set the inputs
-0089         if ~isempty(taskStructure(i).inputs)
-0090             [I, J]=ismember(upper(taskStructure(i).inputs),modelMets);
-0091             K=ismember(upper(taskStructure(i).inputs),'ALLMETS');
-0092             L=~cellfun('isempty',strfind(upper(taskStructure(i).inputs),'ALLMETSIN'));
-0093             %Check that all metabolites are either real metabolites or
-0094             %ALLMETS/ALLMETSIN
-0095             goodMets=I|K|L;
-0096             if ~all(goodMets)
-0097                 %Not all of the inputs could be found in the small model.
-0098                 %Check if they exist in the large model
-0099                 [found, metMatch]=ismember(upper(taskStructure(i).inputs(~goodMets)),largeModelMets);
-0100                 if ~all(found)
-0101                     EM=['Could not find all inputs in "[' taskStructure(i).id '] ' taskStructure(i).description '" in either model'];
-0102                     disp(EM);
-0103                 else
-0104                     %Otherwise add them to the model
-0105                     met.metNames=refModel.metNames(metMatch);
-0106                     met.compartments=refModel.comps(refModel.metComps(metMatch));
-0107                     
-0108                     %Add the metabolite both to the base model and the
-0109                     %model used in the current task
-0110                     model=addMets(model,met);
-0111                     tModel=addMets(tModel,met);
-0112                     modelMets=[modelMets;upper(taskStructure(i).inputs(~goodMets))];
-0113                 end
-0114                 
-0115                 %By now the indexes might be getting a bit confusing, but
-0116                 %this is to update the indexes of the "real" metabolites to
-0117                 %point to the newly added ones
-0118                 I(~goodMets)=true; %All the bad ones are fixed at this stage
-0119                 J(~goodMets)=numel(modelMets)-numel(metMatch)+1:numel(modelMets);
-0120             end
-0121             if numel(J(I))~=numel(unique(J(I)))
-0122                 EM=['The constraints on some input(s) in "[' taskStructure(i).id '] ' taskStructure(i).description '" are defined more than one time'];
-0123                 dispEM(EM);
-0124             end
-0125             %If all metabolites should be added
-0126             if any(K)
-0127                 %Check if ALLMETS is the first metabolite. Otherwise print
-0128                 %a warning since it will write over any other constraints
-0129                 %that are set
-0130                 if K(1)==0
-0131                     EM=['ALLMETS is used as an input in "[' taskStructure(i).id '] ' taskStructure(i).description '" but it it not the first metabolite in the list. Constraints defined for the metabolites before it will be over-written'];
-0132                     dispEM(EM,false);
-0133                 end
-0134                 %Use the first match of ALLMETS. There should only be one,
-0135                 %but still..
-0136                 tModel.b(:,1)=taskStructure(i).UBin(find(K,1))*-1;
-0137             end
-0138             %If metabolites in a specific compartment should be used
-0139             if any(L)
-0140                 L=find(L);
-0141                 for j=1:numel(L)
-0142                     %The compartment defined
-0143                     compartment=upper(taskStructure(i).inputs{L(j)}(11:end-1));
-0144                     %Check if it exists in the model
-0145                     C=find(ismember(upper(model.comps),compartment));
-0146                     if any(C)
-0147                         %Match to metabolites
-0148                         tModel.b(model.metComps==C,1)=taskStructure(i).UBin(L(j))*-1;
-0149                     else
-0150                         EM=['The compartment defined for ALLMETSIN in "[' taskStructure(i).id '] ' taskStructure(i).description '" does not exist'];
-0151                         dispEM(EM);
-0152                     end
-0153                 end
-0154             end
-0155             %Then add the normal constraints
-0156             if any(J(I))
-0157                 tModel.b(J(I),1)=taskStructure(i).UBin(I)*-1;
-0158                 tModel.b(J(I),2)=taskStructure(i).LBin(I)*-1;
-0159             end
-0160         end
-0161         %Set the outputs
-0162         if ~isempty(taskStructure(i).outputs)
-0163             [I, J]=ismember(upper(taskStructure(i).outputs),modelMets);
-0164             K=ismember(upper(taskStructure(i).outputs),'ALLMETS');
-0165             L=~cellfun('isempty',strfind(upper(taskStructure(i).outputs),'ALLMETSIN'));
-0166             %Check that all metabolites are either real metabolites or
-0167             %ALLMETS/ALLMETSIN
-0168             goodMets=I|K|L;
-0169             if ~all(goodMets)
-0170                 %Not all of the outputs could be found in the small model.
-0171                 %Check if they exist in the large model
-0172                 [found, metMatch]=ismember(upper(taskStructure(i).outputs(~goodMets)),largeModelMets);
-0173                 if ~all(found)
-0174                     EM=['Could not find all outputs in "[' taskStructure(i).id '] ' taskStructure(i).description '" in either model'];
-0175                     dispEM(EM);
-0176                 else
-0177                     %Otherwise add them to the model
-0178                     met.metNames=refModel.metNames(metMatch);
-0179                     met.compartments=refModel.comps(refModel.metComps(metMatch));
-0180                     
-0181                     %Add the metabolite both to the base model and the
-0182                     %model used in the current task
-0183                     model=addMets(model,met);
-0184                     tModel=addMets(tModel,met);
-0185                     modelMets=[modelMets;upper(taskStructure(i).outputs(~goodMets))];
-0186                 end
-0187                 
-0188                 %By now the indexes might be getting a bit confusing, but
-0189                 %this is to update the indexes of the "real" metabolites to
-0190                 %point to the newly added ones
-0191                 I(~goodMets)=true; %All the bad ones are fixed at this stage
-0192                 J(~goodMets)=numel(modelMets)-numel(metMatch)+1:numel(modelMets);
-0193             end
-0194             if numel(J(I))~=numel(unique(J(I)))
-0195                 EM=['The constraints on some output(s) in "[' taskStructure(i).id '] ' taskStructure(i).description '" are defined more than one time'];
-0196                 dispEM(EM);
-0197             end
-0198             %If all metabolites should be added
-0199             if any(K)
-0200                 %Check if ALLMETS is the first metabolite. Otherwise print
-0201                 %a warning since it will write over any other constraints
-0202                 %that are set
-0203                 if K(1)==0
-0204                     EM=['ALLMETS is used as an output in "[' taskStructure(i).id '] ' taskStructure(i).description '" but it it not the first metabolite in the list. Constraints defined for the metabolites before it will be over-written'];
-0205                     dispEM(EM,false);
-0206                 end
-0207                 %Use the first match of ALLMETS. There should only be one,
-0208                 %but still..
-0209                 tModel.b(:,2)=taskStructure(i).UBout(find(K,1));
-0210             end
-0211             %If metabolites in a specific compartment should be used
-0212             if any(L)
-0213                 L=find(L);
-0214                 for j=1:numel(L)
-0215                     %The compartment defined
-0216                     compartment=upper(taskStructure(i).outputs{L(j)}(11:end-1));
-0217                     %Check if it exists in the model
-0218                     C=find(ismember(upper(model.comps),compartment));
-0219                     if any(C)
-0220                         %Match to metabolites
-0221                         tModel.b(model.metComps==C,2)=taskStructure(i).UBout(L(j));
-0222                     else
-0223                         EM=['The compartment defined for ALLMETSIN in "[' taskStructure(i).id '] ' taskStructure(i).description '" does not exist'];
-0224                         dispEM(EM);
-0225                     end
-0226                 end
-0227             end
-0228             %Then add the normal constraints
-0229             if any(J(I))
-0230                 %Verify that IN and OUT bounds are consistent. Cannot require
-0231                 %that a metabolite is simultaneously input AND output at some
-0232                 %nonzero flux.
-0233                 J = J(I);
-0234                 I = find(I);  % otherwise indexing becomes confusing
-0235                 nonzero_LBin = tModel.b(J,2) < 0;
-0236                 nonzero_LBout = taskStructure(i).LBout(I) > 0;
-0237                 if any(nonzero_LBin & nonzero_LBout)
-0238                     EM=['The IN LB and OUT LB in "[' taskStructure(i).id '] ' taskStructure(i).description '" cannot be nonzero for the same metabolite'];
-0239                     dispEM(EM);
-0240                 end
-0241                 tModel.b(J(nonzero_LBout),1)=taskStructure(i).LBout(I(nonzero_LBout));
-0242                 tModel.b(J,2)=taskStructure(i).UBout(I);
-0243             end
-0244         end
-0245         
-0246         %Add new rxns
-0247         if ~isempty(taskStructure(i).equations)
-0248             rxn.equations=taskStructure(i).equations;
-0249             rxn.lb=taskStructure(i).LBequ;
-0250             rxn.ub=taskStructure(i).UBequ;
-0251             rxn.rxns=strcat({'TEMPORARY_'},num2str((1:numel(taskStructure(i).equations))'));
-0252             tModel=addRxns(tModel,rxn,3);
-0253         end
-0254         %Add changed bounds
-0255         if ~isempty(taskStructure(i).changed)
-0256             tModel=setParam(tModel,'lb',taskStructure(i).changed,taskStructure(i).LBrxn);
-0257             tModel=setParam(tModel,'ub',taskStructure(i).changed,taskStructure(i).UBrxn);
-0258         end
-0259         
-0260         %Solve and print. Display a warning if the problem is not solveable
-0261         sol=solveLP(tModel);
-0262         if isempty(sol.x)
-0263             %Only do gap-filling if it cannot be solved
-0264             failed=false;
-0265             try
-0266                 [~, ~, newRxns, newModel, exitFlag]=fillGaps(tModel,refModel,false,true,supressWarnings,rxnScores);
-0267                 if exitFlag==-2
-0268                     EM=['"[' taskStructure(i).id '] ' taskStructure(i).description '" was aborted before reaching optimality.\n'];
-0269                     dispEM(EM,false);
-0270                 end
-0271             catch
-0272                 EM=['"[' taskStructure(i).id '] ' taskStructure(i).description '" could not be performed for any set of reactions\n'];
-0273                 dispEM(EM,false);
-0274                 failed=true;
-0275             end
-0276             if failed==false
-0277                 if ~isempty(newRxns)
-0278                     nAdded=nAdded+numel(newRxns);
-0279                     
-0280                     %Add the reactions to the base model. It is not correct
-0281                     %to use newModel directly, as it may contain
-0282                     %reactions/constraints that are specific to this task
-0283                     model=mergeModels({model,removeReactions(newModel,setdiff(newModel.rxns,newRxns),true,true)},'metNames',true);
-0284                     
-0285                     %Keep track of the added reactions
-0286                     addedRxns(ismember(refModel.rxns,newRxns),i)=true;
-0287                 end
-0288                 if printOutput==true
-0289                     fprintf(['[' taskStructure(i).id '] ' taskStructure(i).description ': Added ' num2str(numel(newRxns)) ' reaction(s), ' num2str(nAdded) ' reactions added in total\n']);
-0290                 end
-0291             end
-0292         else
-0293             if printOutput==true
-0294                 fprintf(['[' taskStructure(i).id '] ' taskStructure(i).description ': Added 0 reaction(s), ' num2str(nAdded) ' reactions added in total\n']);
-0295             end
-0296         end
-0297         supressWarnings=true;
-0298         
-0299         %Print the output if chosen
-0300         if taskStructure(i).printFluxes && printOutput
-0301             if ~isempty(sol.x)
-0302                 sol=solveLP(tModel,1);
-0303                 printFluxes(tModel,sol.x,false,10^-5,[],'%rxnID (%eqn):%flux\n');
-0304                 fprintf('\n');
-0305             else
-0306                 %If the problem wasn't solveable then the gap-filled model
-0307                 %should be used
-0308                 if failed==false
-0309                     sol=solveLP(newModel,1);
-0310                     printFluxes(newModel,sol.x,false,10^-5,[],'%rxnID (%eqn):%flux\n');
-0311                     fprintf('\n');
-0312                 end
-0313             end
-0314         end
-0315         
-0316         tModel=model;
-0317         %Since new mets are added by merging the new reactions and not only
-0318         %from the task sheet
-0319         modelMets=upper(strcat(model.metNames,'[',model.comps(model.metComps),']'));
-0320     else
-0321         EM=['"[' taskStructure(i).id '] ' taskStructure(i).description '" is set as SHOULD FAIL. Such tasks cannot be modelled using this approach and the task is therefore ignored\n'];
-0322         dispEM(EM,false);
-0323     end
-0324 end
-0325 model.b(:,2) = [];  % resume field b
-0326 outModel=model;
-0327 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/followChanged.html b/doc/core/followChanged.html deleted file mode 100644 index 0329eb544..000000000 --- a/doc/core/followChanged.html +++ /dev/null @@ -1,170 +0,0 @@ - - - - Description of followChanged - - - - - - - - - -
Home > core > followChanged.m
- - - -

followChanged -

- -

PURPOSE ^

-
followChanged
- -

SYNOPSIS ^

-
function followChanged(model,fluxesA,fluxesB, cutOffChange, cutOffFlux, cutOffDiff, metaboliteList)
- -

DESCRIPTION ^

-
 followChanged
-    Prints fluxes and reactions for each of the reactions that results in
-   different fluxes compared to the reference case.
-
-   model           a model structure
-   fluxesA         flux vector for the test case
-   fluxesB         flux vector for the reference test
-   cutOffChange    reactions where the fluxes differ by less than
-                   this many percent won't be printed (optional, default 10^-8)
-   cutOffFlux      reactions where the absolute value of both fluxes
-                   are below this value won't be printed (optional,
-                   default 10^-8)
-   cutOffDiff      reactions where the fluxes differ by less than
-                   cutOffDiff won't be printed (optional, default 10^-8)
-   metaboliteList  cell array of metabolite names. Only reactions
-                   involving any of these metabolites will be
-                   printed (optional)
-
- Usage: followChanged(model,fluxesA,fluxesB, cutOffChange, cutOffFlux,
-           cutOffDiff, metaboliteList)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function followChanged(model,fluxesA,fluxesB, cutOffChange, cutOffFlux, cutOffDiff, metaboliteList)
-0002 % followChanged
-0003 %    Prints fluxes and reactions for each of the reactions that results in
-0004 %   different fluxes compared to the reference case.
-0005 %
-0006 %   model           a model structure
-0007 %   fluxesA         flux vector for the test case
-0008 %   fluxesB         flux vector for the reference test
-0009 %   cutOffChange    reactions where the fluxes differ by less than
-0010 %                   this many percent won't be printed (optional, default 10^-8)
-0011 %   cutOffFlux      reactions where the absolute value of both fluxes
-0012 %                   are below this value won't be printed (optional,
-0013 %                   default 10^-8)
-0014 %   cutOffDiff      reactions where the fluxes differ by less than
-0015 %                   cutOffDiff won't be printed (optional, default 10^-8)
-0016 %   metaboliteList  cell array of metabolite names. Only reactions
-0017 %                   involving any of these metabolites will be
-0018 %                   printed (optional)
-0019 %
-0020 % Usage: followChanged(model,fluxesA,fluxesB, cutOffChange, cutOffFlux,
-0021 %           cutOffDiff, metaboliteList)
-0022 
-0023 %Checks if a cut off flux has been set
-0024 if nargin<4
-0025     cutOffChange=10^-8;
-0026 end
-0027 if nargin<5
-0028     cutOffFlux=10^-8;
-0029 end
-0030 if nargin<6
-0031     cutOffDiff=10^-8;
-0032 end
-0033 if nargin<7
-0034     metaboliteList=[];
-0035 else
-0036     metaboliteList=convertCharArray(metaboliteList);
-0037 end
-0038 
-0039 %If a metabolite list is to be used, then find all the reactions involving
-0040 %any of those metabolites Finds the metabolites
-0041 if nargin>6
-0042     reactionIndexes=[];
-0043     for i=1:length(metaboliteList)
-0044         metaboliteIndex=find(strcmpi(metaboliteList(i),model.metNames)); %Should use id maybe, setting
-0045         if ~isempty(metaboliteIndex)
-0046             [~, b]=find(model.S(metaboliteIndex,:));
-0047             reactionIndexes=[reactionIndexes; b(:)];
-0048         else
-0049             fprintf('Could not find any reactions with the metabolite %s\n\n',char(metaboliteList(i)))
-0050         end
-0051     end
-0052     reactionIndexes=unique(reactionIndexes);
-0053 else
-0054     reactionIndexes=(1:length(fluxesA))';
-0055 end
-0056 
-0057 %Finds the reactions where either flux is at or above the cutOffFlux value
-0058 in1=find(abs(fluxesA(reactionIndexes))>=cutOffFlux)';
-0059 in2=find(abs(fluxesB(reactionIndexes))>=cutOffFlux)';
-0060 ineither=reactionIndexes(unique([in1 in2]));
-0061 
-0062 %Keep only those solutions where the difference is larger than or equal to
-0063 %cutOffDiff
-0064 ineither=ineither(find(abs(fluxesA(ineither)-fluxesB(ineither))>=cutOffDiff));
-0065 
-0066 %Finds the reactions where the fluxes differ more than cutOffChange percent
-0067 %First check those fluxes that are non-zero in solution1.x
-0068 nonZeroFluxes=ineither(find(fluxesA(ineither)));
-0069 quota=1+cutOffChange/100;
-0070 larger=nonZeroFluxes(find((fluxesB(nonZeroFluxes)./fluxesA(nonZeroFluxes))>=(quota)))';
-0071 smaller=nonZeroFluxes(find((fluxesB(nonZeroFluxes)./fluxesA(nonZeroFluxes))<(1/quota)))';
-0072 fluxIndexes=[larger smaller];
-0073 
-0074 %Then add those where solution1 has a zero flux
-0075 zeroFluxes=ineither(find(fluxesA(ineither)==0));
-0076 fluxIndexes=unique([fluxIndexes zeroFluxes(find(abs(fluxesB(zeroFluxes))>=cutOffFlux))']);
-0077 
-0078 formulas=constructEquations(model,model.rxns(fluxIndexes));
-0079 
-0080 if nargin>4
-0081     if nargin>5
-0082         fprintf('These reactions have flux values that differ by more than %s percent, absolute values above %s, and a total difference above %s (%s reactions)\n\n',num2str(cutOffChange),num2str(cutOffFlux),num2str(cutOffDiff),num2str(length(formulas)));
-0083     else
-0084         fprintf('These reactions have flux values that differ by more than %s percent and absolute values above %s (%s reactions)\n\n',num2str(cutOffChange),num2str(cutOffFlux),num2str(length(formulas)));
-0085     end
-0086 else
-0087     fprintf('These reactions have flux values that differ by more than %s percent (%s reactions)\n\n',num2str(cutOffChange),num2str(length(formulas)));
-0088 end
-0089 
-0090 metaboliteNames=[];
-0091 for i=1:length(metaboliteList)
-0092     metaboliteNames=[metaboliteNames char(metaboliteList(i)) ' '];
-0093 end
-0094 
-0095 if ~isempty(metaboliteNames)
-0096     fprintf('Only prints reactions involving one or more of the following metabolites:\n%s\n\n',metaboliteNames)
-0097 end
-0098 
-0099 for i=1:length(formulas)
-0100     fluxText=['Flux: ' num2str(fluxesA(fluxIndexes(i))) ' Reference flux: ' num2str(fluxesB(fluxIndexes(i))) ' Difference: ' num2str(fluxesA(fluxIndexes(i))-fluxesB(fluxIndexes(i)))];
-0101     fprintf('%s: %s\n\t%s\n\t%s\n\n', char(model.rxns(fluxIndexes(i))), char(formulas(i)),...
-0102         char(model.rxnNames(fluxIndexes(i))),fluxText);
-0103 end
-0104 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/followFluxes.html b/doc/core/followFluxes.html deleted file mode 100644 index ba410833f..000000000 --- a/doc/core/followFluxes.html +++ /dev/null @@ -1,109 +0,0 @@ - - - - Description of followFluxes - - - - - - - - - -
Home > core > followFluxes.m
- - - -

followFluxes -

- -

PURPOSE ^

-
followFluxes
- -

SYNOPSIS ^

-
function errorFlag=followFluxes(model, fluxesA, lowerFlux, upperFlux, fluxesB)
- -

DESCRIPTION ^

-
 followFluxes
-    Prints fluxes and reactions for each of the reactions that results in
-   fluxes in the specified interval.
-
-   model       a model structure
-   fluxesA     flux vector for the test case
-   lowerFlux    only reactions with fluxes above this cutoff
-               value are displayed
-   upperFlux   only reactions with fluxes below this cutoff
-               value are displayed (optional, default Inf)
-   fluxesB     flux vector for the reference case(optional)
-
- Usage: errorFlag=followFluxes(model, fluxesA, lowerFlux, upperFlux,
-           fluxesB)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function errorFlag=followFluxes(model, fluxesA, lowerFlux, upperFlux, fluxesB)
-0002 % followFluxes
-0003 %    Prints fluxes and reactions for each of the reactions that results in
-0004 %   fluxes in the specified interval.
-0005 %
-0006 %   model       a model structure
-0007 %   fluxesA     flux vector for the test case
-0008 %   lowerFlux    only reactions with fluxes above this cutoff
-0009 %               value are displayed
-0010 %   upperFlux   only reactions with fluxes below this cutoff
-0011 %               value are displayed (optional, default Inf)
-0012 %   fluxesB     flux vector for the reference case(optional)
-0013 %
-0014 % Usage: errorFlag=followFluxes(model, fluxesA, lowerFlux, upperFlux,
-0015 %           fluxesB)
-0016 
-0017 %Checks that the upper flux is larger than the lower flux
-0018 if nargin>3
-0019     if upperFlux<=lowerFlux
-0020         errorFlag=1;
-0021         return;
-0022     end
-0023 end
-0024 
-0025 %Gets the fluxes for the reactions
-0026 if nargin<4
-0027     fluxIndexes=find(fluxesA>=lowerFlux);
-0028 else
-0029     fluxIndexes=find(fluxesA>=lowerFlux & fluxesA<=upperFlux);
-0030 end
-0031 
-0032 %Finds the involved reactions
-0033 formulas = constructEquations(model,model.rxns(fluxIndexes));
-0034 
-0035 if nargin>3
-0036     fprintf('These reactions have flux values between %s and %s\n\n',num2str(lowerFlux),num2str(upperFlux));
-0037 else
-0038     fprintf('These reactions have flux values above %s\n\n',num2str(lowerFlux));
-0039 end
-0040 for i=1:length(formulas)
-0041     if nargin>4
-0042         fluxText=['Flux: ' num2str(fluxesA(fluxIndexes(i))) ' Reference flux: ' num2str(fluxesB(fluxIndexes(i)))];
-0043     else
-0044         fluxText=['Flux: ' num2str(fluxesA(fluxIndexes(i)))];
-0045     end
-0046     fprintf('%s: %s\n\t%s\n\t%s\n', char(model.rxns(fluxIndexes(i))), char(formulas(i)),...
-0047         char(model.rxnNames(fluxIndexes(i))),fluxText);
-0048 end
-0049 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/gapReport.html b/doc/core/gapReport.html deleted file mode 100644 index 3e8e78c5e..000000000 --- a/doc/core/gapReport.html +++ /dev/null @@ -1,193 +0,0 @@ - - - - Description of gapReport - - - - - - - - - -
Home > core > gapReport.m
- - - -

gapReport -

- -

PURPOSE ^

-
gapReport
- -

SYNOPSIS ^

-
function [noFluxRxns, noFluxRxnsRelaxed, subGraphs, notProducedMets, minToConnect,neededForProductionMat, canProduceWithoutInput, canConsumeWithoutOutput,connectedFromTemplates, addedFromTemplates]=gapReport(model, templateModels)
- -

DESCRIPTION ^

-
 gapReport
-   Performs a gap analysis and summarizes the results 
-
-   model                       a model structure
-   templateModels              a cell array of template models to use for
-                               gap filling (optional)
-
-   noFluxRxns                  cell array with reactions that cannot carry
-                               flux
-   noFluxRxnsRelaxed           cell array with reactions that cannot carry
-                               flux even if the mass balance constraint is 
-                               relaxed so that it is allowed to have 
-                               net production of all metabolites
-   subGraphs                   structure with the metabolites in each of
-                               the isolated sub networks
-   notProducedMets             cell array with the metabolites that
-                               couldn't have net production
-   minToConnect                structure with the minimal number of
-                               metabolites that need to be connected in 
-                               order to be able to produce all other 
-                               metabolites and which metabolites each of
-                               them connects
-   neededForProductionMat      matrix where n x m is true if metabolite n
-                               allows for production of metabolite m
-   canProduceWithoutInput      cell array with metabolites that could be
-                               produced even when there is no input to the
-                               model
-   canConsumeWithoutOutput     cell array with metabolites that could be
-                               consumed even when there is no output from
-                               the model
-   connectedFromTemplates      cell array with the reactions that could be
-                               connected using the template models
-   addedFromTemplates          structure with the reactions that were
-                               added from the template models and which 
-                               model they were added from
-
- Usage: [noFluxRxns, noFluxRxnsRelaxed, subGraphs, notProducedMets, minToConnect,...
-    neededForProductionMat, connectedFromTemplates, addedFromTemplates]=...
-    gapReport(model, templateModels)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function [noFluxRxns, noFluxRxnsRelaxed, subGraphs, notProducedMets, minToConnect,...
-0002     neededForProductionMat, canProduceWithoutInput, canConsumeWithoutOutput, ...
-0003     connectedFromTemplates, addedFromTemplates]=gapReport(model, templateModels)
-0004 % gapReport
-0005 %   Performs a gap analysis and summarizes the results
-0006 %
-0007 %   model                       a model structure
-0008 %   templateModels              a cell array of template models to use for
-0009 %                               gap filling (optional)
-0010 %
-0011 %   noFluxRxns                  cell array with reactions that cannot carry
-0012 %                               flux
-0013 %   noFluxRxnsRelaxed           cell array with reactions that cannot carry
-0014 %                               flux even if the mass balance constraint is
-0015 %                               relaxed so that it is allowed to have
-0016 %                               net production of all metabolites
-0017 %   subGraphs                   structure with the metabolites in each of
-0018 %                               the isolated sub networks
-0019 %   notProducedMets             cell array with the metabolites that
-0020 %                               couldn't have net production
-0021 %   minToConnect                structure with the minimal number of
-0022 %                               metabolites that need to be connected in
-0023 %                               order to be able to produce all other
-0024 %                               metabolites and which metabolites each of
-0025 %                               them connects
-0026 %   neededForProductionMat      matrix where n x m is true if metabolite n
-0027 %                               allows for production of metabolite m
-0028 %   canProduceWithoutInput      cell array with metabolites that could be
-0029 %                               produced even when there is no input to the
-0030 %                               model
-0031 %   canConsumeWithoutOutput     cell array with metabolites that could be
-0032 %                               consumed even when there is no output from
-0033 %                               the model
-0034 %   connectedFromTemplates      cell array with the reactions that could be
-0035 %                               connected using the template models
-0036 %   addedFromTemplates          structure with the reactions that were
-0037 %                               added from the template models and which
-0038 %                               model they were added from
-0039 %
-0040 % Usage: [noFluxRxns, noFluxRxnsRelaxed, subGraphs, notProducedMets, minToConnect,...
-0041 %    neededForProductionMat, connectedFromTemplates, addedFromTemplates]=...
-0042 %    gapReport(model, templateModels)
-0043 
-0044 if nargin<2
-0045     templateModels=[];
-0046     connectedFromTemplates=[];
-0047     addedFromTemplates=[];
-0048 end
-0049 
-0050 fprintf(['Gap analysis for ' model.id ' - ' model.name '\n\n']);
-0051 if isfield(model,'unconstrained')
-0052     calculateINOUT=true;
-0053     closedModel=model;
-0054     model=simplifyModel(model);
-0055 else
-0056     canConsumeWithoutOutput={};
-0057     canProduceWithoutInput={};
-0058     calculateINOUT=false;
-0059 end
-0060 
-0061 model2=model;
-0062 model2.b=[model2.b inf(numel(model2.mets),1)];
-0063 I=haveFlux(model);
-0064 noFluxRxns=model.rxns(~I);
-0065 J=haveFlux(model2);
-0066 noFluxRxnsRelaxed=model2.rxns(~J);
-0067 bModel=removeReactions(model,~I,true,true);
-0068 cModel=removeReactions(model2,~J,true,true);
-0069 fprintf('***Overview\n');
-0070 fprintf([num2str(numel(model.rxns)-sum(I)) ' out of ' num2str(numel(model.rxns))...
-0071     ' reactions cannot carry flux (' num2str(numel(model.rxns)-sum(J)) ' if net production of all metabolites is allowed)\n']);
-0072 fprintf([num2str(numel(model.mets)-numel(bModel.mets)) ' out of ' num2str(numel(model.mets))...
-0073     ' metabolites are unreachable (' num2str(numel(model.mets)-numel(cModel.mets)) ' if net production of all metabolites is allowed)\n']);
-0074 
-0075 fprintf('\n***Isolated subnetworks\n');
-0076 subGraphs=getAllSubGraphs(model);
-0077 fprintf(['A total of ' num2str(size(subGraphs,2)) ' isolated sub-networks are present in the model\n']);
-0078 for i=1:size(subGraphs,2)
-0079     fprintf(['\t' num2str(i) '. ' num2str(sum(subGraphs(:,i))) ' metabolites\n']);
-0080 end
-0081 
-0082 fprintf('\n***Metabolite connectivity\n');
-0083 [notProducedMets, ~, neededForProductionMat,minToConnect]=checkProduction(model,true,model.comps,false);
-0084 fprintf(['To enable net production of all metabolites, a total of ' num2str(numel(minToConnect)) ' metabolites must be connected\n']);
-0085 fprintf('Top 10 metabolites to connect:\n');
-0086 for i=1:min(10,numel(minToConnect))
-0087     fprintf(['\t' num2str(i) '. ' minToConnect{i} '\n']);
-0088 end
-0089 
-0090 if calculateINOUT==true
-0091     fprintf('\n***Mass balancing\n');
-0092     produced=canProduce(closedModel);
-0093     canProduceWithoutInput=closedModel.mets(produced);
-0094     consumed=canConsume(closedModel);
-0095     canConsumeWithoutOutput=closedModel.mets(consumed);
-0096     fprintf([num2str(numel(canConsumeWithoutOutput)) ' metabolites could be consumed without any outputs\n' num2str(numel(canProduceWithoutInput)) ' metabolites could be produced without any inputs\n']);
-0097 end
-0098 
-0099 if ~isempty(templateModels)
-0100     fprintf('\n***Automated gap-filling\n');
-0101     [connectedFromTemplates, ~, addedFromTemplates]=fillGaps(model,templateModels);
-0102     t=templateModels{1}.id;
-0103     for i=2:numel(templateModels)
-0104         t=[t ', ' templateModels{i}.id];
-0105     end
-0106     fprintf([num2str(numel(connectedFromTemplates)) ' unconnected reactions can be connected by including ' num2str(numel(addedFromTemplates)) ' reactions from\n' t '\n']);
-0107 end
-0108 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/generateNewIds.html b/doc/core/generateNewIds.html deleted file mode 100644 index 557c96030..000000000 --- a/doc/core/generateNewIds.html +++ /dev/null @@ -1,123 +0,0 @@ - - - - Description of generateNewIds - - - - - - - - - -
Home > core > generateNewIds.m
- - - -

generateNewIds -

- -

PURPOSE ^

-
generateNewIds
- -

SYNOPSIS ^

-
function newIds=generateNewIds(model,type,prefix,quantity,numLength)
- -

DESCRIPTION ^

-
 generateNewIds
-   Generates a list of new metabolite or reaction ids, sequentially
-   numbered with a defined prefix. The model is queried for the highest
-   existing number of that type of id.
-
-   model       model structure
-   type        string specifying type of id, 'rxns' or 'mets'
-   prefix      string specifying prefix to be used in all ids. E.g. 's_'
-               or 'r_'.
-   quantity    number of new ids that should be generated (optional, default 1)
-   numLength   length of numerical part of id. E.g. 4 gives ids like
-               r_0001 and 6 gives ids like r_000001. If the prefix is
-               already used in the model, then the model-defined length
-               will be used instead. (optional, default 4)
-
- Usage: newIds=generateNewIds(model,type,prefix,quantity,numLength)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function newIds=generateNewIds(model,type,prefix,quantity,numLength)
-0002 % generateNewIds
-0003 %   Generates a list of new metabolite or reaction ids, sequentially
-0004 %   numbered with a defined prefix. The model is queried for the highest
-0005 %   existing number of that type of id.
-0006 %
-0007 %   model       model structure
-0008 %   type        string specifying type of id, 'rxns' or 'mets'
-0009 %   prefix      string specifying prefix to be used in all ids. E.g. 's_'
-0010 %               or 'r_'.
-0011 %   quantity    number of new ids that should be generated (optional, default 1)
-0012 %   numLength   length of numerical part of id. E.g. 4 gives ids like
-0013 %               r_0001 and 6 gives ids like r_000001. If the prefix is
-0014 %               already used in the model, then the model-defined length
-0015 %               will be used instead. (optional, default 4)
-0016 %
-0017 % Usage: newIds=generateNewIds(model,type,prefix,quantity,numLength)
-0018 %
-0019 type=char(type);
-0020 prefix=char(prefix);
-0021 
-0022 if type=='rxns'
-0023     existingIds=model.rxns;
-0024 elseif type=='mets'
-0025     existingIds=model.mets;
-0026 else
-0027     error('type should be either ''rxns'' or ''mets''.')
-0028 end
-0029 if nargin<4
-0030     quantity=1;
-0031 end
-0032 if nargin<5
-0033     numLength=4;
-0034 end
-0035 
-0036 % Subset only existingIds that have the prefix
-0037 existingIds=existingIds(~cellfun(@isempty,regexp(existingIds,['^' prefix])));
-0038 
-0039 if ~isempty(existingIds)
-0040     existingIds=regexprep(existingIds,['^' prefix],'');
-0041     existingIds=sort(existingIds);
-0042     lastId=existingIds{end};
-0043     numLength=length(lastId);
-0044     lastId=str2double(lastId);
-0045 else
-0046     lastId=0;
-0047     fprintf(['No ' type ' ids with prefix "' prefix ...
-0048         '" currently exist in the model. The first new id will be "' ...
-0049         [prefix,num2str(1,['%0' num2str(numLength) 'd'])] '"\n'],'%s')
-0050 end
-0051 
-0052 if isnan(lastId)
-0053     lastId = 0;
-0054 end
-0055 
-0056 newIds=cell(quantity,1);
-0057 
-0058 for k=1:quantity
-0059     newIds{k}=[prefix,num2str(k+lastId,['%0' num2str(numLength) 'd'])];
-0060 end
-0061 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/getAllRxnsFromGenes.html b/doc/core/getAllRxnsFromGenes.html deleted file mode 100644 index 1881ccb0b..000000000 --- a/doc/core/getAllRxnsFromGenes.html +++ /dev/null @@ -1,96 +0,0 @@ - - - - Description of getAllRxnsFromGenes - - - - - - - - - -
Home > core > getAllRxnsFromGenes.m
- - - -

getAllRxnsFromGenes -

- -

PURPOSE ^

-
getAllRxnsFromGenes
- -

SYNOPSIS ^

-
function allRxns=getAllRxnsFromGenes(model,rxns)
- -

DESCRIPTION ^

-
 getAllRxnsFromGenes
-   Given a list of reactions, this function finds the associated genes in
-   the template model and gives all reactions that are annotated by these
-   genes.
-
-   model       a model structure
-   rxns        either a cell array of IDs, a logical vector with the
-               same number of elements as reactions in the model, or a
-               vector of indexes
-
-   allRxns     either a cell array of IDs, a logical vector with the
-               same number of elements as reactions in the model, or a
-               vector of indexes, dependent on the format of rxns
-
- Usage: allRxns=getAllRxnsFromGenes(model,rxns)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function allRxns=getAllRxnsFromGenes(model,rxns)
-0002 % getAllRxnsFromGenes
-0003 %   Given a list of reactions, this function finds the associated genes in
-0004 %   the template model and gives all reactions that are annotated by these
-0005 %   genes.
-0006 %
-0007 %   model       a model structure
-0008 %   rxns        either a cell array of IDs, a logical vector with the
-0009 %               same number of elements as reactions in the model, or a
-0010 %               vector of indexes
-0011 %
-0012 %   allRxns     either a cell array of IDs, a logical vector with the
-0013 %               same number of elements as reactions in the model, or a
-0014 %               vector of indexes, dependent on the format of rxns
-0015 %
-0016 % Usage: allRxns=getAllRxnsFromGenes(model,rxns)
-0017 
-0018 if ~islogical(rxns) && ~isnumeric(rxns)
-0019     rxns=convertCharArray(rxns);
-0020 end
-0021 
-0022 rxnIdx=getIndexes(model,rxns,'rxns');
-0023 [~, geneIdx]=find(model.rxnGeneMat(rxnIdx,:));
-0024 [allRxns, ~]=find(model.rxnGeneMat(:,geneIdx));
-0025 if iscell(rxns)
-0026     allRxns=unique([model.rxns(allRxns);model.rxns(rxnIdx)]);
-0027 elseif isnumeric(rxns) || islogical(rxns)
-0028     allRxns=unique([allRxns;rxnIdx]);
-0029     if islogical(rxns)
-0030         temp=false(numel(model.rxns),1);
-0031         temp(allRxns)=true;
-0032         allRxns=temp;
-0033     end
-0034 end
-0035 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/getAllSubGraphs.html b/doc/core/getAllSubGraphs.html deleted file mode 100644 index 80fa5200e..000000000 --- a/doc/core/getAllSubGraphs.html +++ /dev/null @@ -1,120 +0,0 @@ - - - - Description of getAllSubGraphs - - - - - - - - - -
Home > core > getAllSubGraphs.m
- - - -

getAllSubGraphs -

- -

PURPOSE ^

-
getAllSubGraphs
- -

SYNOPSIS ^

-
function subGraphs=getAllSubGraphs(model)
- -

DESCRIPTION ^

-
 getAllSubGraphs
-   Get all metabolic subgraphs in a model. Two metabolites 
-   are connected if they share a reaction.
-
-   Input:
-   model         a model structure
-
-   Output:
-   subGraphs     a boolean matrix where the rows correspond to the metabolites
-                 and the columns to which subgraph they are assigned to. The
-                 columns are ordered so that larger subgraphs come first
-
- Usage: subGraphs=getAllSubGraphs(model)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function subGraphs=getAllSubGraphs(model)
-0002 % getAllSubGraphs
-0003 %   Get all metabolic subgraphs in a model. Two metabolites
-0004 %   are connected if they share a reaction.
-0005 %
-0006 %   Input:
-0007 %   model         a model structure
-0008 %
-0009 %   Output:
-0010 %   subGraphs     a boolean matrix where the rows correspond to the metabolites
-0011 %                 and the columns to which subgraph they are assigned to. The
-0012 %                 columns are ordered so that larger subgraphs come first
-0013 %
-0014 % Usage: subGraphs=getAllSubGraphs(model)
-0015 
-0016 %Generate the connectivity graph. Metabolites are connected through
-0017 %reactions. This is not a bipartite graph with the reactions.
-0018 G=model.S*model.S';
-0019 G(G~=0)=1;
-0020 
-0021 %Keeps track of which mets have been assigned to a subgraph
-0022 isAssigned=false(numel(model.mets),1);
-0023 
-0024 %Allocate space for subgraphs, initially one graph for each met
-0025 subGraphs=false(numel(model.mets),numel(model.mets));
-0026 
-0027 %Main loop continues until all mets have been assigned to a subgraph
-0028 counter=1;
-0029 while ~all(isAssigned)
-0030     currentSG=false(numel(model.mets),1);
-0031     %Find the first non-assigned metabolite and assign it to the current SG
-0032     I=find(isAssigned==false,1);
-0033     currentSG(I)=true;
-0034     isAssigned(I)=true;
-0035     %Then iteratively add all mets that are connected to each other, until
-0036     %no more such mets can be found
-0037     while true
-0038         J=sum(G(:,currentSG),2);
-0039         
-0040         %Get the new mets for this SG. Also assign them to the current SG
-0041         newOnes=J~=0 & currentSG==false;
-0042         isAssigned(newOnes)=true;
-0043         currentSG(newOnes)=true;
-0044         
-0045         %If there are no new mets, then abort
-0046         if ~any(newOnes)
-0047             subGraphs(currentSG,counter)=true;
-0048             counter=counter+1;
-0049             break;
-0050         end
-0051     end
-0052 end
-0053 subGraphs=subGraphs(:,1:counter);
-0054 
-0055 [~, I]=sort(sum(subGraphs),'descend');
-0056 
-0057 subGraphs=subGraphs(:,I);
-0058 
-0059 %Also remove empty subgraphs (can happen when metabolites are never used)
-0060 subGraphs(:,sum(subGraphs)==0)=[];
-0061 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/getAllowedBounds.html b/doc/core/getAllowedBounds.html deleted file mode 100644 index ec6855e91..000000000 --- a/doc/core/getAllowedBounds.html +++ /dev/null @@ -1,146 +0,0 @@ - - - - Description of getAllowedBounds - - - - - - - - - -
Home > core > getAllowedBounds.m
- - - -

getAllowedBounds -

- -

PURPOSE ^

-
getAllowedBounds
- -

SYNOPSIS ^

-
function [minFluxes, maxFluxes, exitFlags]=getAllowedBounds(model,rxns,runParallel)
- -

DESCRIPTION ^

-
 getAllowedBounds
-   Returns the minimal and maximal fluxes through each reaction.
-
- Input:
-   model           a model structure
-   rxns            either a cell array of reaction IDs, a logical vector
-                   with the same number of elements as reactions in the
-                   model, or a vector of reaction indexes (optional, default
-                   model.rxns)
-   runParallel     speed up calculations by parallel processing. This is
-                   not beneficial if allowed bounds are calculated for
-                   only a few reactions, as the overhead of parallel
-                   processing will take longer. It requires MATLAB
-                   Parallel Computing Toolbox. If this is not installed,
-                   the calculations will not be parallelized, regardless
-                   what is indicated as runParallel. (optional, default true)
-
- Output:
-   minFluxes       minimal allowed fluxes
-   maxFluxes       maximal allowed fluxes
-   exitFlags       exit flags for min/max for each of the reactions. True
-                   if it was possible to calculate a flux
-
- In cases where no solution can be calculated, NaN is returned.
-
- Usage: [minFluxes, maxFluxes, exitFlags] = getAllowedBounds(model, rxns, runParallel)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function [minFluxes, maxFluxes, exitFlags]=getAllowedBounds(model,rxns,runParallel)
-0002 % getAllowedBounds
-0003 %   Returns the minimal and maximal fluxes through each reaction.
-0004 %
-0005 % Input:
-0006 %   model           a model structure
-0007 %   rxns            either a cell array of reaction IDs, a logical vector
-0008 %                   with the same number of elements as reactions in the
-0009 %                   model, or a vector of reaction indexes (optional, default
-0010 %                   model.rxns)
-0011 %   runParallel     speed up calculations by parallel processing. This is
-0012 %                   not beneficial if allowed bounds are calculated for
-0013 %                   only a few reactions, as the overhead of parallel
-0014 %                   processing will take longer. It requires MATLAB
-0015 %                   Parallel Computing Toolbox. If this is not installed,
-0016 %                   the calculations will not be parallelized, regardless
-0017 %                   what is indicated as runParallel. (optional, default true)
-0018 %
-0019 % Output:
-0020 %   minFluxes       minimal allowed fluxes
-0021 %   maxFluxes       maximal allowed fluxes
-0022 %   exitFlags       exit flags for min/max for each of the reactions. True
-0023 %                   if it was possible to calculate a flux
-0024 %
-0025 % In cases where no solution can be calculated, NaN is returned.
-0026 %
-0027 % Usage: [minFluxes, maxFluxes, exitFlags] = getAllowedBounds(model, rxns, runParallel)
-0028 
-0029 if nargin<2 || isempty(rxns)
-0030     rxns = 1:numel(model.rxns);
-0031 elseif ~islogical(rxns) && ~isnumeric(rxns)
-0032     rxns = convertCharArray(rxns);
-0033     rxns = getIndexes(model,rxns, 'rxns');
-0034 end
-0035 if nargin<3
-0036     runParallel = true;
-0037 end
-0038 
-0039 [ps, oldPoolAutoCreateSetting] = parallelPoolRAVEN(runParallel);
-0040 
-0041 minFluxes = zeros(numel(rxns),1);
-0042 maxFluxes = zeros(numel(rxns),1);
-0043 exitFlags = zeros(numel(rxns),2);
-0044 c = zeros(numel(model.rxns),1);
-0045 
-0046 PB = ProgressBar2(numel(rxns),'Running getAllowedBounds','cli');
-0047 parfor i = 1:numel(rxns)
-0048     count(PB)
-0049     tmpModel = model;
-0050     tmpModel.c = c;
-0051 
-0052     % Get maximal flux
-0053     tmpModel.c(rxns(i)) = 1;
-0054     [solMax,hsSol]=solveLP(tmpModel);
-0055     if ~isempty(solMax.f)
-0056         maxFluxes(i) = solMax.x(rxns(i));
-0057     else
-0058         maxFluxes(i) = NaN;
-0059     end
-0060 
-0061     % Get minimal flux
-0062     tmpModel.c(rxns(i)) = -1;
-0063     solMin = solveLP(tmpModel,[],[],hsSol);
-0064     if ~isempty(solMin.f)
-0065         minFluxes(i) = solMin.x(rxns(i));
-0066     else
-0067         minFluxes(i) = NaN;
-0068     end
-0069     exitFlags(i,:) = [solMin.stat solMax.stat];
-0070 
-0071 end
-0072 % Reset original Parallel setting
-0073 ps.Pool.AutoCreate = oldPoolAutoCreateSetting;
-0074 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/getElementalBalance.html b/doc/core/getElementalBalance.html deleted file mode 100644 index 3aea2d38c..000000000 --- a/doc/core/getElementalBalance.html +++ /dev/null @@ -1,215 +0,0 @@ - - - - Description of getElementalBalance - - - - - - - - - -
Home > core > getElementalBalance.m
- - - -

getElementalBalance -

- -

PURPOSE ^

-
getElementalBalance
- -

SYNOPSIS ^

-
function balanceStructure=getElementalBalance(model,rxns,printUnbalanced,printUnparsable)
- -

DESCRIPTION ^

-
 getElementalBalance
-   Checks a model to see if the reactions are elementally balanced
-
-   model             a model structure
-   rxns              either a cell array of reaction IDs, a logical vector
-                     with the same number of elements as reactions in the model,
-                     of a vector of indexes. Only these reactions will be
-                     checked (optional, default model.rxns)
-   printUnbalanced   print warnings about the reactions that were
-                     unbalanced (optional, default false)
-   printUnparsable   print warnings about the reactions that cannot be
-                     parsed (optional, default false)
-
-   balanceStructure
-       balanceStatus   1 if the reaction is balanced, 0 if it's unbalanced,
-                      -1 if it couldn't be balanced due to missing information,
-                      -2 if it couldn't be balanced due to an error
-       elements
-           abbrevs     cell array with abbreviations for all used elements
-           names       cell array with the names for all used elements
-       leftComp        MxN matrix with the sum of coefficients for each of
-                       the elements (N) for the left side of the
-                       reactions (M)
-       rightComp       the corresponding matrix for the right side
-
- Usage: balanceStructure=getElementalBalance(model,rxns,printUnbalanced,printUnparsable)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function balanceStructure=getElementalBalance(model,rxns,printUnbalanced,printUnparsable)
-0002 % getElementalBalance
-0003 %   Checks a model to see if the reactions are elementally balanced
-0004 %
-0005 %   model             a model structure
-0006 %   rxns              either a cell array of reaction IDs, a logical vector
-0007 %                     with the same number of elements as reactions in the model,
-0008 %                     of a vector of indexes. Only these reactions will be
-0009 %                     checked (optional, default model.rxns)
-0010 %   printUnbalanced   print warnings about the reactions that were
-0011 %                     unbalanced (optional, default false)
-0012 %   printUnparsable   print warnings about the reactions that cannot be
-0013 %                     parsed (optional, default false)
-0014 %
-0015 %   balanceStructure
-0016 %       balanceStatus   1 if the reaction is balanced, 0 if it's unbalanced,
-0017 %                      -1 if it couldn't be balanced due to missing information,
-0018 %                      -2 if it couldn't be balanced due to an error
-0019 %       elements
-0020 %           abbrevs     cell array with abbreviations for all used elements
-0021 %           names       cell array with the names for all used elements
-0022 %       leftComp        MxN matrix with the sum of coefficients for each of
-0023 %                       the elements (N) for the left side of the
-0024 %                       reactions (M)
-0025 %       rightComp       the corresponding matrix for the right side
-0026 %
-0027 % Usage: balanceStructure=getElementalBalance(model,rxns,printUnbalanced,printUnparsable)
-0028 
-0029 if nargin<2
-0030     rxns=[];
-0031 elseif ~islogical(rxns) && ~isnumeric(rxns)
-0032     rxns=convertCharArray(rxns);
-0033 end
-0034 
-0035 if nargin<3
-0036     printUnbalanced=false;
-0037 end
-0038 
-0039 if nargin<4
-0040     printUnparsable=false;
-0041 end
-0042 
-0043 if ~isempty(rxns)
-0044     indexes=~getIndexes(model,rxns,'rxns',true);
-0045     model=removeReactions(model,indexes,true);
-0046 end
-0047 
-0048 balanceStructure.balanceStatus=nan(numel(model.rxns),1);
-0049 
-0050 %Get the formulas
-0051 if isfield(model,'metFormulas')
-0052     [balanceStructure.elements, useMat, exitFlag]=parseFormulas(model.metFormulas, true);
-0053 else
-0054     if isfield(model,'inchis')
-0055         [balanceStructure.elements, useMat, exitFlag]=parseFormulas(model.inchis, true,true);
-0056     else
-0057         EM='The model must contain either the "metFormulas" or the "inchis" field in order to test for elemental balancing';
-0058         dispEM(EM);
-0059     end
-0060 end
-0061 
-0062 balanceStructure.leftComp=zeros(numel(model.rxns),numel(balanceStructure.elements.names));
-0063 balanceStructure.rightComp=balanceStructure.leftComp;
-0064 
-0065 %Look at the right and left side of the reactions separately
-0066 S{1}=model.S;
-0067 S{2}=model.S;
-0068 S{1}(S{1}>0)=0; %Left side
-0069 S{2}(S{2}<0)=0; %Right side
-0070 S{1}=abs(S{1}); %Both should have positive values
-0071 
-0072 %First do it for left side and then for right
-0073 for i=1:2
-0074     for j=1:numel(model.rxns)
-0075         %Get the balance status of the involved mets
-0076         I=exitFlag(S{i}(:,j)~=0);
-0077         if any(I==-1)
-0078             balanceStructure.balanceStatus(j)=-2;
-0079         end
-0080         if any(I==0)
-0081             %Don't change a more serious error to a less serious one
-0082             balanceStructure.balanceStatus(j)=min(-1,balanceStructure.balanceStatus(j));
-0083         end
-0084         %Loop through each element
-0085         for k=1:numel(balanceStructure.elements.names)
-0086             if i==1
-0087                 balanceStructure.leftComp(j,k)=sum(S{i}(:,j).*useMat(:,k));
-0088             else
-0089                 balanceStructure.rightComp(j,k)=sum(S{i}(:,j).*useMat(:,k));
-0090             end
-0091         end
-0092     end
-0093 end
-0094 
-0095 %Now compare the left and right sides to find which are unbalanced. This is
-0096 %done even if the reaction as a whole couldn't be balanced
-0097 total=abs(balanceStructure.rightComp-balanceStructure.leftComp)>10^-8; %To deal with roundoff error
-0098 
-0099 %Get which reactions are unbalanced. Don't change an error to just
-0100 %unbalanced
-0101 balanceStructure.balanceStatus(any(total,2))=min(balanceStructure.balanceStatus(any(total,2)),0);
-0102 
-0103 %The remaining ones are all balanced
-0104 balanceStructure.balanceStatus(isnan(balanceStructure.balanceStatus))=1;
-0105 
-0106 %Print warnings
-0107 toPrint=[];
-0108 if printUnbalanced==true
-0109     toPrint=[toPrint;find(balanceStructure.balanceStatus==0)];
-0110 end
-0111 if printUnparsable==true
-0112     toPrint=[toPrint;find(balanceStructure.balanceStatus<0)];
-0113 end
-0114 
-0115 toPrint=sort(toPrint);
-0116 for i=1:numel(toPrint)
-0117     if balanceStructure.balanceStatus(toPrint(i))<0
-0118         if balanceStructure.balanceStatus(toPrint(i))==-1
-0119             EM=['The reaction ' model.rxns{toPrint(i)} ' could not be balanced due to missing information'];
-0120             dispEM(EM,false);
-0121         else
-0122             EM=['The reaction ' model.rxns{toPrint(i)} ' could not be balanced due to a parsing error'];
-0123             dispEM(EM,false);
-0124         end
-0125     else
-0126         %Find the compounds that it's not balanced for
-0127         notBalanced=find(total(toPrint(i),:));
-0128         for j=1:numel(notBalanced)
-0129             EM=['The reaction ' model.rxns{toPrint(i)} ' is not balanced with respect to ' balanceStructure.elements.names{notBalanced(j)}];
-0130             dispEM(EM,false);
-0131         end
-0132     end
-0133 end
-0134 
-0135 % Re-order the structure entries so they're consistent with the ordering of
-0136 % the input reaction indexes
-0137 if ~isempty(rxns)
-0138     rxns = getIndexes(model,rxns,'rxns');
-0139     [~,i] = sort(rxns);
-0140     balanceStructure.balanceStatus(i) = balanceStructure.balanceStatus;
-0141     balanceStructure.leftComp(i,:) = balanceStructure.leftComp;
-0142     balanceStructure.rightComp(i,:) = balanceStructure.rightComp;
-0143 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/getEssentialRxns.html b/doc/core/getEssentialRxns.html deleted file mode 100644 index ba3ac4c96..000000000 --- a/doc/core/getEssentialRxns.html +++ /dev/null @@ -1,126 +0,0 @@ - - - - Description of getEssentialRxns - - - - - - - - - -
Home > core > getEssentialRxns.m
- - - -

getEssentialRxns -

- -

PURPOSE ^

-
getEssentialRxns
- -

SYNOPSIS ^

-
function [essentialRxns, essentialRxnsIndexes]=getEssentialRxns(model,ignoreRxns)
- -

DESCRIPTION ^

-
 getEssentialRxns
-   Calculate the essential reactions for a model to be solvable
-
-   model                   a model structure
-   ignoreRxns              cell array of reaction IDs which should not be
-                           checked (optional, default {})
-
-   essentialRxns           cell array with the IDs of the essential reactions
-   essentialRxnsIndexes    vector with the indexes of the essential reactions
-
-   Essential reactions are those which, when constrained to 0, result in an
-   infeasible problem.
-
- Usage: [essentialRxns, essentialRxnsIndexes]=getEssentialRxns(model,ignoreRxns)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function [essentialRxns, essentialRxnsIndexes]=getEssentialRxns(model,ignoreRxns)
-0002 % getEssentialRxns
-0003 %   Calculate the essential reactions for a model to be solvable
-0004 %
-0005 %   model                   a model structure
-0006 %   ignoreRxns              cell array of reaction IDs which should not be
-0007 %                           checked (optional, default {})
-0008 %
-0009 %   essentialRxns           cell array with the IDs of the essential reactions
-0010 %   essentialRxnsIndexes    vector with the indexes of the essential reactions
-0011 %
-0012 %   Essential reactions are those which, when constrained to 0, result in an
-0013 %   infeasible problem.
-0014 %
-0015 % Usage: [essentialRxns, essentialRxnsIndexes]=getEssentialRxns(model,ignoreRxns)
-0016 
-0017 if nargin<2
-0018     ignoreRxns={};
-0019 else
-0020     ignoreRxns=convertCharArray(ignoreRxns);
-0021 end
-0022 
-0023 %Too make sure that it doesn't try to optimize for something
-0024 model.c=zeros(numel(model.rxns),1);
-0025 
-0026 %First check that the problem is solvable
-0027 [sol, hsSolOut]=solveLP(model,1);
-0028 
-0029 if sol.stat==-1 || isempty(sol.x)
-0030     EM='No feasible solution to the full model';
-0031     dispEM(EM);
-0032 end
-0033 
-0034 %Check which reactions have flux. Only those can be essential. This is not
-0035 %the smallest list of reactions, but it's a fast way
-0036 rxnsToCheck=setdiff(model.rxns(abs(sol.x)>10^-12),ignoreRxns);
-0037 nToCheck=numel(rxnsToCheck);
-0038 minimize=true;
-0039 while 1
-0040     if minimize==true
-0041         sol=solveLP(setParam(model,'obj',rxnsToCheck,-1));
-0042     else
-0043         sol=solveLP(setParam(model,'obj',rxnsToCheck,1));
-0044     end
-0045     rxnsToCheck=intersect(rxnsToCheck,model.rxns(abs(sol.x)>10^-8));
-0046     if numel(rxnsToCheck)>=nToCheck
-0047         if minimize==true
-0048             minimize=false;
-0049         else
-0050             break;
-0051         end
-0052     else
-0053         nToCheck=numel(rxnsToCheck);
-0054     end
-0055 end
-0056 
-0057 essentialRxns={};
-0058 for i=1:numel(rxnsToCheck)
-0059     sol=solveLP(setParam(model,'eq',rxnsToCheck(i),0),0,[],hsSolOut);
-0060     if sol.stat==-1 || isempty(sol.x)
-0061         essentialRxns=[essentialRxns;rxnsToCheck(i)];
-0062     end
-0063 end
-0064 
-0065 [~, essentialRxnsIndexes]=ismember(essentialRxns,model.rxns);
-0066 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/getExchangeRxns.html b/doc/core/getExchangeRxns.html deleted file mode 100644 index 09e722abe..000000000 --- a/doc/core/getExchangeRxns.html +++ /dev/null @@ -1,170 +0,0 @@ - - - - Description of getExchangeRxns - - - - - - - - - -
Home > core > getExchangeRxns.m
- - - -

getExchangeRxns -

- -

PURPOSE ^

-
getExchangeRxns
- -

SYNOPSIS ^

-
function [exchangeRxns, exchangeRxnsIndexes]=getExchangeRxns(model,reactionType)
- -

DESCRIPTION ^

-
 getExchangeRxns
-   Retrieves the exchange reactions from a model. Exchange reactions are
-   identified by having either no substrates or products.
-
- Input:
-   model               a model structure
-   reactionType        which exchange reactions should be returned
-                       'all'     all reactions, irrespective of reaction
-                                 bounds
-                       'uptake'  reactions with bounds that imply that
-                                 only uptake are allowed. Reaction
-                                 direction, upper and lower bounds are
-                                 all considered
-                       'excrete' reactions with bounds that imply that
-                                 only excretion are allowed. Reaction
-                                 direction, upper and lower bounds are
-                                 all considered
-                       'reverse' reactions with non-zero upper and lower
-                                 bounds that imply that both uptake and
-                                 excretion are allowed
-                       'blocked' reactions that have zero upper and lower
-                                 bounds, not allowing any flux
-                       'in'      reactions where the boundary metabolite
-                                 is the substrate of the reaction, a
-                                 positive flux value would imply uptake,
-                                 but reaction bounds are not considered
-                       'out'     reactions where the boundary metabolite
-                                 is the product of the reaction, a
-                                 negative flux value would imply uptake,
-                                 but reaction bounds are not considered.
-
- Output:
-   exchangeRxns        cell array with the IDs of the exchange reactions
-   exchangeRxnsIndexes vector with the indexes of the exchange reactions
-
- Note:
-   The union of 'in' and 'out' equals 'all'. Also, the union of 'uptake',
-   'excrete', 'reverse' and 'blocked' equals all.
-
- Usage: [exchangeRxns,exchangeRxnsIndexes]=getExchangeRxns(model,reactionType)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function [exchangeRxns, exchangeRxnsIndexes]=getExchangeRxns(model,reactionType)
-0002 % getExchangeRxns
-0003 %   Retrieves the exchange reactions from a model. Exchange reactions are
-0004 %   identified by having either no substrates or products.
-0005 %
-0006 % Input:
-0007 %   model               a model structure
-0008 %   reactionType        which exchange reactions should be returned
-0009 %                       'all'     all reactions, irrespective of reaction
-0010 %                                 bounds
-0011 %                       'uptake'  reactions with bounds that imply that
-0012 %                                 only uptake are allowed. Reaction
-0013 %                                 direction, upper and lower bounds are
-0014 %                                 all considered
-0015 %                       'excrete' reactions with bounds that imply that
-0016 %                                 only excretion are allowed. Reaction
-0017 %                                 direction, upper and lower bounds are
-0018 %                                 all considered
-0019 %                       'reverse' reactions with non-zero upper and lower
-0020 %                                 bounds that imply that both uptake and
-0021 %                                 excretion are allowed
-0022 %                       'blocked' reactions that have zero upper and lower
-0023 %                                 bounds, not allowing any flux
-0024 %                       'in'      reactions where the boundary metabolite
-0025 %                                 is the substrate of the reaction, a
-0026 %                                 positive flux value would imply uptake,
-0027 %                                 but reaction bounds are not considered
-0028 %                       'out'     reactions where the boundary metabolite
-0029 %                                 is the product of the reaction, a
-0030 %                                 negative flux value would imply uptake,
-0031 %                                 but reaction bounds are not considered.
-0032 %
-0033 % Output:
-0034 %   exchangeRxns        cell array with the IDs of the exchange reactions
-0035 %   exchangeRxnsIndexes vector with the indexes of the exchange reactions
-0036 %
-0037 % Note:
-0038 %   The union of 'in' and 'out' equals 'all'. Also, the union of 'uptake',
-0039 %   'excrete', 'reverse' and 'blocked' equals all.
-0040 %
-0041 % Usage: [exchangeRxns,exchangeRxnsIndexes]=getExchangeRxns(model,reactionType)
-0042 
-0043 if nargin<2
-0044     reactionType='all';
-0045 else
-0046     reactionType=char(reactionType);
-0047 end
-0048 
-0049 % Find exchange reactions
-0050 if isfield(model, 'unconstrained')
-0051     [~, I]=find(model.S(model.unconstrained~=0,:)>0);
-0052     hasNoProd(I)=true;
-0053     [~, I]=find(model.S(model.unconstrained~=0,:)<0);
-0054     hasNoSubs(I)=true;
-0055 else
-0056     hasNoProd = transpose(find(sum(model.S>0)==0));
-0057     hasNoSubs = transpose(find(sum(model.S<0)==0));
-0058 end
-0059 allExch   = [hasNoProd; hasNoSubs];
-0060 
-0061 switch reactionType
-0062     case {'both','all'} % For legacy reasons, 'both' is also allowed
-0063         exchangeRxnsIndexes = allExch;
-0064     case 'in'
-0065         exchangeRxnsIndexes = hasNoSubs;
-0066     case 'out'
-0067         exchangeRxnsIndexes = hasNoProd;
-0068     case 'blocked'
-0069         exchangeRxnsIndexes = allExch(model.lb(allExch) == 0 & model.ub(allExch) == 0);
-0070     case 'reverse'
-0071         exchangeRxnsIndexes = allExch(model.lb(allExch) < 0 & model.ub(allExch) > 0);
-0072     case 'uptake'
-0073         
-0074         exchangeRxnsIndexes = allExch([(model.lb(hasNoProd) < 0 & model.ub(hasNoProd) <= 0); ...
-0075                               (model.lb(hasNoSubs) >= 0 & model.ub(hasNoSubs) > 0)]);
-0076     case 'excrete'
-0077         exchangeRxnsIndexes = allExch([(model.lb(hasNoProd) >= 0 & model.ub(hasNoProd) > 0); ...
-0078                               (model.lb(hasNoSubs) < 0 & model.ub(hasNoSubs) <= 0)]);
-0079     otherwise
-0080         error('Invalid reactionType specified')
-0081 end
-0082 exchangeRxnsIndexes = sort(exchangeRxnsIndexes);
-0083 exchangeRxns = model.rxns(exchangeRxnsIndexes);
-0084 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/getExpressionStructure.html b/doc/core/getExpressionStructure.html deleted file mode 100644 index 2074991b2..000000000 --- a/doc/core/getExpressionStructure.html +++ /dev/null @@ -1,180 +0,0 @@ - - - - Description of getExpressionStructure - - - - - - - - - -
Home > core > getExpressionStructure.m
- - - -

getExpressionStructure -

- -

PURPOSE ^

-
getExpressionStructure
- -

SYNOPSIS ^

-
function experiment=getExpressionStructure(fileName)
- -

DESCRIPTION ^

-
 getExpressionStructure
-   Loads a representation of an experiment from an Excel file (see
-   comments further down)
-
-   fileName            an Excel representation on an experiment
-
-   experiment          an experiment structure
-       data            matrix with expression values
-       orfs            the corresponding ORFs
-       experiments     the titles of the experiments
-       boundNames      reaction names for the bounds
-       upperBoundaries matrix with the upper bound values
-       fitNames        reaction names for the measured fluxes
-       fitTo           matrix with the measured fluxes
-
-   A very common data set when working with genome-scale metabolic models
-   is that you have measured fermentation data, gene expression data,
-   and some different 'bounds' (for example different carbon sources
-   or genes that are knocked out) in a number of conditions. This function
-   reads an Excel representation of such an experiment.
-   The Excel file must contain three sheets, 'EXPRESSION', 'BOUNDS',
-   'FITTING'. Below are some examples to show how they should be
-   formatted:
-
-   -EXPRESSION
-       ORF    dsm_paa    wisc_paa
-       Pc00e00030    79.80942723    78.14755338
-   Shows the expression of the gene Pc00e00030 under two different
-   conditions (in this case a DSM strain and a Wisconsin strain of P.
-   chrysogenum with PSS in the media)
-
-   -BOUNDS
-       Fixed Upper    dsm_paa    wisc_paa
-       paaIN    0.1    0.2
-   The upper bound for the reaction paaIN should be 0.1 for the first
-   condition and 0.2 for the second
-
-   -FITTING
-       Fit to    dsm_paa    wisc_paa
-       co2OUT    2.85    3.05
-       glcIN   1.2     0.9
-   The measured fluxes for CO2 production and glucose uptake for the two
-   conditions. The model(s) can later be fitted to match these values as
-   good as possible.
-
- Usage: experiment=getExpressionStructure(fileName)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function experiment=getExpressionStructure(fileName)
-0002 % getExpressionStructure
-0003 %   Loads a representation of an experiment from an Excel file (see
-0004 %   comments further down)
-0005 %
-0006 %   fileName            an Excel representation on an experiment
-0007 %
-0008 %   experiment          an experiment structure
-0009 %       data            matrix with expression values
-0010 %       orfs            the corresponding ORFs
-0011 %       experiments     the titles of the experiments
-0012 %       boundNames      reaction names for the bounds
-0013 %       upperBoundaries matrix with the upper bound values
-0014 %       fitNames        reaction names for the measured fluxes
-0015 %       fitTo           matrix with the measured fluxes
-0016 %
-0017 %   A very common data set when working with genome-scale metabolic models
-0018 %   is that you have measured fermentation data, gene expression data,
-0019 %   and some different 'bounds' (for example different carbon sources
-0020 %   or genes that are knocked out) in a number of conditions. This function
-0021 %   reads an Excel representation of such an experiment.
-0022 %   The Excel file must contain three sheets, 'EXPRESSION', 'BOUNDS',
-0023 %   'FITTING'. Below are some examples to show how they should be
-0024 %   formatted:
-0025 %
-0026 %   -EXPRESSION
-0027 %       ORF    dsm_paa    wisc_paa
-0028 %       Pc00e00030    79.80942723    78.14755338
-0029 %   Shows the expression of the gene Pc00e00030 under two different
-0030 %   conditions (in this case a DSM strain and a Wisconsin strain of P.
-0031 %   chrysogenum with PSS in the media)
-0032 %
-0033 %   -BOUNDS
-0034 %       Fixed Upper    dsm_paa    wisc_paa
-0035 %       paaIN    0.1    0.2
-0036 %   The upper bound for the reaction paaIN should be 0.1 for the first
-0037 %   condition and 0.2 for the second
-0038 %
-0039 %   -FITTING
-0040 %       Fit to    dsm_paa    wisc_paa
-0041 %       co2OUT    2.85    3.05
-0042 %       glcIN   1.2     0.9
-0043 %   The measured fluxes for CO2 production and glucose uptake for the two
-0044 %   conditions. The model(s) can later be fitted to match these values as
-0045 %   good as possible.
-0046 %
-0047 % Usage: experiment=getExpressionStructure(fileName)
-0048 
-0049 [type, sheets]=xlsfinfo(fileName);
-0050 
-0051 %Check if the file is a Microsoft Excel Spreadsheet
-0052 if ~strcmp(type,'Microsoft Excel Spreadsheet')
-0053     EM='The file is not a Microsoft Excel Spreadsheet';
-0054     dispEM(EM);
-0055 end
-0056 
-0057 %Check that all sheets are present and saves the index of each
-0058 exprSheet=find(strcmp('EXPRESSION', sheets));
-0059 boundSheet=find(strcmp('BOUNDS', sheets));
-0060 fitSheet=find(strcmp('FITTING', sheets));
-0061 
-0062 if length(exprSheet)~=1 || length(boundSheet)~=1 || length(fitSheet)~=1
-0063     EM='Not all required spreadsheets are present in the file';
-0064     dispEM(EM);
-0065 end
-0066 
-0067 %Load the expression data
-0068 [discard,dataSheet]=xlsread(fileName,exprSheet);
-0069 experiment.data=discard;
-0070 experiment.orfs=dataSheet(2:size(dataSheet,1),1);
-0071 experiment.experiments=dataSheet(1,2:size(dataSheet,2));
-0072 
-0073 %Loads the maximal boundaries
-0074 [discard,dataSheet]=xlsread(fileName,boundSheet);
-0075 experiment.boundNames=dataSheet(2:size(dataSheet,1),1);
-0076 experiment.upperBoundaries=discard;
-0077 
-0078 %Loads the experimental data to fit to
-0079 [discard,dataSheet]=xlsread(fileName,fitSheet);
-0080 experiment.fitNames=dataSheet(2:size(dataSheet,1),1);
-0081 experiment.fitTo=discard;
-0082 
-0083 %Check to see that the dimensions are correct
-0084 if length(experiment.orfs)~=size(experiment.data,1) || (length(experiment.experiments)~=size(experiment.data,2) && ~isempty(experiment.data))
-0085     EM='The expression data does not seem to be formated in the expected manner';
-0086     dispEM(EM);
-0087 end
-0088 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/getFluxZ.html b/doc/core/getFluxZ.html deleted file mode 100644 index 066e68497..000000000 --- a/doc/core/getFluxZ.html +++ /dev/null @@ -1,120 +0,0 @@ - - - - Description of getFluxZ - - - - - - - - - -
Home > core > getFluxZ.m
- - - -

getFluxZ -

- -

PURPOSE ^

-
getFluxZ
- -

SYNOPSIS ^

-
function Z=getFluxZ(solutionsA, solutionsB)
- -

DESCRIPTION ^

-
 getFluxZ
-   Calculates the Z scores between two sets of random flux distributions.
-
-   solutionsA      random solutions for the reference condition (as
-                   generated by randomSampling)
-   solutionsB      random solutions for the test condition (as generated
-                   by randomSampling)
-
-   Z               a vector with Z-scores that tells you for each reaction
-                   how likely it is for its flux to have increased (positive sign)
-                   or decreased (negative sign) in the second condition with
-                   respect to the first.
-
- Usage: Z=getFluxZ(solutionsA, solutionsB)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function Z=getFluxZ(solutionsA, solutionsB)
-0002 % getFluxZ
-0003 %   Calculates the Z scores between two sets of random flux distributions.
-0004 %
-0005 %   solutionsA      random solutions for the reference condition (as
-0006 %                   generated by randomSampling)
-0007 %   solutionsB      random solutions for the test condition (as generated
-0008 %                   by randomSampling)
-0009 %
-0010 %   Z               a vector with Z-scores that tells you for each reaction
-0011 %                   how likely it is for its flux to have increased (positive sign)
-0012 %                   or decreased (negative sign) in the second condition with
-0013 %                   respect to the first.
-0014 %
-0015 % Usage: Z=getFluxZ(solutionsA, solutionsB)
-0016 
-0017 nRxns=size(solutionsA,1);
-0018 
-0019 %Check that the number of reactions is the same in both cases
-0020 if nRxns~=size(solutionsB,1)
-0021     EM='The number of reactions must be the same in solutionsA as in solutionsB';
-0022     dispEM(EM);
-0023 end
-0024 
-0025 Z=zeros(nRxns,1);
-0026 
-0027 %Calculate the mean and standard deviation for the two cases
-0028 mA=mean(solutionsA,2);
-0029 mB=mean(solutionsB,2);
-0030 
-0031 %This can lead to OUT OF MEMORY, so do it in segments of 500 reactions
-0032 varA=zeros(size(solutionsA,1),1);
-0033 for i=1:500:size(solutionsA,1)
-0034     varA(i:min(i+499,size(solutionsA,1)))=var(solutionsA(i:min(i+499,size(solutionsA,1)),:),0,2);
-0035 end
-0036 varB=zeros(size(solutionsB,1),1);
-0037 for i=1:500:size(solutionsB,1)
-0038     varB(i:min(i+499,size(solutionsB,1)))=var(solutionsB(i:min(i+499,size(solutionsB,1)),:),0,2);
-0039 end
-0040 
-0041 %If the mean of both solutions are the same then the Z-score is zero
-0042 toCheck=mA~=mB;
-0043 
-0044 %If the variance is zero in both cases, then put a very large or very small
-0045 %Z-score for the corresponding reactions
-0046 I=find(varA==0 & varB==0 & toCheck==true);
-0047 toCheck(I)=false;
-0048 J=mA(I)>mB(I);
-0049 Z(I(J))=100;
-0050 Z(I(~J))=-100;
-0051 toCheck=find(toCheck);
-0052 
-0053 for i=1:numel(toCheck)
-0054     Z(toCheck(i))=(mB(toCheck(i))-mA(toCheck(i)))/sqrt(varA(toCheck(i))+varB(toCheck(i)));
-0055 end
-0056 
-0057 %Shrink very large values
-0058 Z=min(Z,100);
-0059 Z=max(Z,-100);
-0060 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/getGenesFromGrRules.html b/doc/core/getGenesFromGrRules.html deleted file mode 100644 index 011069b86..000000000 --- a/doc/core/getGenesFromGrRules.html +++ /dev/null @@ -1,141 +0,0 @@ - - - - Description of getGenesFromGrRules - - - - - - - - - -
Home > core > getGenesFromGrRules.m
- - - -

getGenesFromGrRules -

- -

PURPOSE ^

-
getGenesFromGrRules Extract gene list and rxnGeneMat from grRules array.
- -

SYNOPSIS ^

-
function [genes,rxnGeneMat] = getGenesFromGrRules(grRules, originalGenes)
- -

DESCRIPTION ^

-
getGenesFromGrRules  Extract gene list and rxnGeneMat from grRules array.
-
- USAGE:
-
-   [genes,rxnGeneMat] = getGenesFromGrRules(grRules, originalGenes);
-
- INPUTS:
-
-   grRules     A cell array of model grRules, from which a list of genes
-               are to be extracted.
-               NOTE: Boolean operators can be text ("and", "or") or
-                     symbolic ("&", "|"), but there must be a space
-                     between operators and gene names/IDs.
-   originalGenes     The original gene list from the model as reference
-
- OUTPUTS:
-
-   genes       A unique list of all gene IDs that appear in grRules.
-
-   rxnGeneMat  (Optional) A binary matrix indicating which genes
-               participate in each reaction, where rows correspond to
-               reactions (entries in grRules) and columns correspond to
-               genes.
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function [genes,rxnGeneMat] = getGenesFromGrRules(grRules, originalGenes)
-0002 %getGenesFromGrRules  Extract gene list and rxnGeneMat from grRules array.
-0003 %
-0004 % USAGE:
-0005 %
-0006 %   [genes,rxnGeneMat] = getGenesFromGrRules(grRules, originalGenes);
-0007 %
-0008 % INPUTS:
-0009 %
-0010 %   grRules     A cell array of model grRules, from which a list of genes
-0011 %               are to be extracted.
-0012 %               NOTE: Boolean operators can be text ("and", "or") or
-0013 %                     symbolic ("&", "|"), but there must be a space
-0014 %                     between operators and gene names/IDs.
-0015 %   originalGenes     The original gene list from the model as reference
-0016 %
-0017 % OUTPUTS:
-0018 %
-0019 %   genes       A unique list of all gene IDs that appear in grRules.
-0020 %
-0021 %   rxnGeneMat  (Optional) A binary matrix indicating which genes
-0022 %               participate in each reaction, where rows correspond to
-0023 %               reactions (entries in grRules) and columns correspond to
-0024 %               genes.
-0025 %
-0026 
-0027 
-0028 % handle input arguments
-0029 if nargin < 2
-0030     originalGenes = [];
-0031 end
-0032 
-0033 % check if the grRules use written or symbolic boolean operators
-0034 if any(contains(grRules,{' & ',' | '}))
-0035     % fix some potential missing spaces between parentheses and &/|
-0036     grRules = regexprep(grRules,'\)&',') &');   % ")&"  ->  ") &"
-0037     grRules = regexprep(grRules,'&\(','& (');   % "&("  ->  "& ("
-0038     grRules = regexprep(grRules,'\)\|',') |');  % ")|"  ->  ") |"
-0039     grRules = regexprep(grRules,'\|\(','| (');  % "|("  ->  "| ("
-0040 else
-0041     % fix some potential missing spaces between parentheses and AND/OR
-0042     grRules = regexprep(grRules,'\)and',') and');  % ")and" ->  ") and"
-0043     grRules = regexprep(grRules,'and\(','and (');  % "and(" ->  "and ("
-0044     grRules = regexprep(grRules,'\)or',') or');    % ")or"  ->  ") or"
-0045     grRules = regexprep(grRules,'or\(','or (');    % "or("  ->  "or ("
-0046     
-0047     % convert "and" to "&" and "or" to "|" (easier to work with symbols)
-0048     grRules = regexprep(grRules, ' or ', ' | ');
-0049     grRules = regexprep(grRules, ' and ', ' & ');
-0050 end
-0051 
-0052 % extract list of genes from each reaction
-0053 rxnGenes = cellfun(@(r) regexprep(unique(strsplit(r,{' | ',' & '})),'[\(\) ]+',''),grRules,'UniformOutput',false);
-0054 
-0055 % construct new gene list
-0056 nonEmpty = ~cellfun(@isempty,rxnGenes);
-0057 genes = unique(transpose([rxnGenes{nonEmpty}]));
-0058 genes(cellfun(@isempty,genes)) = [];
-0059 
-0060 if ~isempty(originalGenes)
-0061     if ~isequal(sort(originalGenes), sort(genes))
-0062         error('The grRules and original gene list are inconsistent!');
-0063     else
-0064         genes = originalGenes;
-0065     end
-0066 end
-0067 
-0068 % construct new rxnGeneMat (if requested)
-0069 if nargout > 1
-0070     rxnGeneCell = cellfun(@(rg) ismember(genes,rg),rxnGenes,'UniformOutput',false);
-0071     rxnGeneMat = sparse(double(horzcat(rxnGeneCell{:})'));
-0072 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/getIndexes.html b/doc/core/getIndexes.html deleted file mode 100644 index ba86441e3..000000000 --- a/doc/core/getIndexes.html +++ /dev/null @@ -1,201 +0,0 @@ - - - - Description of getIndexes - - - - - - - - - -
Home > core > getIndexes.m
- - - -

getIndexes -

- -

PURPOSE ^

-
getIndexes
- -

SYNOPSIS ^

-
function indexes=getIndexes(model, objects, type, returnLogical)
- -

DESCRIPTION ^

-
 getIndexes
-   Retrieves the indexes for a list of reactions or metabolites
-
- Input:
-   model           a model structure
-   objects         either a cell array of IDs, a logical vector with the
-                   same number of elements as metabolites in the model,
-                   of a vector of indexes
-   type            'rxns', 'mets', or 'genes' depending on what to retrieve
-                   'metnames' queries metabolite names, while 'metcomps'
-                   allows to provide specific metabolites and their
-                   compartments in the format metaboliteName[comp]. If a
-                   model.ec structure exists (GECKO 3), then also
-                   'ecenzymes', 'ecrxns' and 'ecgenes' are allowed
-   returnLogical   Sets whether to return a logical array or an array with
-                   the indexes (optional, default false)
-
- Output:
-   indexes         can be a logical array or a double array depending on
-                   the value of returnLogical
-
- Note: If 'ecenzymes', 'ecrxns' or 'ecgenes' are used with a GECKO 3
- model, then the indexes are from the model.ec.enzymes, model.ec.rxns or
- model.ec.genes fields, respectively.
- 
- Usage: indexes=getIndexes(model, objects, type, returnLogical)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function indexes=getIndexes(model, objects, type, returnLogical)
-0002 % getIndexes
-0003 %   Retrieves the indexes for a list of reactions or metabolites
-0004 %
-0005 % Input:
-0006 %   model           a model structure
-0007 %   objects         either a cell array of IDs, a logical vector with the
-0008 %                   same number of elements as metabolites in the model,
-0009 %                   of a vector of indexes
-0010 %   type            'rxns', 'mets', or 'genes' depending on what to retrieve
-0011 %                   'metnames' queries metabolite names, while 'metcomps'
-0012 %                   allows to provide specific metabolites and their
-0013 %                   compartments in the format metaboliteName[comp]. If a
-0014 %                   model.ec structure exists (GECKO 3), then also
-0015 %                   'ecenzymes', 'ecrxns' and 'ecgenes' are allowed
-0016 %   returnLogical   Sets whether to return a logical array or an array with
-0017 %                   the indexes (optional, default false)
-0018 %
-0019 % Output:
-0020 %   indexes         can be a logical array or a double array depending on
-0021 %                   the value of returnLogical
-0022 %
-0023 % Note: If 'ecenzymes', 'ecrxns' or 'ecgenes' are used with a GECKO 3
-0024 % model, then the indexes are from the model.ec.enzymes, model.ec.rxns or
-0025 % model.ec.genes fields, respectively.
-0026 %
-0027 % Usage: indexes=getIndexes(model, objects, type, returnLogical)
-0028 
-0029 if nargin<4
-0030     returnLogical=false;
-0031 end
-0032 
-0033 if ~islogical(objects) && ~isnumeric(objects)
-0034     objects=convertCharArray(objects);
-0035 end
-0036 type=char(type);
-0037 
-0038 indexes=[];
-0039 
-0040 switch type
-0041     case 'rxns'
-0042         searchIn=model.rxns;
-0043     case 'mets'
-0044         searchIn=model.mets;
-0045     case 'genes'
-0046         searchIn=model.genes;
-0047     case 'metnames'
-0048         searchIn=model.metNames;
-0049     case 'metcomps'
-0050         % If provided as metaboliteName[comp], then index search is quite
-0051         % different from general approach, and therefore coded separately.
-0052         mets=regexprep(objects,'(^.+)\[(.+)\]$','$1');
-0053         comps=regexprep(objects,'(^.+)\[(.+)\]$','$2');
-0054         indexes=zeros(1,numel(objects));
-0055         for i=1:numel(objects)
-0056             index=find(strcmp(mets(i),model.metNames));
-0057             index=index(strcmp(comps(i),model.comps(model.metComps(index))));
-0058             if ~isempty(index)
-0059                 indexes(i)=index;
-0060             else
-0061                 error(['Could not find object ' objects{i} ' in the model']);
-0062             end
-0063         end
-0064         indexes=indexes(:);
-0065         if returnLogical==true
-0066             tempIndexes=false(numel(model.mets),1);
-0067             tempIndexes(indexes)=true;
-0068             indexes=tempIndexes;
-0069         end
-0070         return %None of the remaining function needs to run if metcomps
-0071     case 'ecrxns'
-0072         if ~isfield(model,'ec')
-0073             error('Type %s cannot be used if no model.ec structure is present.',type)
-0074         end
-0075         searchIn=model.ec.rxns;
-0076     case 'ecenzymes'
-0077         if ~isfield(model,'ec')
-0078             error('Type %s cannot be used if no model.ec structure is present.',type)
-0079         end
-0080         searchIn=model.ec.enzymes;
-0081     case 'ecgenes'
-0082         if ~isfield(model,'ec')
-0083             error('Type %s cannot be used if no model.ec structure is present.',type)
-0084         end
-0085         searchIn=model.ec.genes;
-0086     otherwise
-0087         if contains(objects,{'rxns','mets','metnames','metcomps','genes','ecgenes','ecenzymes','ecrxns'})
-0088             error('The second and third parameter provided to run getIndexes are likely switched. Note that the second parameter is the object to find the index for, while the third parameter is the object type (''rxns'', ''mets'', ''metnames'', ''metcomps'', ''genes'', ''ecgenes'', ''ecenzymes'' or ''ecrxns'').')
-0089         else
-0090             error('Incorrect value of the ''type'' parameter. Allowed values are ''rxns'', ''mets'', ''metnames'', ''metcomps'', ''genes'', ''ecgenes'', ''ecenzymes'' or ''ecrxns''.');
-0091        end
-0092 end
-0093 
-0094 if iscell(objects)
-0095     for i=1:numel(objects)
-0096         index=find(strcmp(objects(i),searchIn));
-0097         if strcmpi(type,'metnames')
-0098             indexes{i}=index;
-0099         elseif ~isempty(index)
-0100             if length(index) > 1
-0101                 error('There are multiple instances of object "%s" in the model, while "%s" type should be unique', objects{i}, type)
-0102             end
-0103             indexes(i)=index;
-0104         else
-0105             error(['Could not find object ''' objects{i} ''' in the model']);
-0106         end
-0107     end
-0108 else
-0109     %Now it's either a logical (or 0/1) array or an array with indexes. We
-0110     %want it to be an array with indexes.
-0111     if all(objects)
-0112         %This gets weird if it's all 1
-0113         indexes=objects;
-0114     else
-0115         indexes=find(objects);
-0116     end
-0117 end
-0118 
-0119 if returnLogical==true
-0120     tempIndexes=false(numel(searchIn),1);
-0121     tempIndexes(indexes)=true;
-0122     indexes=tempIndexes;
-0123 end
-0124 
-0125 indexes=indexes(:);
-0126 if iscell(indexes) && length(indexes)==1
-0127     indexes=indexes{1};
-0128 end
-0129 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/getMetsInComp.html b/doc/core/getMetsInComp.html deleted file mode 100644 index be4480152..000000000 --- a/doc/core/getMetsInComp.html +++ /dev/null @@ -1,80 +0,0 @@ - - - - Description of getMetsInComp - - - - - - - - - -
Home > core > getMetsInComp.m
- - - -

getMetsInComp -

- -

PURPOSE ^

-
getMetsInComp
- -

SYNOPSIS ^

-
function [I, metNames]=getMetsInComp(model,comp)
- -

DESCRIPTION ^

-
 getMetsInComp
-   Gets the metabolites in a specified compartment
-
-   model       a model structure
-   comp        string with the compartment id
-
-   I           boolean vector of the metabolites
-   metNames    the names of the metabolites
-
- Usage: [I, metNames]=getMetsInComp(model,comp)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function [I, metNames]=getMetsInComp(model,comp)
-0002 % getMetsInComp
-0003 %   Gets the metabolites in a specified compartment
-0004 %
-0005 %   model       a model structure
-0006 %   comp        string with the compartment id
-0007 %
-0008 %   I           boolean vector of the metabolites
-0009 %   metNames    the names of the metabolites
-0010 %
-0011 % Usage: [I, metNames]=getMetsInComp(model,comp)
-0012 
-0013 comp=char(comp);
-0014 
-0015 J=find(ismember(upper(model.comps),upper(comp)));
-0016 
-0017 if numel(J)~=1
-0018     EM=['No unique match to compartment "' comp{1} '"'];
-0019     dispEM(EM);
-0020 end
-0021 
-0022 I=model.metComps==J;
-0023 metNames=model.metNames(I);
-0024 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/getMinNrFluxes.html b/doc/core/getMinNrFluxes.html deleted file mode 100644 index 62a6847d9..000000000 --- a/doc/core/getMinNrFluxes.html +++ /dev/null @@ -1,237 +0,0 @@ - - - - Description of getMinNrFluxes - - - - - - - - - -
Home > core > getMinNrFluxes.m
- - - -

getMinNrFluxes -

- -

PURPOSE ^

-
getMinNrFluxes
- -

SYNOPSIS ^

-
function [x,I,exitFlag]=getMinNrFluxes(model, toMinimize, params,scores)
- -

DESCRIPTION ^

-
 getMinNrFluxes
-   Returns the minimal set of fluxes that satisfy the model using
-   mixed integer linear programming.
-
-    model         a model structure
-   toMinimize    either a cell array of reaction IDs, a logical vector
-                 with the same number of elements as reactions in the model,
-                 of a vector of indexes for the reactions that should be
-                 minimized (optional, default model.rxns)
-   params        *obsolete option*
-   scores        vector of weights for the reactions. Negative scores
-                 should not have flux. Positive scores are not possible in this
-                 implementation, and they are changed to max(scores(scores<0)).
-                 Must have the same dimension as toMinimize (find(toMinimize)
-                 if it is a logical vector) (optional, default -1 for all reactions)
-
-   x             the corresponding fluxes for the full model
-   I             the indexes of the reactions in toMinimize that were used
-                 in the solution
-   exitFlag      1: optimal solution found
-                -1: no feasible solution found
-                -2: optimization time out
-
-   NOTE: Uses 1000 mmol/gDW/h as an arbitary large flux. Could possibly
-   cause problems if the fluxes in the model are larger than that.
-
- Usage: [x,I,exitFlag]=getMinNrFluxes(model, toMinimize, params, scores)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function [x,I,exitFlag]=getMinNrFluxes(model, toMinimize, params,scores)
-0002 % getMinNrFluxes
-0003 %   Returns the minimal set of fluxes that satisfy the model using
-0004 %   mixed integer linear programming.
-0005 %
-0006 %    model         a model structure
-0007 %   toMinimize    either a cell array of reaction IDs, a logical vector
-0008 %                 with the same number of elements as reactions in the model,
-0009 %                 of a vector of indexes for the reactions that should be
-0010 %                 minimized (optional, default model.rxns)
-0011 %   params        *obsolete option*
-0012 %   scores        vector of weights for the reactions. Negative scores
-0013 %                 should not have flux. Positive scores are not possible in this
-0014 %                 implementation, and they are changed to max(scores(scores<0)).
-0015 %                 Must have the same dimension as toMinimize (find(toMinimize)
-0016 %                 if it is a logical vector) (optional, default -1 for all reactions)
-0017 %
-0018 %   x             the corresponding fluxes for the full model
-0019 %   I             the indexes of the reactions in toMinimize that were used
-0020 %                 in the solution
-0021 %   exitFlag      1: optimal solution found
-0022 %                -1: no feasible solution found
-0023 %                -2: optimization time out
-0024 %
-0025 %   NOTE: Uses 1000 mmol/gDW/h as an arbitary large flux. Could possibly
-0026 %   cause problems if the fluxes in the model are larger than that.
-0027 %
-0028 % Usage: [x,I,exitFlag]=getMinNrFluxes(model, toMinimize, params, scores)
-0029 
-0030 exitFlag=1;
-0031 
-0032 if nargin<2
-0033     toMinimize=model.rxns;
-0034 elseif ~islogical(toMinimize) && ~isnumeric(toMinimize)
-0035     toMinimize=convertCharArray(toMinimize);
-0036 else
-0037     toMinimize=model.rxns(toMinimize);
-0038 end
-0039 
-0040 %For passing parameters to the solver
-0041 if nargin<3
-0042     params=struct();
-0043 end
-0044 
-0045 if nargin<4
-0046     %It says that the default is -1, but that is to fit with other code
-0047     scores=ones(numel(toMinimize),1)*1;
-0048 else
-0049     if numel(scores)~=numel(toMinimize)
-0050         EM='The number of scores must be the same as the number of reactions to minimize';
-0051         dispEM(EM);
-0052     end
-0053     
-0054     %Change positive scores to have a small negative weight. This is a
-0055     %temporary solution.
-0056     scores(scores>=0)=max(scores(scores<0));
-0057     
-0058     %It says that the default is -1, but that is to fit with other code
-0059     scores=scores*-1;
-0060 end
-0061 
-0062 %Check if the model is in irreversible format
-0063 if any(model.rev)
-0064     %Convert the model to irreversible format
-0065     irrevModel=convertToIrrev(model);
-0066     
-0067     %Find the indexes for the reactions in toMinimize
-0068     [indexes, I]=ismember(strrep(irrevModel.rxns,'_REV',''),toMinimize);
-0069 else
-0070     irrevModel=model;
-0071     
-0072     %Find the indexes for the reactions in toMinimize
-0073     [indexes, I]=ismember(irrevModel.rxns,toMinimize);
-0074 end
-0075 
-0076 indexes=find(indexes);
-0077 %Adjust scores to fit with reversible
-0078 scores=scores(I(indexes));
-0079 
-0080 %Add binary constraints in the following manner: -  Add one unique
-0081 %"metabolite" for each integer reaction as a substrate.
-0082 %   These metabolites can have net production
-0083 %-  Add reactions for the production of each of those metabolites. The
-0084 %   amount produced in one reaction unit must be larger than the largest
-0085 %   possible flux in the model (but not too large to avoid bad scaling)
-0086 
-0087 %Calculate a solution to the problem without any constraints. This is to
-0088 %get an estimate about the magnitude of fluxes in the model and to get a
-0089 %feasible start solution.
-0090 sol=solveLP(irrevModel,1);
-0091 
-0092 %Return an empty solution if the non-constrained problem couldn't be solved
-0093 if isempty(sol.x)
-0094     x=[];
-0095     I=[];
-0096     exitFlag=-1;
-0097     return;
-0098 end
-0099 
-0100 %Take the maximal times 5 to have a safe margin. If it's smaller than 1000,
-0101 %then use 1000 instead.
-0102 maxFlux=max(max(sol.x)*5,1000);
-0103 
-0104 intArray=speye(numel(irrevModel.rxns))*-1;
-0105 intArray=intArray(indexes,:);
-0106 prob.a=[irrevModel.S;intArray];
-0107 a=[sparse(numel(irrevModel.mets),numel(indexes));speye(numel(indexes))*maxFlux];
-0108 prob.a=[prob.a a];
-0109 prob.ints.sub=numel(irrevModel.rxns)+1:numel(irrevModel.rxns)+numel(indexes);
-0110 
-0111 prob.c=[zeros(numel(irrevModel.rxns),1);scores(:);zeros(size(prob.a,1),1)]; %Minimize the number of fluxes
-0112 prob.A=[prob.a -speye(size(prob.a,1))];
-0113 prob.blc=[irrevModel.b(:,1);zeros(numel(indexes),1)];
-0114 if size(irrevModel.b,2)==2
-0115     prob.buc=[irrevModel.b(:,2);inf(numel(indexes),1)];
-0116 else
-0117     prob.buc=[irrevModel.b(:,1);inf(numel(indexes),1)];
-0118 end
-0119 prob.blx=[irrevModel.lb;zeros(numel(indexes),1)];
-0120 prob.bux=[irrevModel.ub;ones(numel(indexes),1)];
-0121 prob.lb = [prob.blx; prob.blc];
-0122 prob.ub = [prob.bux; prob.buc];
-0123 prob.osense=1;
-0124 prob.csense=repmat('E', 1, size(prob.a,1),1);
-0125 prob.b=zeros(size(prob.a,1), 1);
-0126 
-0127 %Use the output from the linear solution as starting point. Only the values
-0128 %for the integer variables will be used, but all are supplied.
-0129 prob.sol.int.xx=zeros(numel(prob.c),1);
-0130 prob.sol.int.xx(prob.ints.sub(sol.x(indexes)>10^-12))=1;
-0131 prob.x0=[];
-0132 prob.vartype=repmat('C', size(prob.A,2), 1);
-0133 prob.vartype(prob.ints.sub) = 'I'; % with .lb = 0 and .ub = 1, they are binary
-0134 % integers (glpk in octave only allows 'continuous' or '', not 'binary')
-0135 prob=rmfield(prob,{'blx','bux','blc','buc'});
-0136 
-0137 % Optimize the problem
-0138 res = optimizeProb(prob,params,false);
-0139 isFeasible=checkSolution(res);
-0140 
-0141 if ~isFeasible
-0142     x=[];
-0143     I=[];
-0144     exitFlag=-1;
-0145     return;
-0146 end
-0147 
-0148 xx=res.full(1:numel(irrevModel.rxns));
-0149 I=res.full(numel(xx)+1:end);
-0150 
-0151 %Check if Mosek aborted because it reached the time limit
-0152 %TODO: modify for cobra/gurobi
-0153 % if strcmp('MSK_RES_TRM_MAX_TIME',res.rcode)
-0154 %     exitFlag=-2;
-0155 % end
-0156 
-0157 %Map back to original model from irrevModel
-0158 x=xx(1:numel(model.rxns));
-0159 if numel(irrevModel.rxns)>numel(model.rxns)
-0160     x(model.rev~=0)=x(model.rev~=0)-xx(numel(model.rxns)+1:end);
-0161 end
-0162 
-0163 I=ismember(toMinimize,strrep(irrevModel.rxns(indexes(I>10^-12)),'_REV',''));
-0164 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/getModelFromHomology.html b/doc/core/getModelFromHomology.html deleted file mode 100644 index 5291424f9..000000000 --- a/doc/core/getModelFromHomology.html +++ /dev/null @@ -1,663 +0,0 @@ - - - - Description of getModelFromHomology - - - - - - - - - -
Home > core > getModelFromHomology.m
- - - -

getModelFromHomology -

- -

PURPOSE ^

-
getModelFromHomology
- -

SYNOPSIS ^

-
function [draftModel, hitGenes]=getModelFromHomology(models,blastStructure,getModelFor,preferredOrder,strictness,onlyGenesInModels,maxE,minLen,minIde,mapNewGenesToOld)
- -

DESCRIPTION ^

-
 getModelFromHomology
-   Constructs a new model from a set of existing models and gene homology
-   information.
-
-   models            a cell array of model structures to build the model
-                     from. These models must be sorted by importance in
-                     decreasing order
-   blastStructure    a blastStructure as produced by getBlast or
-                     getBlastFromExcel
-   getModelFor       a three-four letter abbreviation of the organism to
-                     build a model for. Must have BLASTP hits in both
-                     directions to the organisms in 'models'
-   preferredOrder    the order in which reactions should be added from the
-                     models. If not supplied, reactions will be included
-                     from all models, otherwise one gene will only result
-                     in reactions from one model (optional, default {})
-   strictness        integer that specifies which reactions should be
-                     included:
-                     1: Map new genes to old for all pairs, which have
-                     acceptable BLASTP results in both directions
-                     2: Map new genes to old for all pairs, which have
-                     acceptable BLASTP results in correspondent direction
-                     (mapping can be done in the opposite direction, see
-                     mapNewGenesToOld below)
-                     3: Check all BLASTP results and retain only the best
-                     results by E-value for all gene pairs in each
-                     direction separately. Then map new genes to old for
-                     all pairs, which have acceptable BLASTP results in
-                     both directions (optional, default 1).
-   onlyGenesInModels consider BLASTP results only for genes that exist in
-                     the models. This tends to import a larger fraction
-                     from the existing models but may give less reliable
-                     results. Has effect only if strictness=3 (optional,
-                     default false)
-   maxE              only look at genes with E-values <= this value (optional,
-                     default 10^-30)
-   minLen            only look at genes with alignment length >= this
-                     value (optional, default 200)
-   minIde            only look at genes with identity >= this value
-                     (optional, default 40 (%))
-   mapNewGenesToOld  determines how to match genes if not looking at only
-                     1-1 orthologs. Either map the new genes to the old or
-                     old genes to new. The default is to map the new genes
-                     (optional, default true)
-
-   draftModel        a model structure for the new organism
-   hitGenes          collect the old and new genes
-
-   The models in the 'models' structure should have named the metabolites
-   in the same manner, have their reversible reactions in the same
-   direction (run sortModel), and use the same compartment names. To avoid
-   keeping unneccesary old genes, the models should not have
-   'or'-relations in their grRules (use expandModel).
-
-   The resulting draft model contains only reactions associated with
-   orthologous genes. The old (original) genes involved in 'and'
-   relations in grRules without any orthologs are still included in
-   the draft model as OLD_MODELID_geneName.
-
-   NOTE: "to" and "from" means relative to the new organism
-
- Usage: draftModel=getModelFromHomology(models,blastStructure,...
-    getModelFor,preferredOrder,strictness,onlyGenesInModels,maxE,...
-    minLen,minIde,mapNewGenesToOld)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function [draftModel, hitGenes]=getModelFromHomology(models,blastStructure,...
-0002     getModelFor,preferredOrder,strictness,onlyGenesInModels,maxE,...
-0003     minLen,minIde,mapNewGenesToOld)
-0004 % getModelFromHomology
-0005 %   Constructs a new model from a set of existing models and gene homology
-0006 %   information.
-0007 %
-0008 %   models            a cell array of model structures to build the model
-0009 %                     from. These models must be sorted by importance in
-0010 %                     decreasing order
-0011 %   blastStructure    a blastStructure as produced by getBlast or
-0012 %                     getBlastFromExcel
-0013 %   getModelFor       a three-four letter abbreviation of the organism to
-0014 %                     build a model for. Must have BLASTP hits in both
-0015 %                     directions to the organisms in 'models'
-0016 %   preferredOrder    the order in which reactions should be added from the
-0017 %                     models. If not supplied, reactions will be included
-0018 %                     from all models, otherwise one gene will only result
-0019 %                     in reactions from one model (optional, default {})
-0020 %   strictness        integer that specifies which reactions should be
-0021 %                     included:
-0022 %                     1: Map new genes to old for all pairs, which have
-0023 %                     acceptable BLASTP results in both directions
-0024 %                     2: Map new genes to old for all pairs, which have
-0025 %                     acceptable BLASTP results in correspondent direction
-0026 %                     (mapping can be done in the opposite direction, see
-0027 %                     mapNewGenesToOld below)
-0028 %                     3: Check all BLASTP results and retain only the best
-0029 %                     results by E-value for all gene pairs in each
-0030 %                     direction separately. Then map new genes to old for
-0031 %                     all pairs, which have acceptable BLASTP results in
-0032 %                     both directions (optional, default 1).
-0033 %   onlyGenesInModels consider BLASTP results only for genes that exist in
-0034 %                     the models. This tends to import a larger fraction
-0035 %                     from the existing models but may give less reliable
-0036 %                     results. Has effect only if strictness=3 (optional,
-0037 %                     default false)
-0038 %   maxE              only look at genes with E-values <= this value (optional,
-0039 %                     default 10^-30)
-0040 %   minLen            only look at genes with alignment length >= this
-0041 %                     value (optional, default 200)
-0042 %   minIde            only look at genes with identity >= this value
-0043 %                     (optional, default 40 (%))
-0044 %   mapNewGenesToOld  determines how to match genes if not looking at only
-0045 %                     1-1 orthologs. Either map the new genes to the old or
-0046 %                     old genes to new. The default is to map the new genes
-0047 %                     (optional, default true)
-0048 %
-0049 %   draftModel        a model structure for the new organism
-0050 %   hitGenes          collect the old and new genes
-0051 %
-0052 %   The models in the 'models' structure should have named the metabolites
-0053 %   in the same manner, have their reversible reactions in the same
-0054 %   direction (run sortModel), and use the same compartment names. To avoid
-0055 %   keeping unneccesary old genes, the models should not have
-0056 %   'or'-relations in their grRules (use expandModel).
-0057 %
-0058 %   The resulting draft model contains only reactions associated with
-0059 %   orthologous genes. The old (original) genes involved in 'and'
-0060 %   relations in grRules without any orthologs are still included in
-0061 %   the draft model as OLD_MODELID_geneName.
-0062 %
-0063 %   NOTE: "to" and "from" means relative to the new organism
-0064 %
-0065 % Usage: draftModel=getModelFromHomology(models,blastStructure,...
-0066 %    getModelFor,preferredOrder,strictness,onlyGenesInModels,maxE,...
-0067 %    minLen,minIde,mapNewGenesToOld)
-0068 
-0069 hitGenes.oldGenes = [];  % collect the old genes from the template model (organism)
-0070 hitGenes.newGenes = [];  % collect the new genes of the draft model (target organism)
-0071 
-0072 getModelFor=char(getModelFor);
-0073 
-0074 if nargin<4
-0075     preferredOrder=[];
-0076 else
-0077     preferredOrder=convertCharArray(preferredOrder);
-0078     [row,col]=size(preferredOrder);
-0079     if col>row
-0080         preferredOrder=transpose(preferredOrder);
-0081     end
-0082 end
-0083 if nargin<5
-0084     strictness=1;
-0085 end
-0086 if nargin<6
-0087     onlyGenesInModels=false;
-0088 end
-0089 if nargin<7
-0090     maxE=10^-30;
-0091 end
-0092 if nargin<8
-0093     minLen=200;
-0094 end
-0095 if nargin<9
-0096     minIde=40;
-0097 end
-0098 if nargin<10
-0099     mapNewGenesToOld=true;
-0100 end
-0101 
-0102 if isfield(models,'S')
-0103     models={models};
-0104 end
-0105     
-0106 %Check that all the information is in the blast structure
-0107 modelNames=cell(numel(models),1);
-0108 for i=1:numel(models)
-0109     modelNames{i}=models{i}.id;
-0110     %Gene short names, geneMiriams and proteins are often different
-0111     %between species, safer not to include them
-0112     if isfield(models{i},'geneShortNames')
-0113         models{i}=rmfield(models{i},'geneShortNames');
-0114     end
-0115     if isfield(models{i},'geneMiriams')
-0116         models{i}=rmfield(models{i},'geneMiriams');
-0117     end
-0118     if isfield(models{i},'proteins')
-0119         models{i}=rmfield(models{i},'proteins');
-0120     end
-0121     %The geneFrom field also loses meaning if the genes are replaced by
-0122     %orthologs
-0123     if isfield(models{i},'geneFrom')
-0124         models{i}=rmfield(models{i},'geneFrom');
-0125     end
-0126 end
-0127 
-0128 %Check that genes do not begin with ( or end with ), as this makes problematic grRules
-0129 for i=1:numel(blastStructure)
-0130     problemGenes = startsWith(blastStructure(i).fromGenes,'(') | endsWith(blastStructure(i).fromGenes,')');
-0131     if any(problemGenes)
-0132         error(['One or multiple gene identifiers from ' blastStructure(i).fromId ...
-0133                ' starts with ''('' and/or ends with '')'', which is not allowed'])
-0134     end
-0135 end
-0136 
-0137 %Assume for now that all information is there and that it's correct. This
-0138 %is important to fix since no further checks are being made!
-0139 
-0140 %Check whether provided fasta files use the same gene identifiers as
-0141 %provided template models
-0142 for i=1:numel(blastStructure)
-0143     if ~strcmp(blastStructure(i).fromId,getModelFor)
-0144         j=strcmpi(blastStructure(i).fromId,modelNames);
-0145         if j==0
-0146             error(['While the blastStructure contains sequences from '...
-0147                 'organismID "%s" (as\nprovided in getBlast), none of '...
-0148                 'template models have this id (as model.id)'],...
-0149                 string(blastStructure(i).fromId));
-0150         end
-0151         k=sum(ismember(blastStructure(i).fromGenes,models{j}.genes));
-0152         if k<(numel(models{j}.genes)*0.05)
-0153             error(['Less than 5%% of the genes in the template model '...
-0154                 'with model.id "%s"\ncan be found in the blastStructure. '...
-0155                 'Ensure that the protein FASTA\nused in getBlast and '...
-0156                 'the template model used in getModelFromHomology\nuse '...
-0157                 'the same style of gene identifiers'],models{j}.id)
-0158         end
-0159     end
-0160 end
-0161 
-0162 %Standardize grRules of template models
-0163 for i=1:length(models)
-0164     fprintf('\nStandardizing grRules of template model with ID "%s" ...',models{i}.id);
-0165     [models{i}.grRules,models{i}.rxnGeneMat]=standardizeGrRules(models{i},false);
-0166 end
-0167 fprintf(' done\n');
-0168 
-0169 %Remove all gene matches that are below the cutoffs
-0170 for i=1:numel(blastStructure)
-0171     indexes=blastStructure(i).evalue<maxE & blastStructure(i).aligLen>=minLen & blastStructure(i).identity>=minIde; %Do it in this direction to lose NaNs
-0172     blastStructure(i).fromGenes(~indexes)=[];
-0173     blastStructure(i).toGenes(~indexes)=[];
-0174     blastStructure(i).evalue(~indexes)=[];
-0175     blastStructure(i).identity(~indexes)=[];
-0176     blastStructure(i).aligLen(~indexes)=[];
-0177     blastStructure(i).bitscore(~indexes)=[];
-0178     blastStructure(i).ppos(~indexes)=[];
-0179 end
-0180 
-0181 %Remove all reactions from the models that have no genes encoding for them.
-0182 %Also remove all genes that encode for no reactions. There shouldn't be any
-0183 %but there might be mistakes
-0184 for i=1:numel(models)
-0185     [hasGenes, ~]=find(models{i}.rxnGeneMat);
-0186     hasNoGenes=1:numel(models{i}.rxns);
-0187     hasNoGenes(hasGenes)=[];
-0188     models{i}=removeReactions(models{i},hasNoGenes,true,true);
-0189 end
-0190 
-0191 %Create a structure that contains all genes used in the blasts in any
-0192 %direction for each of the models in 'models' and for the new organism. The
-0193 %first cell is for the new organism and then according to the preferred
-0194 %order. If no such order is supplied, then according to the order in
-0195 %'models'
-0196 allGenes=cell(numel(models)+1,1);
-0197 if isempty(preferredOrder)
-0198     useOrder=modelNames;
-0199 else
-0200     useOrder=preferredOrder;
-0201 end
-0202 
-0203 %Get the corresponding indexes for those models in the 'models' structure
-0204 useOrderIndexes=zeros(numel(models),1);
-0205 for i=1:numel(models)
-0206     [~, index]=ismember(models{i}.id,useOrder);
-0207     useOrderIndexes(index)=i;
-0208 end
-0209 
-0210 %Remove all genes from the blast structure that have no genes in the models
-0211 if onlyGenesInModels==true
-0212     modelGenes={};
-0213     for i=1:numel(models)
-0214         modelGenes=[modelGenes;models{i}.genes];
-0215     end
-0216     for i=1:numel(blastStructure)
-0217         %Check to see if it should match the toId or fromId
-0218         if strcmpi(blastStructure(i).fromId,getModelFor)
-0219             I=ismember(blastStructure(i).toGenes,modelGenes);
-0220         else
-0221             I=ismember(blastStructure(i).fromGenes,modelGenes);
-0222         end
-0223         blastStructure(i).fromGenes(~I)=[];
-0224         blastStructure(i).toGenes(~I)=[];
-0225         blastStructure(i).evalue(~I)=[];
-0226         blastStructure(i).identity(~I)=[];
-0227         blastStructure(i).aligLen(~I)=[];
-0228         blastStructure(i).bitscore(~I)=[];
-0229         blastStructure(i).ppos(~I)=[];
-0230         
-0231         %Check that no matching in blastStructure is empty. This happens if
-0232         %no genes in the models are present in the corresponding sheet
-0233         if isempty(blastStructure(i).fromGenes)
-0234             EM=['No genes in matching from ' blastStructure(i).fromId ' to ' blastStructure(i).toId ' are present in the corresponding model'];
-0235             dispEM(EM);
-0236         end
-0237     end
-0238 end
-0239 
-0240 %If only best orthologs are to be used then all other measurements are
-0241 %deleted from the blastStructure. All code after this stays the same. This
-0242 %means that preferred order can still matter. The best ortholog scoring is
-0243 %based only on the E-value
-0244 if strictness==3
-0245     for i=1:numel(blastStructure)
-0246         keep=false(numel(blastStructure(i).toGenes),1);
-0247         [allFromGenes, ~, I]=unique(blastStructure(i).fromGenes);
-0248         
-0249         %It would be nice to get rid of this loop
-0250         for j=1:numel(allFromGenes)
-0251             allMatches=find(I==j);
-0252             bestMatches=allMatches(blastStructure(i).evalue(allMatches)==min(blastStructure(i).evalue(allMatches)));
-0253             
-0254             %Keep the best matches
-0255             keep(bestMatches)=true;
-0256         end
-0257         
-0258         %Delete all matches that were not best matches
-0259         blastStructure(i).fromGenes(~keep)=[];
-0260         blastStructure(i).toGenes(~keep)=[];
-0261         blastStructure(i).evalue(~keep)=[];
-0262         blastStructure(i).identity(~keep)=[];
-0263         blastStructure(i).aligLen(~keep)=[];
-0264         blastStructure(i).bitscore(~keep)=[];
-0265         blastStructure(i).ppos(~keep)=[];
-0266     end
-0267 end
-0268 
-0269 useOrder=[{getModelFor};useOrder];
-0270 
-0271 for i=1:numel(blastStructure)
-0272     [~, toIndex]=ismember(blastStructure(i).toId,useOrder);
-0273     [~, fromIndex]=ismember(blastStructure(i).fromId,useOrder);
-0274     
-0275     %Add all genes to the corresponding list in allGenes
-0276     allGenes{toIndex}=[allGenes{toIndex};blastStructure(i).toGenes];
-0277     allGenes{fromIndex}=[allGenes{fromIndex};blastStructure(i).fromGenes];
-0278 end
-0279 
-0280 %Keep only the unique gene names
-0281 maxOtherGeneNr=0; %Determines the dimension of the connectivity matrixes
-0282 for i=1:numel(allGenes)
-0283     allGenes{i}=unique(allGenes{i});
-0284     if i>1
-0285         if numel(allGenes{i})>maxOtherGeneNr
-0286             maxOtherGeneNr=numel(allGenes{i});
-0287         end
-0288     end
-0289 end
-0290 
-0291 %Generate a cell array of matrixes that describes how the genes in the new
-0292 %organism map to the models. Each cell matches to the corresponding model
-0293 %in useOrder (starting at 2 of course). First dimension is gene in new
-0294 %organism, second which gene it is in the other organism. The second matrix
-0295 %describes how they map back.
-0296 
-0297 %As it is now, a significant match is indicated by a 1. This could be
-0298 %expanded to contain some kind of significance level. The first dimension
-0299 %is still the genes in the new model.
-0300 
-0301 allTo=cell(numel(useOrder)-1,1);
-0302 allFrom=cell(numel(useOrder)-1,1);
-0303 
-0304 for i=1:numel(useOrder)-1
-0305     allTo{i}=sparse(numel(allGenes{1}),numel(allGenes{i+1}));
-0306     allFrom{i}=sparse(numel(allGenes{1}),numel(allGenes{i+1}));
-0307 end
-0308 
-0309 %Fill the matches to other species
-0310 for i=1:numel(blastStructure)
-0311     if strcmp(blastStructure(i).toId,getModelFor)
-0312         %This was 'to' the new organism. They should all match so no checks
-0313         %are being made
-0314         [~, a]=ismember(blastStructure(i).toGenes,allGenes{1});
-0315         [~, fromModel]=ismember(blastStructure(i).fromId,useOrder);
-0316         [~, b]=ismember(blastStructure(i).fromGenes,allGenes{fromModel});
-0317         idx = sub2ind(size(allTo{fromModel-1}), a, b);
-0318         allTo{fromModel-1}(idx)=1;
-0319     else
-0320         %This was 'from' the new organism
-0321         [~, a]=ismember(blastStructure(i).fromGenes,allGenes{1});
-0322         [~, toModel]=ismember(blastStructure(i).toId,useOrder);
-0323         [~, b]=ismember(blastStructure(i).toGenes,allGenes{toModel});
-0324         idx = sub2ind(size(allFrom{toModel-1}), a, b);
-0325         allFrom{toModel-1}(idx)=1;
-0326     end
-0327 end
-0328 
-0329 %Now we have all the gene matches in a convenient way. For all the genes in
-0330 %the new organism get the genes that should be included from other
-0331 %organisms. If all genes should be included this simply means keep the
-0332 %allFrom matrix as it is. If only orthologs which could be mapped in both
-0333 %BLAST directions are to be included then only those elements are kept.
-0334 
-0335 finalMappings=cell(numel(useOrder)-1,1);
-0336 if strictness==1 || strictness==3
-0337     for j=1:numel(allFrom)
-0338         finalMappings{j}=allTo{j}~=0 & allFrom{j}~=0;
-0339     end
-0340 else
-0341     if mapNewGenesToOld==true
-0342         finalMappings=allFrom;
-0343     else
-0344         finalMappings=allTo;
-0345     end
-0346 end
-0347 
-0348 %Remove all genes from the mapping that are not in the models. This doesn't
-0349 %do much if only genes in the models were used for the original mapping.
-0350 %Also simplify the finalMapping and allGenes structures so that they only
-0351 %contain mappings that exist
-0352 usedNewGenes=false(numel(allGenes{1}),1);
-0353 
-0354 for i=1:numel(allGenes)-1
-0355     %First remove mappings for those genes that are not in the model
-0356     if onlyGenesInModels==false
-0357         a=ismember(allGenes{i+1},models{useOrderIndexes(i)}.genes);
-0358         finalMappings{i}(:,~a)=false;
-0359     end
-0360     
-0361     %Then remove unused ones and simplify
-0362     [a, b]=find(finalMappings{i});
-0363     usedGenes=false(numel(allGenes{i+1}),1);
-0364     usedNewGenes(a)=true;
-0365     usedGenes(b)=true;
-0366     finalMappings{i}=finalMappings{i}(:,usedGenes);
-0367     allGenes{i+1}=allGenes{i+1}(usedGenes);
-0368 end
-0369 
-0370 %Remove all new genes that have not been mapped to anything
-0371 allGenes{1}=allGenes{1}(usedNewGenes);
-0372 for i=1:numel(finalMappings)
-0373     finalMappings{i}=finalMappings{i}(usedNewGenes,:);
-0374 end
-0375 
-0376 %Now is it time to choose which reactions should be included from which
-0377 %models. If there is a preferred order specified then each gene can only
-0378 %result in reactions from one model, otherwise they should all be included
-0379 
-0380 %Start by simplifying the models by removing genes/reactions that are not
-0381 %used. This is where it gets weird with complexes, especially "or"
-0382 %complexes. In this step only reactions which are encoded by one single
-0383 %gene, or where all genes should be deleted, are deleted. The info on the
-0384 %full complex is still present in the grRules
-0385 
-0386 for i=1:numel(models)
-0387     a=ismember(models{useOrderIndexes(i)}.genes,allGenes{i+1});
-0388     
-0389     %Remove reactions that are not associated to any of the genes in
-0390     %allGenes, thereby also keeping complexes where only for one of the
-0391     %genes was matched
-0392     [rxnsToKeep,~] = find(models{useOrderIndexes(i)}.rxnGeneMat(:,a));
-0393     rxnsToRemove = repmat(1,numel(models{useOrderIndexes(i)}.rxns),1);
-0394     rxnsToRemove(rxnsToKeep) = 0;
-0395     rxnsToRemove = find(rxnsToRemove);
-0396     models{useOrderIndexes(i)}=removeReactions(models{useOrderIndexes(i)},rxnsToRemove,true,true,true);
-0397 end
-0398 
-0399 %Since mergeModels function will be used in the end, the models are
-0400 %simplified further by deleting genes/reactions in the order specified by
-0401 %preferredOrder. This means that the last model will only contain reactions
-0402 %for genes that mapped only to that model
-0403 
-0404 allUsedGenes=false(numel(allGenes{1}),1);
-0405 
-0406 if ~isempty(preferredOrder) && numel(models)>1
-0407     [usedGenes, ~]=find(finalMappings{1}); %All that are used in the first model in preferredOrder
-0408     allUsedGenes(usedGenes)=true;
-0409     for i=2:numel(finalMappings)
-0410         [usedGenes, ~]=find(finalMappings{i});
-0411         usedGenes=unique(usedGenes);
-0412         a=ismember(usedGenes,find(allUsedGenes));
-0413         
-0414         [~, genesToDelete]=find(finalMappings{i}(usedGenes(a),:)); %IMPORTANT! IS it really correct to remove all genes that map?
-0415         genesToDelete=unique(genesToDelete); %Maybe not needed, but for clarity if nothing else
-0416         
-0417         %Remove all the genes that were already found and add the other
-0418         %ones to allUsedGenes
-0419         models{useOrderIndexes(i)}=removeGenes(models{useOrderIndexes(i)},allGenes{i+1}(genesToDelete),true,true,false);
-0420         allUsedGenes(usedGenes)=true;
-0421         
-0422         %Remove the deleted genes from finalMappings and allGenes.
-0423         finalMappings{i}(:,genesToDelete)=[];
-0424         allGenes{i+1}(genesToDelete)=[];
-0425     end
-0426 end
-0427 
-0428 %Now loop through the models and update the gene associations. Genes not
-0429 %belonging to the new organism will be renamed as 'OLD_MODELID_gene'
-0430 for i=1:numel(models)
-0431     %Find all the new genes that should be used for this model
-0432     [newGenes, oldGenes]=find(finalMappings{i});
-0433     
-0434     %Create a new gene list with the genes from the new organism and those
-0435     %genes that could not be removed
-0436     replaceableGenes=allGenes{i+1}(unique(oldGenes));
-0437     nonReplaceableGenes=setdiff(models{useOrderIndexes(i)}.genes,replaceableGenes);
-0438     fullGeneList=[allGenes{1}(unique(newGenes));nonReplaceableGenes];
-0439     
-0440     %Just to save some indexing later. This is the LAST index of
-0441     %replaceable ones
-0442     nonRepStartIndex=numel(unique(newGenes));
-0443     
-0444     %Construct a new rxnGeneMat
-0445     newRxnGeneMat=sparse(numel(models{useOrderIndexes(i)}.rxns),numel(fullGeneList));
-0446     
-0447     %Now update the rxnGeneMat. This is a little tricky and could
-0448     %probably be done in a more efficient way, but I just loop through the
-0449     %reactions and add them one by one
-0450     for j=1:numel(models{useOrderIndexes(i)}.rxns)
-0451         %Get the old genes encoding for this reaction
-0452         [~, oldGeneIds]=find(models{useOrderIndexes(i)}.rxnGeneMat(j,:));
-0453         
-0454         %Update the matrix for each gene. This includes replacing one gene
-0455         %with several new ones if there were several matches
-0456         for k=1:numel(oldGeneIds)
-0457             %Match the gene to one in the gene list. This is done as a text
-0458             %match. Could probably be done better, but I'm a little lost in
-0459             %the indexing
-0460             
-0461             geneName=models{useOrderIndexes(i)}.genes(oldGeneIds(k));
-0462             
-0463             %First search in the mappable genes
-0464             mapIndex=find(ismember(allGenes{i+1},geneName));
-0465             
-0466             if ~isempty(mapIndex)
-0467                 % add the old genes
-0468                 hitGenes.oldGenes = [hitGenes.oldGenes, {geneName}];
-0469                 
-0470                 %Get the new genes for that gene
-0471                 a=find(finalMappings{i}(:,mapIndex));
-0472                 
-0473                 %Find the positions of these genes in the final gene list
-0474                 [~, b]=ismember(allGenes{1}(a),fullGeneList);
-0475                 
-0476                 %Update the matrix
-0477                 newRxnGeneMat(j,b)=1;
-0478                 
-0479                 %Update the grRules string. This is tricky, but I hope that
-0480                 %it's ok to replace the old gene name with the new one and
-0481                 %add ') or (' if there were several matches. Be sure of
-0482                 %this!
-0483                 repString=fullGeneList{b(1)};
-0484                 if numel(b)>1
-0485                     for l=2:numel(b)
-0486                         repString=[repString ' or ' fullGeneList{b(l)}];
-0487                     end
-0488                     repString=['(' repString ')'];
-0489                 end
-0490                 
-0491                 % add the new matched genes
-0492                 hitGenes.newGenes = [hitGenes.newGenes, {repString}];
-0493                 
-0494                 %Use regexprep instead of strrep to prevent partial matches
-0495                 models{useOrderIndexes(i)}.grRules{j}=regexprep(models{useOrderIndexes(i)}.grRules{j},['(^|\s|\()' geneName{1} '($|\s|\))'],['$1' repString '$2']);
-0496             else
-0497                 %Then search in the non-replaceable genes. There could only
-0498                 %be one match here
-0499                 index=find(ismember(nonReplaceableGenes,geneName));
-0500                 
-0501                 %Update the matrix
-0502                 newRxnGeneMat(j,nonRepStartIndex+index)=1;
-0503                 
-0504                 models{useOrderIndexes(i)}.grRules{j}=strrep(models{useOrderIndexes(i)}.grRules{j},geneName{1},strcat('OLD_',models{useOrderIndexes(i)}.id,'_',geneName{1}));
-0505             end
-0506         end
-0507     end
-0508     
-0509     %Add the new list of genes
-0510     models{useOrderIndexes(i)}.rxnGeneMat=newRxnGeneMat;
-0511     if ~isempty(nonReplaceableGenes)
-0512         models{useOrderIndexes(i)}.genes=[allGenes{1}(unique(newGenes));strcat('OLD_',models{useOrderIndexes(i)}.id,'_',nonReplaceableGenes)];
-0513     else
-0514         models{useOrderIndexes(i)}.genes=allGenes{1}(unique(newGenes));
-0515     end
-0516     if isfield(models{useOrderIndexes(i)},'geneComps')
-0517         geneComps=models{useOrderIndexes(i)}.geneComps(1);
-0518         models{useOrderIndexes(i)}.geneComps=zeros(numel(models{useOrderIndexes(i)}.genes),1);
-0519         %Assume that all genes are in the same compartment, and this
-0520         %compartment is specified for the first gene
-0521         models{useOrderIndexes(i)}.geneComps(:)=geneComps;
-0522     end
-0523 end
-0524 
-0525 %Now merge the models. All information should be correct except for 'or'
-0526 %complexes
-0527 draftModel=mergeModels(models,'metNames');
-0528 
-0529 %Remove unnecessary OLD_ genes, that were added with OR relationships
-0530 regexStr=['OLD_(', strjoin(modelNames(:),'|'),')_(\S^\))+'];
-0531 draftModel.grRules=regexprep(draftModel.grRules,[' or ' regexStr],'');
-0532 draftModel.grRules=regexprep(draftModel.grRules,[regexStr ' or '],'');
-0533 
-0534 %Change name of the resulting model
-0535 draftModel.id=getModelFor;
-0536 name='Generated by getModelFromHomology using ';
-0537 for i=1:numel(models)
-0538     if i<numel(models)
-0539         name=[name models{i}.id ', '];
-0540     else
-0541         name=[name models{i}.id];
-0542     end
-0543 end
-0544 draftModel.name=name;
-0545 draftModel.rxnNotes=cell(length(draftModel.rxns),1);
-0546 draftModel.rxnNotes(:)={'Included by getModelFromHomology'};
-0547 draftModel.rxnConfidenceScores=NaN(length(draftModel.rxns),1);
-0548 draftModel.rxnConfidenceScores(:)=2;
-0549 draftModel=deleteUnusedGenes(draftModel,0);
-0550 %Standardize grRules and notify if problematic grRules are found
-0551 [draftModel.grRules,draftModel.rxnGeneMat]=standardizeGrRules(draftModel,false);
-0552 draftModel=deleteUnusedGenes(draftModel,false);
-0553 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/getRxnsInComp.html b/doc/core/getRxnsInComp.html deleted file mode 100644 index 5de7d1f1b..000000000 --- a/doc/core/getRxnsInComp.html +++ /dev/null @@ -1,100 +0,0 @@ - - - - Description of getRxnsInComp - - - - - - - - - -
Home > core > getRxnsInComp.m
- - - -

getRxnsInComp -

- -

PURPOSE ^

-
getRxnsInComp
- -

SYNOPSIS ^

-
function [I, rxnNames]=getRxnsInComp(model,comp,includePartial)
- -

DESCRIPTION ^

-
 getRxnsInComp
-   Gets the reactions in a specified compartment
-
-   model           a model structure
-   comp            string with the compartment id
-   includePartial  true if reactions with metabolites in several
-                   compartments (normally transport reactions) should
-                   be included (optional, default false)
-
-   I               boolean vector of the reactions
-   rxnNames        the names of the reactions
-
- Usage: [I, rxnNames]=getRxnsInComp(model,comp,includePartial)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function [I, rxnNames]=getRxnsInComp(model,comp,includePartial)
-0002 % getRxnsInComp
-0003 %   Gets the reactions in a specified compartment
-0004 %
-0005 %   model           a model structure
-0006 %   comp            string with the compartment id
-0007 %   includePartial  true if reactions with metabolites in several
-0008 %                   compartments (normally transport reactions) should
-0009 %                   be included (optional, default false)
-0010 %
-0011 %   I               boolean vector of the reactions
-0012 %   rxnNames        the names of the reactions
-0013 %
-0014 % Usage: [I, rxnNames]=getRxnsInComp(model,comp,includePartial)
-0015 
-0016 comp=char(comp);
-0017 if nargin<3
-0018     includePartial=false;
-0019 end
-0020 
-0021 J=find(ismember(upper(model.comps),upper(comp)));
-0022 
-0023 if numel(J)~=1
-0024     EM=['No unique match to compartment "' comp{1} '"'];
-0025     dispEM(EM);
-0026 end
-0027 
-0028 K=model.metComps==J; %Get all metabolites in the compartment
-0029 
-0030 S=model.S~=0;
-0031 
-0032 %Find the reactions which involve any of the mets
-0033 [~, I]=find(S(K,:));
-0034 I=unique(I);
-0035 
-0036 %Then remove the ones which also include metabolites in other comps
-0037 if includePartial==false
-0038     I=I(sum(S(:,I))==sum(S(K,I)));
-0039 end
-0040 rxnNames=model.rxnNames(I);
-0041 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/getTransportRxns.html b/doc/core/getTransportRxns.html deleted file mode 100644 index 32a04c6e7..000000000 --- a/doc/core/getTransportRxns.html +++ /dev/null @@ -1,80 +0,0 @@ - - - - Description of getTransportRxns - - - - - - - - - -
Home > core > getTransportRxns.m
- - - -

getTransportRxns -

- -

PURPOSE ^

-
getTransportRxns
- -

SYNOPSIS ^

-
function transportRxns=getTransportRxns(model)
- -

DESCRIPTION ^

-
 getTransportRxns
-   Retrieves the transport reactions from a model
-
-   model           a model structure
-
-   transportRxns   logical array with true if the corresponding 
-                   reaction is a transport reaction
-
-   Transport reactions are defined as reactions involving (at least) one
-   metabolite name in more than one compartment.
-
- Usage: transportRxns=getTransportRxns(model)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function transportRxns=getTransportRxns(model)
-0002 % getTransportRxns
-0003 %   Retrieves the transport reactions from a model
-0004 %
-0005 %   model           a model structure
-0006 %
-0007 %   transportRxns   logical array with true if the corresponding
-0008 %                   reaction is a transport reaction
-0009 %
-0010 %   Transport reactions are defined as reactions involving (at least) one
-0011 %   metabolite name in more than one compartment.
-0012 %
-0013 % Usage: transportRxns=getTransportRxns(model)
-0014 
-0015 transportRxns=false(numel(model.rxns),1);
-0016 
-0017 for i=1:numel(model.rxns)
-0018     %Get the involved metabolites in each reaction
-0019     mets=model.metNames(model.S(:,i)~=0);
-0020     transportRxns(i)=numel(mets)~=numel(unique(mets));
-0021 end
-0022 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/guessComposition.html b/doc/core/guessComposition.html deleted file mode 100644 index 95b9c0f65..000000000 --- a/doc/core/guessComposition.html +++ /dev/null @@ -1,247 +0,0 @@ - - - - Description of guessComposition - - - - - - - - - -
Home > core > guessComposition.m
- - - -

guessComposition -

- -

PURPOSE ^

-
guessComposition
- -

SYNOPSIS ^

-
function [model, guessedFor, couldNotGuess]=guessComposition(model, printResults)
- -

DESCRIPTION ^

-
 guessComposition
-   Attempts to guess the composition of metabolites without information
-   about elemental composition
-
-   model               a model structure
-   printResults        true if the output should be printed (optional, default true)
-
-   model               a model structure with information about elemental
-                       composition added
-   guessedFor          indexes for the metabolites for which a composition
-                       could be guessed
-   couldNotGuess       indexes for the metabolites for which no
-                       composition could be assigned
-
-   This function works in a rather straight forward manner:
-
-   1. Get the metabolites which lack composition and participates in
-   at least one reaction where all other metabolites have composition information
-   2. Loop through them and calculate their composition based on the rest
-   of the involved metabolites. If there are any inconsistencies, so that
-   a given metabolite should have different composition in different
-   equations, then throw an error
-   3. Go to 1
-
-   This simple approach requires that the rest of the metabolites have
-   correct composition information, and that the involved reactions are
-   correct. The function will exit with an error on any inconsistencies,
-   which means that it could also be used as a way of checking the model
-   for errors. Note that just because this exits sucessfully, the
-   calculated compositions could still be wrong (in case that the existing
-   compositions were wrong)
-
- Usage: [newModel, guessedFor, couldNotGuess]=guessComposition(model, printResults)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 function [model, guessedFor, couldNotGuess]=guessComposition(model, printResults)
-0002 % guessComposition
-0003 %   Attempts to guess the composition of metabolites without information
-0004 %   about elemental composition
-0005 %
-0006 %   model               a model structure
-0007 %   printResults        true if the output should be printed (optional, default true)
-0008 %
-0009 %   model               a model structure with information about elemental
-0010 %                       composition added
-0011 %   guessedFor          indexes for the metabolites for which a composition
-0012 %                       could be guessed
-0013 %   couldNotGuess       indexes for the metabolites for which no
-0014 %                       composition could be assigned
-0015 %
-0016 %   This function works in a rather straight forward manner:
-0017 %
-0018 %   1. Get the metabolites which lack composition and participates in
-0019 %   at least one reaction where all other metabolites have composition information
-0020 %   2. Loop through them and calculate their composition based on the rest
-0021 %   of the involved metabolites. If there are any inconsistencies, so that
-0022 %   a given metabolite should have different composition in different
-0023 %   equations, then throw an error
-0024 %   3. Go to 1
-0025 %
-0026 %   This simple approach requires that the rest of the metabolites have
-0027 %   correct composition information, and that the involved reactions are
-0028 %   correct. The function will exit with an error on any inconsistencies,
-0029 %   which means that it could also be used as a way of checking the model
-0030 %   for errors. Note that just because this exits sucessfully, the
-0031 %   calculated compositions could still be wrong (in case that the existing
-0032 %   compositions were wrong)
-0033 %
-0034 % Usage: [newModel, guessedFor, couldNotGuess]=guessComposition(model, printResults)
-0035 
-0036 if nargin<2
-0037     printResults=true;
-0038 end
-0039 
-0040 %The metabolites for which there is no elemental composition
-0041 originalMissing=unique(model.metNames(cellfun(@isempty,model.metFormulas)));
-0042 guessedFor={};
-0043 
-0044 %This is to keep track of if new metabolite compositions were predicted
-0045 predicted=true;
-0046 while predicted==true
-0047     predicted=false;
-0048     
-0049     %Get the unique names (composition should be independent of
-0050     %compartment) for the metabolites without composition
-0051     metNames=unique(model.metNames(cellfun(@isempty,model.metFormulas)));
-0052     
-0053     %Parse the formulas in the model
-0054     [elements, useMat, exitFlag]=parseFormulas(model.metFormulas, true,false);
-0055     
-0056     for i=1:numel(metNames)
-0057         %Get the metabolites with this name. Not so neat, but this is a
-0058         %fast function anyways
-0059         mets=find(ismember(model.metNames,metNames(i)));
-0060         
-0061         currentComp=[];
-0062         
-0063         %Loop through the metabolites -1: Could not assign due to missing
-0064         %info. -2: Could not assign due to contradiction 1: Composition
-0065         %assigned
-0066         metStatus=-1;
-0067         for j=1:numel(mets)
-0068             %Get the reactions that the metabolite participates in
-0069             [~, I]=find(model.S(mets(j),:));
-0070             if any(I)
-0071                 for k=1:numel(I)
-0072                     %Loop through the reactions and check if all other mets
-0073                     %in them have known composition
-0074                     eqn=model.S(:,I(k));
-0075                     eqn(mets(j))=0;
-0076                     if all(exitFlag(eqn~=0)==1)
-0077                         %This means that all other mets had composition.
-0078                         %Calculate the resulting composition for the
-0079                         %unknown one
-0080                         comp=useMat'*eqn;
-0081                         
-0082                         %This can result in round off errors if there are
-0083                         %stoichiometries with many decimals. Ignore values
-0084                         %below 10^-12
-0085                         comp(abs(comp)<10^-12)=0;
-0086                         
-0087                         %Check if the composition consist of both negative
-0088                         %and positive values. If so, throw an error
-0089                         if all(comp<=0) || all(comp>=0)
-0090                             comp=abs(comp);
-0091                             if isempty(currentComp)
-0092                                 currentComp=comp;
-0093                             end
-0094                             %Also to deal with round off errors
-0095                             if all(abs(currentComp-comp)<10^-10)
-0096                                 metStatus=1;
-0097                             else
-0098                                 metStatus=-2;
-0099                                 break;
-0100                                 
-0101                                 %%Check if there is an inconcistency
-0102                                 %if any(currentComp~=comp)
-0103                                 %    dispEM(['Could not predict composition
-0104                                 %    of ' model.metNames{mets(i)} ],false);
-0105                                 %end
-0106                             end
-0107                         else
-0108                             %Check if there is an inconcistency if
-0109                             %any(currentComp~=comp)
-0110                             %    dispEM(['Could not predict composition of
-0111                             %    ' model.metNames{loopThrough(i)} ],false);
-0112                             %end
-0113                             metStatus=-2;
-0114                             break;
-0115                         end
-0116                     end
-0117                 end
-0118                 %If there was contradictions in one compartment, then abort
-0119                 %for all compartments
-0120                 if metStatus==-2
-0121                     break;
-0122                 end
-0123             else
-0124                 %The metabolite doesn't participate, no composition can be
-0125                 %calculated
-0126                 metStatus=-1;
-0127             end
-0128         end
-0129         %Check status of the metabolite
-0130         switch metStatus
-0131             case -2
-0132                 EM=['Could not predict composition for "' metNames{i} '" due to inconsistencies'];
-0133                 dispEM(EM,false);
-0134             case 1
-0135                 %Calculate and add the composition
-0136                 str=getCompString(elements,comp);
-0137                 model.metFormulas(mets)={str};
-0138                 if printResults==true
-0139                     fprintf(['Predicted composition for "' metNames{i} '" to be ' str '\n']);
-0140                 end
-0141                 
-0142                 %Keep track
-0143                 guessedFor=[guessedFor;metNames(i)];
-0144                 
-0145                 predicted=true; %To loop again
-0146         end
-0147     end
-0148 end
-0149 
-0150 couldNotGuess=setdiff(originalMissing,guessedFor);
-0151 end
-0152 
-0153 %Helper function for getting the composition string
-0154 function str=getCompString(elements,comp)
-0155 str='';
-0156 
-0157 for i=1:numel(comp)
-0158     if comp(i)~=0
-0159         if comp(i)==1
-0160             str=[str elements.abbrevs{i}];
-0161         else
-0162             str=[str elements.abbrevs{i} num2str(comp(i))];
-0163         end
-0164     end
-0165 end
-0166 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/haveFlux.html b/doc/core/haveFlux.html deleted file mode 100644 index 4f10e9bc2..000000000 --- a/doc/core/haveFlux.html +++ /dev/null @@ -1,148 +0,0 @@ - - - - Description of haveFlux - - - - - - - - - -
Home > core > haveFlux.m
- - - -

haveFlux -

- -

PURPOSE ^

-
haveFlux
- -

SYNOPSIS ^

-
function I=haveFlux(model,cutOff,rxns)
- -

DESCRIPTION ^

-
 haveFlux
-   Checks which reactions can carry a (positive or negative) flux. Is used
-   as a faster version of getAllowedBounds if it is only interesting
-   whether the reactions can carry a flux or not
-
- Input:
-   model       a model structure
-   cutOff      the flux value that a reaction has to carry to be
-               identified as positive (optional, default 10^-8)
-   rxns        either a cell array of IDs, a logical vector with the
-               same number of elements as metabolites in the model, or a
-               vector of indexes (optional, default model.rxns)
-
- Output:
-   I           logical array with true if the corresponding reaction can
-               carry a flux
-
- If a model has +/- Inf bounds then those are replaced with an arbitary
- large value of +/- 10000 prior to solving
-
- Usage: I = haveFlux(model, cutOff, rxns)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function I=haveFlux(model,cutOff,rxns)
-0002 % haveFlux
-0003 %   Checks which reactions can carry a (positive or negative) flux. Is used
-0004 %   as a faster version of getAllowedBounds if it is only interesting
-0005 %   whether the reactions can carry a flux or not
-0006 %
-0007 % Input:
-0008 %   model       a model structure
-0009 %   cutOff      the flux value that a reaction has to carry to be
-0010 %               identified as positive (optional, default 10^-8)
-0011 %   rxns        either a cell array of IDs, a logical vector with the
-0012 %               same number of elements as metabolites in the model, or a
-0013 %               vector of indexes (optional, default model.rxns)
-0014 %
-0015 % Output:
-0016 %   I           logical array with true if the corresponding reaction can
-0017 %               carry a flux
-0018 %
-0019 % If a model has +/- Inf bounds then those are replaced with an arbitary
-0020 % large value of +/- 10000 prior to solving
-0021 %
-0022 % Usage: I = haveFlux(model, cutOff, rxns)
-0023 
-0024 if nargin<2
-0025     cutOff=10^-6;
-0026 end
-0027 if isempty(cutOff)
-0028     cutOff=10^-6;
-0029 end
-0030 if nargin<3
-0031     rxns=model.rxns;
-0032 elseif ~islogical(rxns) && ~isnumeric(rxns)
-0033     rxns=convertCharArray(rxns);
-0034 end
-0035 
-0036 %This is since we're maximizing for the sum of fluxes, which isn't possible
-0037 %when there are infinite bounds
-0038 model.lb(model.lb==-inf)=-10000;
-0039 model.ub(model.ub==inf)=10000;
-0040 
-0041 %Get the reaction IDs. A bit of an awkward way, but fine.
-0042 indexes=getIndexes(model,rxns,'rxns');
-0043 rxns=model.rxns(indexes);
-0044 
-0045 %First remove all dead-end reactions
-0046 smallModel=simplifyModel(model,false,false,true,true);
-0047 
-0048 %Get the indexes of the reactions in the connected model
-0049 indexes=getIndexes(smallModel,intersect(smallModel.rxns,rxns),'rxns');
-0050 J=false(numel(indexes),1);
-0051 mixIndexes=indexes(randperm(numel(indexes)));
-0052 
-0053 %Maximize for all fluxes first in order to get fewer rxns to test
-0054 smallModel.c=ones(numel(smallModel.c),1);
-0055 sol=solveLP(smallModel);
-0056 if ~isempty(sol.x)
-0057     J(abs(sol.x(mixIndexes))>cutOff)=true;
-0058 end
-0059 
-0060 %Loop through and maximize then minimize each rxn if it does not already
-0061 %have a flux
-0062 Z=zeros(numel(smallModel.c),1);
-0063 hsSolOut=[];
-0064 for i=[1 -1]
-0065     for j=1:numel(J)
-0066         if J(j)==false
-0067             %Only minimize for reversible reactions
-0068             if i==1 || smallModel.rev(mixIndexes(j))~=0
-0069                 smallModel.c=Z;
-0070                 smallModel.c(mixIndexes(j))=i;
-0071                 [sol, hsSolOut]=solveLP(smallModel,0,[],hsSolOut);
-0072                 if any(sol.x)
-0073                     J(abs(sol.x(mixIndexes))>cutOff)=true;
-0074                 end
-0075             end
-0076         end
-0077     end
-0078 end
-0079 
-0080 I=ismember(rxns,smallModel.rxns(mixIndexes(J)));
-0081 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/index.html b/doc/core/index.html deleted file mode 100644 index f8ca81dd5..000000000 --- a/doc/core/index.html +++ /dev/null @@ -1,29 +0,0 @@ - - - - Index for Directory core - - - - - - - - - - -
< Master indexIndex for core >
- -

Index for core

- -

Matlab files in this directory:

- -
 FSEOFFSEOF
 addExchangeRxnsaddExchangeRxns
 addGenesRavenaddGenesRaven
 addMetsaddMets
 addRxnsaddRxns
 addRxnsGenesMetsaddRxnsGenesMets
 addTransportaddTransport
 analyzeSamplinganalyzeSampling
 buildEquationbuildEquation
 canConsumecanConsume
 canProducecanProduce
 changeGrRuleschangeGrRules
 changeRxnschangeRxns
 checkModelStructcheckModelStruct
 checkProductioncheckProduction
 checkRxncheckRxn
 checkTaskscheckTasks
 compareMultipleModelscompareMultipleModels
 compareRxnsGenesMetsCompscompareRxnsGenesMetsComps
 constructEquationsconstructEquations
 constructSconstructS
 consumeSomethingconsumeSomething
 contractModelcontractModel
 convertCharArrayconvertCharArray
 convertToIrrevconvertToIrrev
 copyToCompscopyToComps
 deleteUnusedGenesdeleteUnusedGenes
 dispEMdispEM
 expandModelexpandModel
 fillGapsfillGaps
 findGeneDeletionsfindGeneDeletions
 findRAVENrootfindRAVENroot
 fitParametersfitParameters
 fitTasksfitTasks
 followChangedfollowChanged
 followFluxesfollowFluxes
 gapReportgapReport
 generateNewIdsgenerateNewIds
 getAllRxnsFromGenesgetAllRxnsFromGenes
 getAllSubGraphsgetAllSubGraphs
 getAllowedBoundsgetAllowedBounds
 getElementalBalancegetElementalBalance
 getEssentialRxnsgetEssentialRxns
 getExchangeRxnsgetExchangeRxns
 getExpressionStructuregetExpressionStructure
 getFluxZgetFluxZ
 getGenesFromGrRulesgetGenesFromGrRules Extract gene list and rxnGeneMat from grRules array.
 getIndexesgetIndexes
 getMetsInCompgetMetsInComp
 getMinNrFluxesgetMinNrFluxes
 getModelFromHomologygetModelFromHomology
 getRxnsInCompgetRxnsInComp
 getTransportRxnsgetTransportRxns
 guessCompositionguessComposition
 haveFluxhaveFlux
 makeSomethingmakeSomething
 mapCompartmentsmapCompartments
 mergeCompartmentsmergeCompartments
 mergeModelsmergeModels
 parallelPoolRAVENhandleParallelRAVEN
 parseFormulasparseFormulas
 parseRxnEquparseRxnEqu
 parseTaskListparseTaskList
 permuteModelpermuteModel
 predictLocalizationpredictLocalization
 printFluxesprintFluxes
 printModelprintModel
 printModelStatsprintModelStats
 printOrangeprintOrange
 randomSamplingrandomSampling
 removeBadRxnsremoveBadRxns
 removeGenesremoveGenes
 removeMetsremoveMets
 removeReactionsremoveReactions
 replaceMetsreplaceMets
 reporterMetabolitesreporterMetabolites
 runDynamicFBArunDynamicFBA
 runPhenotypePhasePlanerunPhenotypePhasePlane
 runProductionEnveloperunProductionEnvelope
 runRobustnessAnalysisrunRobustnessAnalysis
 runSimpleOptKnockrunSimpleOptKnock
 setExchangeBoundssetExchangeBounds
 setParamsetParam
 simplifyModelsimplifyModel
 sortModelsortModel
 standardizeGrRulesstandardizeGrRules
- - - - -
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/makeSomething.html b/doc/core/makeSomething.html deleted file mode 100644 index bbf9b56e4..000000000 --- a/doc/core/makeSomething.html +++ /dev/null @@ -1,275 +0,0 @@ - - - - Description of makeSomething - - - - - - - - - -
Home > core > makeSomething.m
- - - -

makeSomething -

- -

PURPOSE ^

-
makeSomething
- -

SYNOPSIS ^

-
function [solution, metabolite]=makeSomething(model,ignoreMets,isNames,minNrFluxes,allowExcretion,params,ignoreIntBounds)
- -

DESCRIPTION ^

-
 makeSomething
-   Tries to excrete any metabolite using as few reactions as possible.
-   The intended use is when you want to make sure that you model cannot
-   synthesize anything from nothing. It is then a faster way than to use
-   checkProduction or canProduce
-
-   model           a model structure
-   ignoreMets      either a cell array of metabolite IDs, a logical vector
-                   with the same number of elements as metabolites in the model,
-                   of a vector of indexes for metabolites to exclude from
-                   this analysis (optional, default [])
-   isNames         true if the supplied mets represent metabolite names
-                   (as opposed to IDs). This is a way to delete
-                   metabolites in several compartments at once without
-                   knowing the exact IDs. This only works if ignoreMets
-                   is a cell array (optional, default false)
-   minNrFluxes     solves the MILP problem of minimizing the number of
-                   fluxes instead of the sum. Slower, but can be
-                   used if the sum gives too many fluxes (optional, default
-                   false)
-   allowExcretion  allow for excretion of all other metabolites (optional,
-                   default true)
-   params          *obsolete option*
-   ignoreIntBounds    true if internal bounds (including reversibility)
-                   should be ignored. Exchange reactions are not affected.
-                   This can be used to find unbalanced solutions which are
-                   not possible using the default constraints (optional,
-                   default false)
-
-   solution        flux vector for the solution
-   metabolite      the index of the metabolite(s) which was excreted. If
-                   possible only one metabolite is reported, but there are
-                   situations where metabolites can only be excreted in
-                   pairs (or more)
-
-   NOTE: This works by forcing at least 1 unit of "any metabolites" to be
-   produced and then minimize for the sum of fluxes. If more than one
-   metabolite is produced, it picks one of them to be produced and then
-   minimizes for the sum of fluxes.
-
- Usage: [solution, metabolite]=makeSomething(model,ignoreMets,isNames,...
-           minNrFluxes,allowExcretion,params,ignoreIntBounds)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function [solution, metabolite]=makeSomething(model,ignoreMets,isNames,minNrFluxes,allowExcretion,params,ignoreIntBounds)
-0002 % makeSomething
-0003 %   Tries to excrete any metabolite using as few reactions as possible.
-0004 %   The intended use is when you want to make sure that you model cannot
-0005 %   synthesize anything from nothing. It is then a faster way than to use
-0006 %   checkProduction or canProduce
-0007 %
-0008 %   model           a model structure
-0009 %   ignoreMets      either a cell array of metabolite IDs, a logical vector
-0010 %                   with the same number of elements as metabolites in the model,
-0011 %                   of a vector of indexes for metabolites to exclude from
-0012 %                   this analysis (optional, default [])
-0013 %   isNames         true if the supplied mets represent metabolite names
-0014 %                   (as opposed to IDs). This is a way to delete
-0015 %                   metabolites in several compartments at once without
-0016 %                   knowing the exact IDs. This only works if ignoreMets
-0017 %                   is a cell array (optional, default false)
-0018 %   minNrFluxes     solves the MILP problem of minimizing the number of
-0019 %                   fluxes instead of the sum. Slower, but can be
-0020 %                   used if the sum gives too many fluxes (optional, default
-0021 %                   false)
-0022 %   allowExcretion  allow for excretion of all other metabolites (optional,
-0023 %                   default true)
-0024 %   params          *obsolete option*
-0025 %   ignoreIntBounds    true if internal bounds (including reversibility)
-0026 %                   should be ignored. Exchange reactions are not affected.
-0027 %                   This can be used to find unbalanced solutions which are
-0028 %                   not possible using the default constraints (optional,
-0029 %                   default false)
-0030 %
-0031 %   solution        flux vector for the solution
-0032 %   metabolite      the index of the metabolite(s) which was excreted. If
-0033 %                   possible only one metabolite is reported, but there are
-0034 %                   situations where metabolites can only be excreted in
-0035 %                   pairs (or more)
-0036 %
-0037 %   NOTE: This works by forcing at least 1 unit of "any metabolites" to be
-0038 %   produced and then minimize for the sum of fluxes. If more than one
-0039 %   metabolite is produced, it picks one of them to be produced and then
-0040 %   minimizes for the sum of fluxes.
-0041 %
-0042 % Usage: [solution, metabolite]=makeSomething(model,ignoreMets,isNames,...
-0043 %           minNrFluxes,allowExcretion,params,ignoreIntBounds)
-0044 
-0045 if nargin<2
-0046     ignoreMets=[];
-0047 elseif ~islogical(ignoreMets) && ~isnumeric(ignoreMets)
-0048     ignoreMets=convertCharArray(ignoreMets);
-0049 end
-0050 if nargin<3
-0051     isNames=false;
-0052 end
-0053 if nargin<4
-0054     minNrFluxes=false;
-0055 end
-0056 if nargin<5
-0057     allowExcretion=true;
-0058 end
-0059 if nargin<6
-0060     params.relGap=0.8;
-0061 end
-0062 if nargin<7
-0063     ignoreIntBounds=false;
-0064 end
-0065 
-0066 if isNames==true && ~isempty(ignoreMets)
-0067     %Check that metsToRemove is a cell array
-0068     if iscellstr(ignoreMets)==false
-0069         EM='Must supply a cell array of strings if isNames=true';
-0070         dispEM(EM);
-0071     end
-0072 end
-0073 
-0074 if isNames==false
-0075     indexesToIgnore=getIndexes(model,ignoreMets,'mets');
-0076 else
-0077     indexesToIgnore=[];
-0078     for i=1:numel(ignoreMets)
-0079         indexesToIgnore=[indexesToIgnore;find(strcmp(ignoreMets(i),model.metNames))];
-0080     end
-0081 end
-0082 
-0083 %Allow for excretion of all metabolites
-0084 if allowExcretion==true
-0085     model.b=[model.b(:,1) inf(numel(model.mets),1)];
-0086 end
-0087 
-0088 %Change all internal reactions to be unbounded in both directions
-0089 if ignoreIntBounds==true
-0090     [~, I]=getExchangeRxns(model);
-0091     nonExc=true(numel(model.rxns),1);
-0092     nonExc(I)=false;
-0093     model=setParam(model,'lb',nonExc,-1000);
-0094     model=setParam(model,'ub',nonExc,1000);
-0095     model=setParam(model,'rev',nonExc,1);
-0096 end
-0097 
-0098 solution=[];
-0099 metabolite=[];
-0100 
-0101 nRxns=numel(model.rxns);
-0102 nMets=numel(model.mets);
-0103 
-0104 %Add excretion reactions for all metabolites
-0105 model.S=[model.S speye(nMets)*-1];
-0106 
-0107 %Add so that they all produce a fake metabolite
-0108 model.S=[model.S;[sparse(1,nRxns) ones(1,nMets)]];
-0109 
-0110 %Change so that the ignoreMets have a coefficient 0 in their reactions.
-0111 %Does not remove the actual reaction to make mapping easier later
-0112 model.S(:,indexesToIgnore+nRxns)=0;
-0113 
-0114 %Add an excretion reaction for this last fake metabolite
-0115 model.S(size(model.S,1),size(model.S,2)+1)=-1;
-0116 model.b=[model.b;zeros(1,size(model.b,2))];
-0117 model.lb=[model.lb;zeros(nMets,1);1];
-0118 model.ub=[model.ub;inf(nMets+1,1)];
-0119 model.rev=[model.rev;zeros(nMets+1,1)];
-0120 model.c=zeros(size(model.S,2),1);
-0121 
-0122 %Add padding to the reaction annotation to prevent an error in solveLP
-0123 padding=1:numel(model.rev);
-0124 padding=num2cell(padding)';
-0125 padding=cellfun(@num2str,padding,'uniformoutput',false);
-0126 model.rxns=padding;
-0127 model.rxnNames=padding;
-0128 model.eccodes=padding;
-0129 model.rxnMiriams=padding;
-0130 model.grRules=padding;
-0131 if isfield(model,'genes')
-0132     model.rxnGeneMat=sparse(numel(model.rev),numel(model.genes));
-0133 end
-0134 model.subSystems=padding;
-0135 model.rxnFrom=padding;
-0136 model.rxnComps=ones(numel(model.rev),1);
-0137 model.rxnNotes=padding;
-0138 model.rxnReferences=padding;
-0139 model.rxnConfidenceScores=NaN(numel(model.rev),1);
-0140 
-0141 sol=solveLP(model,1);
-0142 if any(sol.x)
-0143     %It could be that several metabolites were produced in order to get the
-0144     %best solution. The setdiff is to avoid including the last fake
-0145     %metabolite
-0146     I=setdiff(find(sol.x(nRxns+1:end)>0.1),size(model.S,1));
-0147     
-0148     if any(I) %This should always be true
-0149         %Change the coefficients so that only the first is produced. This
-0150         %is not always possible, but it is tested for since it it results
-0151         %in more easily interpretable results
-0152         
-0153         oldS=model.S;
-0154         foundSingle=false;
-0155         %Test if any of the metabolites could be produced on their own
-0156         for i=1:numel(I)
-0157             model.S=oldS;
-0158             J=nRxns+1:numel(model.lb)-1;
-0159             J(I(i))=[];
-0160             model.S(:,J)=0;
-0161             sol=solveLP(model);
-0162             if any(sol.x)
-0163                 foundSingle=true;
-0164                 break;
-0165             end
-0166         end
-0167         %This means that there was no metabolite which could be produced on
-0168         %its own. Then let all the produceable metabolites be produced.
-0169         if foundSingle==false
-0170             model.S=oldS;
-0171         end
-0172         if minNrFluxes==true
-0173             %Has to add names for the rxns to prevent an error in
-0174             %minNrFluxes
-0175             model.rxns=cell(numel(model.lb),1);
-0176             model.rxns(:)=sprintfc('tmp_%d',1:numel(model.lb));
-0177             model.mets=cell(size(model.b,1),1);
-0178             model.mets(:)={'TEMP'};
-0179             sol=solveLP(model,3,params);
-0180         else
-0181             sol=solveLP(model,1);
-0182         end
-0183         solution=sol.x(1:nRxns);
-0184         metabolite=find(sol.x(nRxns+1:end-1)>0.1);
-0185     end
-0186 end
-0187 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/mapCompartments.html b/doc/core/mapCompartments.html deleted file mode 100644 index 1af9de4d3..000000000 --- a/doc/core/mapCompartments.html +++ /dev/null @@ -1,214 +0,0 @@ - - - - Description of mapCompartments - - - - - - - - - -
Home > core > mapCompartments.m
- - - -

mapCompartments -

- -

PURPOSE ^

-
mapCompartments
- -

SYNOPSIS ^

-
function geneScoreStructure=mapCompartments(geneScoreStructure,varargin)
- -

DESCRIPTION ^

-
 mapCompartments
-   Maps compartments in the geneScoreStructure. This is used if you do not
-   want a models that uses all of the compartment from the predictor. This
-   function will then let you define rules on how the compartments should
-   be merged.
-
-   Any number of rules could be defined as consecutive strings or in a cell array.
-   'comp1'             comp1 should be kept in the structure
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function geneScoreStructure=mapCompartments(geneScoreStructure,varargin)
-0002 % mapCompartments
-0003 %   Maps compartments in the geneScoreStructure. This is used if you do not
-0004 %   want a models that uses all of the compartment from the predictor. This
-0005 %   function will then let you define rules on how the compartments should
-0006 %   be merged.
-0007 %
-0008 %   Any number of rules could be defined as consecutive strings or in a cell array.
-0009 %   'comp1'             comp1 should be kept in the structure
-0010 
-0011 %   'comp1=comp2'       The scores in comp2 are merged to comp1 and comp2 is
-0012 %                       removed from the structure. This automatically
-0013 %                       keeps comp1 in the structure
-0014 
-0015 %   'comp1=comp2 comp3' The scores in comp2 and comp3 are merged to comp1
-0016 %                       and comp2 & comp2 are removed from the structure.
-0017 %                       This automatically keeps comp1 in the structure
-0018 
-0019 %   'comp1 comp2=comp3' The scores in comp3 are split between comp1 and
-0020 %                       comp2. This automatically keeps comp1 and comp2 in
-0021 %                       the structure
-0022 
-0023 %   'comp1=other'       The scores in any compartment not included are
-0024 %                       merged to comp1. This is applied after all other
-0025 %                       rules.
-0026 %
-0027 %   When one compartment is merged to another the resulting scores will be
-0028 %   the best for each gene in either of the compartments. In the case where
-0029 %   one compartment is split among several, the scores for the compartment
-0030 %   to be merged is weighted with the number of compartments to split to.
-0031 %
-0032 %   Example: The predictor you use give prediction for Extracellular,
-0033 %   Cytosol, Nucleus, Peroxisome, Mitochondria, ER, and Lysosome. You want to
-0034 %   have a model with Extracellular, Cytosol, Mitochondria, and Peroxisome
-0035 %   where Lysosome is merged with Peroxisome and all other compartments
-0036 %   are merged to the Cytosol.
-0037 %
-0038 %   GSS=mapCompartments(GSS,'Extracellular','Mitochondria','Peroxisome=Lyso
-0039 %   some','Cytosol=other');
-0040 %
-0041 %   geneScoreStructure  a structure to be used in predictLocalization
-0042 %
-0043 % Usage: geneScoreStructure=mapCompartments(geneScoreStructure,varargin)
-0044 
-0045 varargin=upper(varargin);
-0046 
-0047 %First find the compartment that will end up in the final structure. They
-0048 %are the ones that stand alone or are to the left of some '='
-0049 toKeep={};
-0050 toMerge={};
-0051 I=regexp(varargin,'=','split');
-0052 for i=1:numel(varargin)
-0053     if numel(I{i})==1
-0054         toKeep=[toKeep;I{i}];
-0055     else
-0056         J=regexp(I{i}(1),' ','split');
-0057         K=regexp(I{i}(2),' ','split');
-0058         toKeep=[toKeep;J{1}(:)];
-0059         toMerge=[toMerge;K{1}(:)];
-0060     end
-0061 end
-0062 
-0063 %Check that there are no compartment that should both be merged and kept
-0064 if ~isempty(intersect(toKeep,toMerge))
-0065     EM='There are inconsistencies where one or more compartment(s) should be both kept and merged to another';
-0066     dispEM(EM);
-0067 end
-0068 
-0069 %Check that there are no compartments in the rules that are not in the
-0070 %geneScoreStructure.
-0071 uComps=upper(geneScoreStructure.compartments);
-0072 J=[uComps,{'OTHER'}];
-0073 
-0074 if ~isempty(setdiff([toKeep;toMerge],J))
-0075     EM='There are compartment in the rules that are not in geneScoreStructure.compartments';
-0076     dispEM(EM);
-0077 end
-0078 
-0079 %Loop through it again and do the mapping
-0080 otherIndex=[]; %This stores the rule which maps 'other'.
-0081 
-0082 for i=1:numel(I)
-0083     if numel(I{i})>1
-0084         %Get the compartment indexes that should be mapped
-0085         J=regexp(I{i}(2),' ','split');
-0086         if strcmpi(J{1},'other')
-0087             otherIndex=i;
-0088             continue;
-0089         end
-0090         [k, K]=ismember(J{1},uComps);
-0091         
-0092         %And to where they should be mapped
-0093         J=regexp(I{i}(1),' ','split');
-0094         [l, L]=ismember(J{1},uComps);
-0095         
-0096         %It's not allowed to have rules like A B=C D
-0097         if numel(K)>1 && numel(L)>1
-0098             EM='It is not allowed to have rules like "A B=C D" (map more than one compartment to more than one compartment)';
-0099             dispEM(EM);
-0100         end
-0101         
-0102         if ~all(k) || ~all(l)
-0103             EM='Error in mapping. This most likely means that some compartment(s) are mapped to different compartments in different rules. Use A B=C if you want to map C to several compartments';
-0104             dispEM(EM);
-0105         end
-0106         
-0107         %Get the sum of the scores for the compartments that should be
-0108         %merged to something else
-0109         S=max(geneScoreStructure.scores(:,K),[],2);
-0110         for j=1:numel(L)
-0111             %If the scores are mapped to several different compartments
-0112             %then split the scores between them
-0113             geneScoreStructure.scores(:,L(j))=max(geneScoreStructure.scores(:,L(j)),S./numel(L));
-0114         end
-0115         
-0116         %Remove the comparement that were merged
-0117         geneScoreStructure.compartments(K)=[];
-0118         geneScoreStructure.scores(:,K)=[];
-0119         uComps(K)=[];
-0120     end
-0121 end
-0122 
-0123 %Then check if there are remaining compartments that should be removed or
-0124 %mapped as 'other'
-0125 J=find(~ismember(uComps,toKeep));
-0126 if any(J)
-0127     if any(otherIndex)
-0128         K=regexp(I{otherIndex}(1),' ','split');
-0129         [l, L]=ismember(K{1},uComps);
-0130         if l==1 && numel(l)==1
-0131             S=max(geneScoreStructure.scores(:,J),[],2);
-0132             geneScoreStructure.scores(:,L)=max(geneScoreStructure.scores(:,L),S);
-0133         else
-0134             EM='Could not map "other" to more than one compartment';
-0135             dispEM(EM);
-0136         end
-0137     else
-0138         EM='There are compartments that are not defined if they should be kept or removed. Use "A=other" or define more rules if you do not want them to be deleted';
-0139         dispEM(EM,false);
-0140     end
-0141     
-0142     %Remove the comparement that were merged
-0143     geneScoreStructure.compartments(J)=[];
-0144     geneScoreStructure.scores(:,J)=[];
-0145 end
-0146 
-0147 %Renormalize
-0148 I=max(geneScoreStructure.scores,[],2);
-0149 geneScoreStructure.scores=bsxfun(@times, geneScoreStructure.scores, 1./I);
-0150 
-0151 %If there are genes that have score 0 in all compartments, remove them and
-0152 %print a warning.
-0153 I=find(isnan(geneScoreStructure.scores(:,1))); %Only looks a the first colum as it will be the same for the other ones
-0154 if any(I)
-0155     EM='The following genes had score 0.0 in all compartments. They have been removed from the structure. Consider using more rules or "A=other" in order to prevent this:';
-0156     dispEM(EM,false,geneScoreStructure.genes(I));
-0157     geneScoreStructure.scores(I,:)=[];
-0158     geneScoreStructure.genes(I)=[];
-0159 end
-0160 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/mergeCompartments.html b/doc/core/mergeCompartments.html deleted file mode 100644 index 5754bdbdc..000000000 --- a/doc/core/mergeCompartments.html +++ /dev/null @@ -1,209 +0,0 @@ - - - - Description of mergeCompartments - - - - - - - - - -
Home > core > mergeCompartments.m
- - - -

mergeCompartments -

- -

PURPOSE ^

-
mergeCompartments
- -

SYNOPSIS ^

-
function [model, deletedRxns, duplicateRxns]=mergeCompartments(model,keepUnconstrained,deleteRxnsWithOneMet,distReverse)
- -

DESCRIPTION ^

-
 mergeCompartments
-   Merge all compartments in a model
-
-   model                 a model structure
-   keepUnconstrained     keep metabolites that are unconstrained in a
-                         'unconstrained' compartment. If these are merged the
-                         exchange reactions will most often be deleted (optional,
-                         default false)
-   deleteRxnsWithOneMet  delete reactions with only one metabolite. These
-                         reactions come from reactions such as A[c] + B[c]
-                         => A[m]. In some models hydrogen is balanced around
-                         each membrane with reactions like this (optional,
-                         default false)
-   distReverse           distinguish reactions with same metabolites but
-                         different reversibility as different reactions
-                         (optional, default true)
-
-   model                 a model with all reactions located to one compartment
-   deletedRxns           reactions that were deleted because of only
-                         having one metabolite after merging
-   duplicateRxns         identical reactions that occurred in different
-                         compartments and were deleted because they turned
-                         to be duplicated after merging
-
-   Merges all compartments into one 's' compartment (for 'System'). This can
-   be useful for example to ensure that there are metabolic capabilities to
-   synthesize all metabolites.
-
-   NOTE: If the metabolite IDs reflect the compartment that they are in
-   the IDs may no longer be representative.
-
- Usage: [model, deletedRxns, duplicateRxns]=mergeCompartments(model,keepUnconstrained,deleteRxnsWithOneMet,distReverse)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function [model, deletedRxns, duplicateRxns]=mergeCompartments(model,keepUnconstrained,deleteRxnsWithOneMet,distReverse)
-0002 % mergeCompartments
-0003 %   Merge all compartments in a model
-0004 %
-0005 %   model                 a model structure
-0006 %   keepUnconstrained     keep metabolites that are unconstrained in a
-0007 %                         'unconstrained' compartment. If these are merged the
-0008 %                         exchange reactions will most often be deleted (optional,
-0009 %                         default false)
-0010 %   deleteRxnsWithOneMet  delete reactions with only one metabolite. These
-0011 %                         reactions come from reactions such as A[c] + B[c]
-0012 %                         => A[m]. In some models hydrogen is balanced around
-0013 %                         each membrane with reactions like this (optional,
-0014 %                         default false)
-0015 %   distReverse           distinguish reactions with same metabolites but
-0016 %                         different reversibility as different reactions
-0017 %                         (optional, default true)
-0018 %
-0019 %   model                 a model with all reactions located to one compartment
-0020 %   deletedRxns           reactions that were deleted because of only
-0021 %                         having one metabolite after merging
-0022 %   duplicateRxns         identical reactions that occurred in different
-0023 %                         compartments and were deleted because they turned
-0024 %                         to be duplicated after merging
-0025 %
-0026 %   Merges all compartments into one 's' compartment (for 'System'). This can
-0027 %   be useful for example to ensure that there are metabolic capabilities to
-0028 %   synthesize all metabolites.
-0029 %
-0030 %   NOTE: If the metabolite IDs reflect the compartment that they are in
-0031 %   the IDs may no longer be representative.
-0032 %
-0033 % Usage: [model, deletedRxns, duplicateRxns]=mergeCompartments(model,keepUnconstrained,deleteRxnsWithOneMet,distReverse)
-0034 
-0035 if nargin<2
-0036     keepUnconstrained=false;
-0037 end
-0038 if nargin<3
-0039     deleteRxnsWithOneMet=false;
-0040 end
-0041 if nargin<4
-0042     distReverse=true;
-0043 end
-0044 
-0045 if ~isfield(model,'unconstrained')
-0046     keepUnconstrained=false;
-0047 end
-0048 
-0049 %Keep track of which reactions only contained one metabolite before the
-0050 %merging as they are probable exchange reactions.
-0051 if deleteRxnsWithOneMet==true
-0052     reservedRxns=model.rxns(sum(model.S~=0)==1);
-0053     if ~isempty(reservedRxns) && isfield(model,'unconstrained')
-0054         %If there is no unconstrained field these reactions are probably
-0055         %exchange reactions and shall be kept. If not then print a warning
-0056         EM='There are reactions with only one metabolite. Cannot determine whether they are exchange reactions since there is no unconstrained field';
-0057         dispEM(EM,false);
-0058     end
-0059 end
-0060 
-0061 %Loop through each metabolite, and if it is not unconstrained then change
-0062 %the S matrix to use the metabolite with the lowest index in model.comps
-0063 %instead
-0064 uNames=unique(model.metNames);
-0065 for i=1:numel(uNames)
-0066     %Find all metabolites with this name..
-0067     I=ismember(model.metNames,uNames(i));
-0068     
-0069     %Find the first of those that is not unconstrained. This is the one
-0070     %that the other "un-unconstrained" should be changed to.
-0071     if keepUnconstrained==true
-0072         mergeTo=find(I & model.unconstrained==false,1);
-0073         
-0074         %This could happen if there is only one metabolite and it is
-0075         %unconstrained
-0076         if isempty(mergeTo)
-0077             continue;
-0078         end
-0079     else
-0080         mergeTo=find(I,1);
-0081     end
-0082     I(mergeTo)=false; %Do not do anything for itself
-0083     I=find(I);
-0084     
-0085     %Go through each of the metabolites with this name and update them to
-0086     %mergeTo
-0087     for j=1:numel(I)
-0088         if keepUnconstrained==true && model.unconstrained(I(j))==true
-0089             continue;
-0090         end
-0091         %Update the S matrix
-0092         model.S(mergeTo,:)=model.S(mergeTo,:)+model.S(I(j),:);
-0093         model.S(I(j),:)=0;
-0094     end
-0095 end
-0096 
-0097 %Remove all metabolites that are no longer used (with a bit of a trick)
-0098 model=removeReactions(model,{},true);
-0099 
-0100 %Update all mets so that they are in compartment "s" with id "1"
-0101 model.compNames={'System'};
-0102 model.comps={'s'};
-0103 model.compOutside={''};
-0104 model.metComps=ones(numel(model.mets),1);
-0105 
-0106 %Add exchange mets to another compartment "b" with id "2"
-0107 if keepUnconstrained==true
-0108     model.compNames=[model.compNames; {'Unconstrained'}];
-0109     model.comps=[model.comps; {'b'}];
-0110     model.compOutside=[model.compOutside; {'s'}];
-0111     model.metComps(model.unconstrained~=0)=2;
-0112 end
-0113 
-0114 %Transport reactions on the form A <=> B will have been deleted by the
-0115 %merging. Remove those reactions
-0116 model=removeMets(model,{},false,true,true);
-0117 
-0118 if deleteRxnsWithOneMet==true
-0119     I=model.rxns(sum(model.S~=0)==1);
-0120     
-0121     %Delete the reactions that contain only one metabolite after the
-0122     %merging but not before
-0123     deletedRxns=setdiff(I,reservedRxns);
-0124     model=removeReactions(model,deletedRxns,true,true);
-0125 else
-0126     deletedRxns={};
-0127 end
-0128 
-0129 %And then finally merge the identical reactions
-0130 [model, ~, duplicateRxns]=contractModel(model,distReverse);
-0131 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/mergeModels.html b/doc/core/mergeModels.html deleted file mode 100644 index 577f82d32..000000000 --- a/doc/core/mergeModels.html +++ /dev/null @@ -1,720 +0,0 @@ - - - - Description of mergeModels - - - - - - - - - -
Home > core > mergeModels.m
- - - -

mergeModels -

- -

PURPOSE ^

-
mergeModels
- -

SYNOPSIS ^

-
function model=mergeModels(models,metParam,supressWarnings,copyToComps)
- -

DESCRIPTION ^

-
 mergeModels
-   Merges models into one model structure. Reactions are added without any
-   checks, so duplicate reactions might appear. Metabolites are matched by
-   their name and compartment (metaboliteName[comp]), while genes are
-   matched by their name.
-
- Input:
-   models          a cell array with model structures
-   metParam        string metabolite name ('metNames') or ID ('mets') are
-                   used for matching (optional, default 'metNames')
-   supressWarnings logical whether warnings should be supressed (optional,
-                   default false)
-   copyToComps     logical whether mergeModels is run via copyToComps
-                   (optional, default false)
-
- Output:
-   model           a model structure with the merged model. Follows the
-                   structure of normal models but also has 'rxnFrom/
-                   metFrom/geneFrom' fields to indicate from which model
-                   each reaction/metabolite/gene was taken. If the model
-                   already has 'rxnFrom/metFrom/geneFrom' fields, then
-                   these fields are not modified.
-
- Usage: model=mergeModels(models)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function model=mergeModels(models,metParam,supressWarnings,copyToComps)
-0002 % mergeModels
-0003 %   Merges models into one model structure. Reactions are added without any
-0004 %   checks, so duplicate reactions might appear. Metabolites are matched by
-0005 %   their name and compartment (metaboliteName[comp]), while genes are
-0006 %   matched by their name.
-0007 %
-0008 % Input:
-0009 %   models          a cell array with model structures
-0010 %   metParam        string metabolite name ('metNames') or ID ('mets') are
-0011 %                   used for matching (optional, default 'metNames')
-0012 %   supressWarnings logical whether warnings should be supressed (optional,
-0013 %                   default false)
-0014 %   copyToComps     logical whether mergeModels is run via copyToComps
-0015 %                   (optional, default false)
-0016 %
-0017 % Output:
-0018 %   model           a model structure with the merged model. Follows the
-0019 %                   structure of normal models but also has 'rxnFrom/
-0020 %                   metFrom/geneFrom' fields to indicate from which model
-0021 %                   each reaction/metabolite/gene was taken. If the model
-0022 %                   already has 'rxnFrom/metFrom/geneFrom' fields, then
-0023 %                   these fields are not modified.
-0024 %
-0025 % Usage: model=mergeModels(models)
-0026 
-0027 arguments
-0028     models;
-0029     metParam {emptyOrTextScalar} = "metNames"
-0030     supressWarnings {emptyOrLogicalScalar} = false
-0031     copyToComps {emptyOrLogicalScalar} = false
-0032 end
-0033 
-0034 metParam = char(metParam);
-0035 
-0036 %Just return the model
-0037 if numel(models)<=1
-0038     model=models{1};
-0039     return;
-0040 end
-0041 
-0042 hasMetFrom  = cellfun(@(s) isfield(s,'metFrom'), models);
-0043 hasGeneFrom = cellfun(@(s) isfield(s,'geneFrom'), models);
-0044 hasRxnFrom  = cellfun(@(s) isfield(s,'rxnFrom'), models);
-0045 
-0046 for i = 1:numel(models)
-0047     if copyToComps
-0048         if hasMetFrom(1)
-0049             models{2}.metFrom = repmat({''},numel(models{i}.mets),1);
-0050         end
-0051     elseif ~any(hasMetFrom)
-0052         models{i}.metFrom = repmat({models{i}.id},numel(models{i}.mets),1);
-0053     elseif ~hasMetFrom(i)
-0054         models{i}.metFrom = repmat({''},numel(models{i}.mets),1);
-0055     end
-0056     if copyToComps
-0057         if hasRxnFrom(1)
-0058             models{2}.rxnFrom = repmat({''},numel(models{i}.rxns),1);
-0059         end
-0060     elseif ~any(hasRxnFrom)
-0061         models{i}.rxnFrom = repmat({models{i}.id},numel(models{i}.rxns),1);
-0062     elseif ~hasRxnFrom(i)
-0063         models{i}.rxnFrom = repmat({''},numel(models{i}.rxns),1);
-0064     end
-0065     if copyToComps
-0066         if hasGeneFrom(1)
-0067             models{2}.geneFrom = repmat({''},numel(models{i}.genes),1);
-0068         end
-0069     elseif ~any(hasGeneFrom) && any(cellfun(@(s) isfield(s,'genes'), models))
-0070         models{i}.geneFrom = repmat({models{i}.id},numel(models{i}.genes),1);
-0071     elseif ~hasGeneFrom(i)
-0072         models{i}.geneFrom = repmat({''},numel(models{i}.genes),1);
-0073     end
-0074 end
-0075 
-0076 %Add new functionality in the order specified in models
-0077 model=models{1};
-0078 model.id='MERGED';
-0079 model.name='';
-0080 
-0081 if isfield(model,'equations')
-0082     model=rmfield(model,'equations');
-0083 end
-0084 
-0085 for i=1:numel(models)
-0086     if isfield(models{i},'subSystems')
-0087         models{i}.subSystems = cellfun(@(x) {x}, models{i}.subSystems, 'uni', 0);
-0088     end
-0089 end
-0090 for i=2:numel(models)
-0091     %Add the model id to the rxn id id it already exists in the model (id
-0092     %have to be unique) This is because it makes a '[]' string if no new
-0093     %reactions
-0094     if ~isempty(models{i}.rxns)
-0095         I=ismember(models{i}.rxns,model.rxns);
-0096         models{i}.rxns(I)=strcat(models{i}.rxns(I),['_' models{i}.id]);
-0097     end
-0098     
-0099     %Make sure that there are no conflicting reaction ids
-0100     [~, ~, conflicting]=intersect(model.rxns,models{i}.rxns);
-0101     
-0102     if ~isempty(conflicting)
-0103         printString=cell(numel(conflicting),1);
-0104         for j=1:numel(conflicting)
-0105             printString{j}=['Old: ' models{i}.rxns{conflicting(j)} ' New: ' models{i}.rxns{conflicting(j)} '_' models{i}.id];
-0106             models{i}.rxns{conflicting(j)}=[models{i}.rxns{conflicting(j)} '_' models{i}.id];
-0107         end
-0108         if supressWarnings==false
-0109             EM=['The following reaction IDs in ' models{i}.id ' are already present in the model and were renamed:'];
-0110             dispEM(EM,false,printString);
-0111             fprintf('\n');
-0112         end
-0113     end
-0114     
-0115     %Add all static stuff
-0116     if any(hasRxnFrom) || (~copyToComps && ~any(hasRxnFrom))
-0117         model.rxnFrom  = [model.rxnFrom;  models{i}.rxnFrom];
-0118     end
-0119     model.rxns     = [model.rxns;     models{i}.rxns];
-0120     model.rxnNames = [model.rxnNames; models{i}.rxnNames];
-0121     model.lb       = [model.lb;       models{i}.lb];
-0122     model.ub       = [model.ub;       models{i}.ub];
-0123     model.c        = [model.c;        models{i}.c];
-0124     model.rev      = [model.rev;      models{i}.rev];
-0125     
-0126     if isfield(models{i},'subSystems')
-0127         if isfield(model,'subSystems')
-0128             model.subSystems=[model.subSystems;models{i}.subSystems];
-0129         else
-0130             emptySubSystem=cell(numel(model.rxns)-numel(models{i}.rxns),1);
-0131             emptySubSystem(:)={''};
-0132             emptySubSystem=cellfun(@(x) cell(0,0),emptySubSystem,'UniformOutput',false);
-0133             model.subSystems=[emptySubSystem;models{i}.subSystems];
-0134         end
-0135     else
-0136         if isfield(model,'subSystems')
-0137             emptySubSystem=cell(numel(models{i}.rxns),1);
-0138             emptySubSystem(:)={''};
-0139             emptySubSystem=cellfun(@(x) cell(0,0),emptySubSystem,'UniformOutput',false);
-0140             model.subSystems=[model.subSystems;emptySubSystem];
-0141         end
-0142     end
-0143     
-0144     if isfield(models{i},'eccodes')
-0145         if isfield(model,'eccodes')
-0146             model.eccodes=[model.eccodes;models{i}.eccodes];
-0147         else
-0148             emptyEC=cell(numel(model.rxns)-numel(models{i}.rxns),1);
-0149             emptyEC(:)={''};
-0150             model.eccodes=[emptyEC;models{i}.eccodes];
-0151         end
-0152     else
-0153         if isfield(model,'eccodes')
-0154             emptyEC=cell(numel(models{i}.rxns),1);
-0155             emptyEC(:)={''};
-0156             model.eccodes=[model.eccodes;emptyEC];
-0157         end
-0158     end
-0159     
-0160     if isfield(models{i},'rxnMiriams')
-0161         if isfield(model,'rxnMiriams')
-0162             model.rxnMiriams=[model.rxnMiriams;models{i}.rxnMiriams];
-0163         else
-0164             model.rxnMiriams=[cell(numel(model.rxns)-numel(models{i}.rxns),1);models{i}.rxnMiriams];
-0165         end
-0166     else
-0167         if isfield(model,'rxnMiriams')
-0168             model.rxnMiriams=[model.rxnMiriams;cell(numel(models{i}.rxns),1)];
-0169         end
-0170     end
-0171     
-0172     if isfield(models{i},'rxnNotes')
-0173         if isfield(model,'rxnNotes')
-0174             model.rxnNotes=[model.rxnNotes;models{i}.rxnNotes];
-0175         else
-0176             emptyNotes=cell(numel(model.rxns)-numel(models{i}.rxns),1);
-0177             emptyNotes(:)={''};
-0178             model.rxnNotes=[emptyNotes;models{i}.rxnNotes];
-0179         end
-0180     else
-0181         if isfield(model,'rxnNotes')
-0182             emptyNotes=cell(numel(models{i}.rxns),1);
-0183             emptyNotes(:)={''};
-0184             model.rxnNotes=[model.rxnNotes;emptyNotes];
-0185         end
-0186     end
-0187     
-0188     if isfield(models{i},'rxnReferences')
-0189         if isfield(model,'rxnReferences')
-0190             model.rxnReferences=[model.rxnReferences;models{i}.rxnReferences];
-0191         else
-0192             emptyReferences=cell(numel(model.rxns)-numel(models{i}.rxns),1);
-0193             emptyReferences(:)={''};
-0194             model.rxnReferences=[emptyReferences;models{i}.rxnReferences];
-0195         end
-0196     else
-0197         if isfield(model,'rxnReferences')
-0198             emptyReferences=cell(numel(models{i}.rxns),1);
-0199             emptyReferences(:)={''};
-0200             model.rxnReferences=[model.rxnReferences;emptyReferences];
-0201         end
-0202     end
-0203     
-0204     if isfield(models{i},'rxnConfidenceScores')
-0205         if isfield(model,'rxnConfidenceScores')
-0206             model.rxnConfidenceScores=[model.rxnConfidenceScores;models{i}.rxnConfidenceScores];
-0207         else
-0208             model.rxnConfidenceScores=[NaN(numel(model.rxns)-numel(models{i}.rxns),1);models{i}.rxnConfidenceScores];
-0209         end
-0210     else
-0211         if isfield(model,'rxnConfidenceScores')
-0212             model.rxnConfidenceScores=[model.rxnConfidenceScores;NaN(numel(models{i}.rxns),1)];
-0213         end
-0214     end
-0215 
-0216     if isfield(models{i},'rxnDeltaG')
-0217         if isfield(model,'rxnDeltaG')
-0218             model.rxnDeltaG=[model.rxnDeltaG;models{i}.rxnDeltaG];
-0219         else
-0220             model.rxnDeltaG=[NaN(numel(model.rxns)-numel(models{i}.rxns),1);models{i}.rxnDeltaG];
-0221         end
-0222     else
-0223         if isfield(model,'rxnDeltaG')
-0224             model.rxnDeltaG=[model.rxnDeltaG;NaN(numel(models{i}.rxns),1)];
-0225         end
-0226     end
-0227     
-0228     if isfield(models{i},'rxnComps')
-0229         if isfield(model,'rxnComps')
-0230             model.rxnComps=[model.rxnComps;models{i}.rxnComps];
-0231         else
-0232             model.rxnComps=[ones(numel(model.rxns)-numel(models{i}.rxns),1);models{i}.rxnComps];
-0233             fprintf('NOTE: One of the models does not contain compartment information for its reactions. All reactions in that model has been assigned to the first compartment\n');
-0234         end
-0235     else
-0236         if isfield(model,'rxnComps')
-0237             model.rxnComps=[model.rxnComps;ones(numel(models{i}.rxns),1)];
-0238             fprintf('NOTE: One of the models does not contain compartment information for its reactions. All reactions in that model has been assigned to the first compartment\n');
-0239         end
-0240     end
-0241     
-0242     if isfield(models{i},'rxnScores')
-0243         if isfield(model,'rxnScores')
-0244             model.rxnScores=[model.rxnScores;models{i}.rxnScores];
-0245         else
-0246             emptyRS=zeros(numel(model.rxns)-numel(models{i}.rxns),1);
-0247             model.rxnScores=[emptyRS;models{i}.rxnScores];
-0248         end
-0249     else
-0250         if isfield(model,'rxnScores')
-0251             emptyRS=zeros(numel(models{i}.rxns),1);
-0252             model.rxnScores=[model.rxnScores;emptyRS];
-0253         end
-0254     end
-0255     
-0256     if isfield(models{i},'pwys')
-0257         if isfield(model,'pwys')
-0258             model.pwys=[model.pwys;models{i}.pwys];
-0259         else
-0260             model.pwys=[cell(numel(model.rxns)-numel(models{i}.rxns),1);models{i}.pwys];
-0261         end
-0262     else
-0263         if isfield(model,'pwys')
-0264             model.pwys=[model.pwys;cell(numel(models{i}.rxns),1)];
-0265         end
-0266     end
-0267 
-0268     if strcmpi(metParam,'metNames')
-0269     %Get the new metabolites from matching the models. Metabolites are said
-0270     %to be the same if they share name and compartment id. This means that
-0271     %metabolite IDs are not taken into account.
-0272         
-0273         oldMetComps=model.comps(model.metComps);
-0274         oldMets=strcat(model.metNames,'[',oldMetComps,']');
-0275         %This is because it makes a '[]' string if no new metabolites
-0276         if ~isempty(models{i}.metNames)
-0277             newMetComps=models{i}.comps(models{i}.metComps);
-0278             newMets=strcat(models{i}.metNames,'[',newMetComps,']');
-0279         else
-0280             newMets={};
-0281             newMetComps={};
-0282         end
-0283         tf=ismember(newMets,oldMets);
-0284         metsToAdd=find(~tf);
-0285 
-0286     end
-0287 
-0288     if strcmpi(metParam,'mets')
-0289     %Get the new metabolites from matching the models. Metabolites are matched by metabolite ID (model.mets).
-0290 
-0291         oldMets=model.mets;
-0292     
-0293         if ~isempty(models{i}.mets)
-0294             newMetComps=models{i}.comps(models{i}.metComps);
-0295             newMets=models{i}.mets;
-0296         else
-0297             newMets={};
-0298             newMetComps={};
-0299         end
-0300         tf=ismember(newMets,oldMets);
-0301         metsToAdd=find(~tf);
-0302 
-0303     end
-0304     
-0305     %First add the new metabolites Make sure that there are no conflicting
-0306     %metabolite ids
-0307     conflicting=ismember(models{i}.mets(metsToAdd),model.mets);
-0308     
-0309     conflicting=find(conflicting);
-0310     
-0311     if ~isempty(conflicting)
-0312         printString=cell(numel(conflicting),1);
-0313         for j=1:numel(conflicting)
-0314             printString{j}=['Old: ' models{i}.mets{metsToAdd(conflicting(j))} ' New: ' models{i}.mets{metsToAdd(conflicting(j))} '_' models{i}.id];
-0315             models{i}.mets{metsToAdd(conflicting(j))}=[models{i}.mets{metsToAdd(conflicting(j))} '_' models{i}.id];
-0316         end
-0317         if supressWarnings==false
-0318             EM=['The following metabolite IDs in ' models{i}.id ' are already present in the model and were renamed:'];
-0319             dispEM(EM,false,printString);
-0320         end
-0321     end
-0322     
-0323     %Add static info on the metabolites
-0324     if any(hasMetFrom) || (~copyToComps && ~any(hasMetFrom))
-0325         model.metFrom  = [model.metFrom;  models{i}.metFrom(metsToAdd)];
-0326     end
-0327     model.mets     = [model.mets;     models{i}.mets(metsToAdd)];
-0328     model.metNames = [model.metNames; models{i}.metNames(metsToAdd)];
-0329     model.b        = [model.b;        zeros(numel(metsToAdd),size(model.b,2))];
-0330     
-0331     if isfield(model,'unconstrained')
-0332         if isfield(models{i},'unconstrained')
-0333             model.unconstrained=[model.unconstrained;models{i}.unconstrained(metsToAdd)];
-0334         else
-0335             model.unconstrained=[model.unconstrained;zeros(numel(metsToAdd),1)];
-0336         end
-0337     else
-0338         if isfield(models{i},'unconstrained')
-0339             model.unconstrained=[zeros(numel(model.mets),1);models{i}.unconstrained(metsToAdd)];
-0340         end
-0341     end
-0342     
-0343     %Only add extra info on new metabolites since it's a little tricky to
-0344     %chose what to keep otherwise. Should change in the future
-0345 
-0346     if ~isempty(metsToAdd)
-0347         if isfield(models{i},'inchis')
-0348             if isfield(model,'inchis')
-0349                 model.inchis=[model.inchis;models{i}.inchis(metsToAdd)];
-0350             else
-0351                 emptyInchi=cell(numel(model.mets)-numel(metsToAdd),1);
-0352                 emptyInchi(:)={''};
-0353                 model.inchis=[emptyInchi;models{i}.inchis(metsToAdd)];
-0354             end
-0355         else
-0356             if isfield(model,'inchis')
-0357                 emptyInchi=cell(numel(metsToAdd),1);
-0358                 emptyInchi(:)={''};
-0359                 model.inchis=[model.inchis;emptyInchi];
-0360             end
-0361         end
-0362 
-0363         if isfield(models{i},'metSmiles')
-0364             if isfield(model,'metSmiles')
-0365                 model.metSmiles=[model.metSmiles;models{i}.metSmiles(metsToAdd)];
-0366             else
-0367                 emptyInchi=cell(numel(model.mets)-numel(metsToAdd),1);
-0368                 emptyInchi(:)={''};
-0369                 model.metSmiles=[emptyInchi;models{i}.metSmiles(metsToAdd)];
-0370             end
-0371         else
-0372             if isfield(model,'metSmiles')
-0373                 emptyInchi=cell(numel(metsToAdd),1);
-0374                 emptyInchi(:)={''};
-0375                 model.metSmiles=[model.metSmiles;emptyInchi];
-0376             end
-0377         end
-0378         
-0379         if isfield(models{i},'metFormulas')
-0380             if isfield(model,'metFormulas')
-0381                 model.metFormulas=[model.metFormulas;models{i}.metFormulas(metsToAdd)];
-0382             else
-0383                 emptyMetFormulas=cell(numel(model.mets)-numel(metsToAdd),1);
-0384                 emptyMetFormulas(:)={''};
-0385                 model.metFormulas=[emptyMetFormulas;models{i}.metFormulas(metsToAdd)];
-0386             end
-0387         else
-0388             if isfield(model,'metFormulas')
-0389                 emptyMetFormulas=cell(numel(metsToAdd),1);
-0390                 emptyMetFormulas(:)={''};
-0391                 model.metFormulas=[model.metFormulas;emptyMetFormulas];
-0392             end
-0393         end
-0394         
-0395         if isfield(models{i},'metCharges')
-0396             if isfield(model,'metCharges')
-0397                 model.metCharges=[model.metCharges;models{i}.metCharges(metsToAdd)];
-0398             else
-0399                 emptyMetCharge=nan(numel(model.mets)-numel(metsToAdd),1);
-0400                 model.metCharges=[emptyMetCharge;models{i}.metCharges(metsToAdd)];
-0401             end
-0402         else
-0403             if isfield(model,'metCharges')
-0404                 emptyMetCharge=nan(numel(metsToAdd),1);
-0405                 model.metCharges=[model.metCharges;emptyMetCharge];
-0406             end
-0407         end
-0408 
-0409         if isfield(models{i},'metDeltaG')
-0410             if isfield(model,'metDeltaG')
-0411                 model.metDeltaG=[model.metDeltaG;models{i}.metDeltaG(metsToAdd)];
-0412             else
-0413                 emptyMetCharge=nan(numel(model.mets)-numel(metsToAdd),1);
-0414                 model.metDeltaG=[emptyMetCharge;models{i}.metDeltaG(metsToAdd)];
-0415             end
-0416         else
-0417             if isfield(model,'metDeltaG')
-0418                 emptyMetCharge=nan(numel(metsToAdd),1);
-0419                 model.metDeltaG=[model.metDeltaG;emptyMetCharge];
-0420             end
-0421         end
-0422         
-0423         if isfield(models{i},'metMiriams')
-0424             if isfield(model,'metMiriams')
-0425                 model.metMiriams=[model.metMiriams;models{i}.metMiriams(metsToAdd)];
-0426             else
-0427                 emptyMetMiriam=cell(numel(model.mets)-numel(metsToAdd),1);
-0428                 model.metMiriams=[emptyMetMiriam;models{i}.metMiriams(metsToAdd)];
-0429             end
-0430         else
-0431             if isfield(model,'metMiriams')
-0432                 emptyMetMiriam=cell(numel(metsToAdd),1);
-0433                 model.metMiriams=[model.metMiriams;emptyMetMiriam];
-0434             end
-0435         end
-0436     end
-0437     
-0438     %Add if there are any new compartments and add those. This can change
-0439     %the order of compartments and the corresponding indexes in
-0440     %model.metComps.
-0441     
-0442     %Find overlapping and new compartments
-0443     [overlap, oldIDs]=ismember(models{i}.comps,model.comps);
-0444     overlap=find(overlap);
-0445     
-0446     %Add the new compartments if any
-0447     if numel(overlap)~=numel(models{i}.compNames)
-0448         compIndexes=oldIDs==0;
-0449         
-0450         %Make sure that there are no conflicting compartment ids
-0451         [~, conflicting]=ismember(models{i}.compNames(compIndexes),model.compNames);
-0452         if any(conflicting)
-0453             EM=['The following compartment IDs in ' models{i}.id ' are already present in the model but with another name. They have to be renamed'];
-0454             dispEM(EM,true,model.comps(conflicting));
-0455         end
-0456         
-0457         %It's ok to add duplicate name, but not duplicate IDs
-0458         model.compNames=[model.compNames; models{i}.compNames(compIndexes)];
-0459         model.comps=[model.comps; models{i}.comps(compIndexes)];
-0460         if isfield(model,'compOutside')
-0461             if isfield(models{i},'compOutside')
-0462                 model.compOutside=[model.compOutside; models{i}.compOutside(compIndexes)];
-0463             else
-0464                 %This is if not all models have the field
-0465                 padding=cell(sum(compIndexes),1);
-0466                 padding(:)={''};
-0467                 model.compOutside=[model.compOutside;padding];
-0468             end
-0469         end
-0470         if isfield(model,'compMiriams')
-0471             if isfield(models{i},'compMiriams')
-0472                 model.compMiriams=[model.compMiriams; models{i}.compMiriams(compIndexes)];
-0473             else
-0474                 %This is if not all models have the field
-0475                 model.compMiriams=[model.compMiriams;cell(sum(compIndexes),1)];
-0476             end
-0477         end
-0478     end
-0479     
-0480     %Only add new comp info on the un-matched metabolites since the old
-0481     %ones will be mapped to the existing list anyways
-0482     [I, J]=ismember(newMetComps(metsToAdd),model.comps);
-0483     %Just a check
-0484     if ~all(I)
-0485         EM='There was an unexpected error in matching compartments';
-0486         dispEM(EM);
-0487     end
-0488     model.metComps=[model.metComps;J];
-0489      
-0490     %Create the new stoichiometric matrix
-0491     model.S=[model.S;sparse(numel(metsToAdd),size(model.S,2))];
-0492     
-0493 
-0494     if strcmpi(metParam,'metNames')
-0495         %Rematch metabolite names. Not the most clever way to do it maybe
-0496         allMets=strcat(model.metNames,'[',model.comps(model.metComps),']');
-0497         [~, J]=ismember(newMets,allMets);
-0498     end
-0499 
-0500     if strcmpi(metParam,'mets')
-0501         %Rematch metabolite by IDs and add unique new metabolites
-0502         allMets=model.mets;
-0503         uniqueNewMets = setdiff(newMets,oldMets);
-0504         allMets(end+1:end+numel(uniqueNewMets)) = uniqueNewMets;
-0505         [~, J]=ismember(newMets,allMets);
-0506     end
-0507 
-0508     %Update the stoichiometric matrix for the model to add
-0509     newS=sparse(numel(model.mets),numel(models{i}.rxns));
-0510     newS(J,:)=models{i}.S;
-0511     model.S=[model.S newS];
-0512 
-0513     
-0514     %Now add new genes
-0515     if isfield(models{i},'genes')
-0516         if ~isfield(model,'genes')
-0517             %If there was no gene info before
-0518             model.genes      = models{i}.genes;
-0519             model.rxnGeneMat = [sparse(numel(model.rxns),numel(models{i}.genes));models{i}.rxnGeneMat];
-0520             emptyGene        = repmat({''},numel(model.rxns),1);
-0521             model.grRules    = [emptyGene;models{i}.grRules];
-0522             if any(hasGeneFrom) || (~copyToComps && ~any(hasGeneFrom))
-0523                 model.geneFrom   = models{i}.geneFrom;
-0524             end
-0525             
-0526             if isfield(models{i},'geneShortNames')
-0527                 model.geneShortNames=models{i}.geneShortNames;
-0528             end
-0529 
-0530             if isfield(models{i},'proteins')
-0531                 model.proteins=models{i}.proteins;
-0532             end
-0533 
-0534             if isfield(models{i},'geneMiriams')
-0535                 model.geneMiriams=models{i}.geneMiriams;
-0536             end
-0537             
-0538             if isfield(models{i},'geneComps')
-0539                 model.geneComps=models{i}.geneComps;
-0540             end
-0541         else
-0542             %If gene info should be merged
-0543             a=ismember(models{i}.genes,model.genes);
-0544             
-0545             genesToAdd=find(~a);
-0546             
-0547             %Only add extra gene info on new genes. This might not be
-0548             %correct and should be changed later...
-0549             if ~isempty(genesToAdd)
-0550                 model.genes      = [model.genes;        models{i}.genes(genesToAdd)];
-0551                 model.geneFrom   = [model.geneFrom;     models{i}.geneFrom(genesToAdd)];
-0552                 model.rxnGeneMat = [model.rxnGeneMat    sparse(size(model.rxnGeneMat,1),numel(genesToAdd))];
-0553                 
-0554                 if isfield(models{i},'geneShortNames')
-0555                     if isfield(model,'geneShortNames')
-0556                         model.geneShortNames=[model.geneShortNames;models{i}.geneShortNames(genesToAdd)];
-0557                     else
-0558                         emptyGeneSN=cell(numel(model.genes)-numel(genesToAdd),1);
-0559                         emptyGeneSN(:)={''};
-0560                         model.geneShortNames=[emptyGeneSN;models{i}.geneShortNames(genesToAdd)];
-0561                     end
-0562                 else
-0563                     if isfield(model,'geneShortNames')
-0564                         emptyGeneSN=cell(numel(genesToAdd),1);
-0565                         emptyGeneSN(:)={''};
-0566                         model.geneShortNames=[model.geneShortNames;emptyGeneSN];
-0567                     end
-0568                 end
-0569 
-0570                 if isfield(models{i},'proteins')
-0571                     if isfield(model,'proteins')
-0572                         model.proteins=[model.proteins;models{i}.proteins(genesToAdd)];
-0573                     else
-0574                         emptyGeneSN=cell(numel(model.genes)-numel(genesToAdd),1);
-0575                         emptyGeneSN(:)={''};
-0576                         model.proteins=[emptyGeneSN;models{i}.proteins(genesToAdd)];
-0577                     end
-0578                 else
-0579                     if isfield(model,'proteins')
-0580                         emptyGeneSN=cell(numel(genesToAdd),1);
-0581                         emptyGeneSN(:)={''};
-0582                         model.proteins=[model.proteins;emptyGeneSN];
-0583                     end
-0584                 end
-0585 
-0586                 if isfield(models{i},'geneMiriams')
-0587                     if isfield(model,'geneMiriams')
-0588                         model.geneMiriams=[model.geneMiriams;models{i}.geneMiriams(genesToAdd)];
-0589                     else
-0590                         emptyGeneMir=cell(numel(model.genes)-numel(genesToAdd),1);
-0591                         model.geneMiriams=[emptyGeneMir;models{i}.geneMiriams(genesToAdd)];
-0592                     end
-0593                 else
-0594                     if isfield(model,'geneMiriams')
-0595                         emptyGeneMir=cell(numel(genesToAdd),1);
-0596                         model.geneMiriams=[model.geneMiriams;emptyGeneMir];
-0597                     end
-0598                 end
-0599                 
-0600                 if isfield(models{i},'geneComps')
-0601                     if isfield(model,'geneComps')
-0602                         model.geneComps=[model.geneComps;models{i}.geneComps(genesToAdd)];
-0603                     else
-0604                         emptyGeneMir=ones(numel(model.genes)-numel(genesToAdd),1);
-0605                         model.geneComps=[emptyGeneMir;models{i}.geneComps(genesToAdd)];
-0606                         EM='Adding genes with compartment information to a model without such information. All existing genes will be assigned to the first compartment';
-0607                         dispEM(EM,false);
-0608                     end
-0609                 else
-0610                     if isfield(model,'geneComps')
-0611                         emptyGeneMir=ones(numel(genesToAdd),1);
-0612                         model.geneComps=[model.geneComps;emptyGeneMir];
-0613                         EM='Adding genes with compartment information to a model without such information. All existing genes will be assigned to the first compartment';
-0614                         dispEM(EM,false);
-0615                     end
-0616                 end
-0617             end
-0618             
-0619             %Remap the genes from the new model. The same thing as with
-0620             %mets; this is a wasteful way to do it but I do not care right
-0621             %now
-0622             a = ismember(models{i}.genes,model.genes);
-0623             
-0624             %Just a check
-0625             if ~all(a)
-0626                 EM='There was an unexpected error in matching genes';
-0627                 dispEM(EM);
-0628             end
-0629             model.grRules=[model.grRules;models{i}.grRules];
-0630         end
-0631     else
-0632         %Add empty gene associations
-0633         if isfield(model,'genes')
-0634             emptyGene=cell(numel(models{i}.rxns),1);
-0635             emptyGene(:)={''};
-0636             model.grRules=[model.grRules;emptyGene];
-0637         end
-0638     end
-0639 end
-0640 %Fix grRules and reconstruct rxnGeneMat
-0641 [grRules,rxnGeneMat] = standardizeGrRules(model,true);
-0642 model.grRules = grRules;
-0643 model.rxnGeneMat = rxnGeneMat;
-0644 %Flatten subSystems if possible
-0645 if isfield(model,'subSystems')
-0646     if all(cellfun(@(x) iscell(x) && isscalar(x), model.subSystems))
-0647         model.subSystems = transpose([model.subSystems{:}]);
-0648     end
-0649 end
-0650 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/parallelPoolRAVEN.html b/doc/core/parallelPoolRAVEN.html deleted file mode 100644 index be878bab6..000000000 --- a/doc/core/parallelPoolRAVEN.html +++ /dev/null @@ -1,123 +0,0 @@ - - - - Description of parallelPoolRAVEN - - - - - - - - - -
Home > core > parallelPoolRAVEN.m
- - - -

parallelPoolRAVEN -

- -

PURPOSE ^

-
handleParallelRAVEN
- -

SYNOPSIS ^

-
function [ps, oldPoolAutoCreate] = parallelPoolRAVEN(runParallel)
- -

DESCRIPTION ^

-
 handleParallelRAVEN
-   Called by RAVEN functions that support parallel processing, to confirm
-   whether the MATLAB Parallel Computing Toolbox is installed.
-   - The toolbox is installed, and runParallel == true, ==> a parallel
-     pool is started.
-   - The toolbox is installed, but runParallel == false, ==> the auto-
-     creation of a parallel pool is disabled, to prevent "parfor" in
-     the target function to start a pool anyway.
-   - The toolbox is not installed, and runParallel == true, ==> a warning
-     is displayed that parallel computer is not possible.
-   - The toolbox is not installed, and runParallel == false, ==> the
-     target runs as intended, as "parfor" will automatically run in serial
-     mode instead.
-
- Input:
-   runParallel         logical, whether the target function (which calls
-                       parallelPoolRAVEN) should be run in parallel (optional,
-                       default true)
-
- Output:
-   ps                  parallel settings structure that will be used by
-                       the target function    
-   oldPoolAutoCreate   logical, to reset the original ps.Pool.AutoCreate
-                       setting once the target function has finished
-
- Use: [ps, oldPoolAutoCreate] = parallelPoolRAVEN(runParallel)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function [ps, oldPoolAutoCreate] = parallelPoolRAVEN(runParallel)
-0002 % handleParallelRAVEN
-0003 %   Called by RAVEN functions that support parallel processing, to confirm
-0004 %   whether the MATLAB Parallel Computing Toolbox is installed.
-0005 %   - The toolbox is installed, and runParallel == true, ==> a parallel
-0006 %     pool is started.
-0007 %   - The toolbox is installed, but runParallel == false, ==> the auto-
-0008 %     creation of a parallel pool is disabled, to prevent "parfor" in
-0009 %     the target function to start a pool anyway.
-0010 %   - The toolbox is not installed, and runParallel == true, ==> a warning
-0011 %     is displayed that parallel computer is not possible.
-0012 %   - The toolbox is not installed, and runParallel == false, ==> the
-0013 %     target runs as intended, as "parfor" will automatically run in serial
-0014 %     mode instead.
-0015 %
-0016 % Input:
-0017 %   runParallel         logical, whether the target function (which calls
-0018 %                       parallelPoolRAVEN) should be run in parallel (optional,
-0019 %                       default true)
-0020 %
-0021 % Output:
-0022 %   ps                  parallel settings structure that will be used by
-0023 %                       the target function
-0024 %   oldPoolAutoCreate   logical, to reset the original ps.Pool.AutoCreate
-0025 %                       setting once the target function has finished
-0026 %
-0027 % Use: [ps, oldPoolAutoCreate] = parallelPoolRAVEN(runParallel)
-0028 
-0029 if nargin<1 || isempty(runParallel)
-0030     runParallel = true;
-0031 end
-0032 
-0033 addonList = matlab.addons.installedAddons;
-0034 ps = []; oldPoolAutoCreate = [];
-0035 if ~any(strcmpi(addonList.Name,'Parallel Computing Toolbox'))
-0036     if runParallel % User wants parallel, but will not be possible
-0037         disp('Cannot find MATLAB Parallel Computing Toolbox, process is not parallelized.')
-0038     end
-0039 else
-0040     pool = gcp('nocreate');
-0041     if ~runParallel % User has Parallel toolbox, but does not want pool to start.
-0042         % If pool is already running, delete it
-0043         ps = parallel.Settings;
-0044         oldPoolAutoCreate = ps.Pool.AutoCreate;
-0045         ps.Pool.AutoCreate = false;
-0046         delete(pool);
-0047     elseif isempty(pool)
-0048         parpool('IdleTimeout',120);
-0049     end
-0050 end
-0051 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/parseFormulas.html b/doc/core/parseFormulas.html deleted file mode 100644 index 2a99eeabf..000000000 --- a/doc/core/parseFormulas.html +++ /dev/null @@ -1,318 +0,0 @@ - - - - Description of parseFormulas - - - - - - - - - -
Home > core > parseFormulas.m
- - - -

parseFormulas -

- -

PURPOSE ^

-
parseFormulas
- -

SYNOPSIS ^

-
function [elements, useMat, exitFlag, MW]=parseFormulas(formulas, noPolymers,isInchi,ignoreRX)
- -

DESCRIPTION ^

-
 parseFormulas
-   Gets the elemental composition from formulas
-
-   formulas      a cell array with formulas
-   noPolymers    assume that all polymers consist of one element.
-                 Corresponds to counting everything between (...)n as
-                 n being equal to one. Only one set of parentheses
-                 is allowed. If this is false then polymers are returned as
-                 "Could not parse formula" (optional, default false)
-   isInchi       true if the formulas are in the InChI format (optional,
-                 default false)
-   ignoreRX      ignore R-groups and bound protein. This can be useful since they
-                 are often used only as intermediates (optional, default false)
-
-   elements
-       abbrevs   cell array with abbreviations for all used elements
-       names     cell array with the names for all used elements
-   useMat        MxN matrix with the number of atoms for each formula (M) and each
-                 element (N)
-   exitFlag      array with the exit flags:
-                 1=  Sucessful parsing
-                 0=  No formula found
-                 -1= Could not parse formula
-   MW            predicted molecular weight (g/mol). This is only returned
-                 for formulas which can be sucessfully parsed, and its
-                 calculation doesn't affect the exitFlag variable. NaN is
-                 returned if the weight couldn't be calculated
-   
- Usage: [elements, useMat, exitFlag, MW]=
-               parseFormulas(formulas, noPolymers,isInchi,ignoreRX)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function [elements, useMat, exitFlag, MW]=parseFormulas(formulas, noPolymers,isInchi,ignoreRX)
-0002 % parseFormulas
-0003 %   Gets the elemental composition from formulas
-0004 %
-0005 %   formulas      a cell array with formulas
-0006 %   noPolymers    assume that all polymers consist of one element.
-0007 %                 Corresponds to counting everything between (...)n as
-0008 %                 n being equal to one. Only one set of parentheses
-0009 %                 is allowed. If this is false then polymers are returned as
-0010 %                 "Could not parse formula" (optional, default false)
-0011 %   isInchi       true if the formulas are in the InChI format (optional,
-0012 %                 default false)
-0013 %   ignoreRX      ignore R-groups and bound protein. This can be useful since they
-0014 %                 are often used only as intermediates (optional, default false)
-0015 %
-0016 %   elements
-0017 %       abbrevs   cell array with abbreviations for all used elements
-0018 %       names     cell array with the names for all used elements
-0019 %   useMat        MxN matrix with the number of atoms for each formula (M) and each
-0020 %                 element (N)
-0021 %   exitFlag      array with the exit flags:
-0022 %                 1=  Sucessful parsing
-0023 %                 0=  No formula found
-0024 %                 -1= Could not parse formula
-0025 %   MW            predicted molecular weight (g/mol). This is only returned
-0026 %                 for formulas which can be sucessfully parsed, and its
-0027 %                 calculation doesn't affect the exitFlag variable. NaN is
-0028 %                 returned if the weight couldn't be calculated
-0029 %
-0030 % Usage: [elements, useMat, exitFlag, MW]=
-0031 %               parseFormulas(formulas, noPolymers,isInchi,ignoreRX)
-0032 
-0033 if nargin<2
-0034     noPolymers=false;
-0035 end
-0036 if nargin<3
-0037     isInchi=false;
-0038 end
-0039 if nargin<4
-0040     ignoreRX=false;
-0041 end
-0042 
-0043 elements.abbrevs={'C', 'N', 'O', 'S', 'P', 'H', 'He', 'Li', 'Be', 'B', 'F', 'Ne', 'Na', 'Mg', 'Al',...
-0044     'Si', 'Cl', 'Ar', 'K', 'Ca', 'Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe', 'Co', 'Ni',...
-0045     'Cu', 'Zn', 'Ga', 'Ge', 'As', 'Se', 'Br', 'Kr', 'Rb', 'Sr', 'Y', 'Zr', 'Nb', 'Mo', 'Tc',...
-0046     'Ru', 'Rh', 'Pd', 'Ag', 'Cd', 'In', 'Sn', 'Sb', 'Te', 'I', 'Xe', 'Cs', 'Ba', 'La', 'Ce',...
-0047     'Pr', 'Nd', 'Pm', 'Sm', 'Eu', 'Gd', 'Tb', 'Dy', 'Ho', 'Er', 'Tm', 'Yb', 'Lu', 'Hf', 'Ta',...
-0048     'W', 'Re', 'Os', 'Ir', 'Pt', 'Au', 'Hg', 'Tl', 'Pb', 'Bi', 'Po', 'At', 'Rn', 'Fr', 'Ra',...
-0049     'Ac', 'Th', 'Pa', 'U', 'Np', 'Pu', 'Am', 'Cm', 'Bk', 'Cf', 'Es', 'Fm', 'Md', 'No', 'Lr',...
-0050     'Rf', 'Db', 'Sg', 'Bh', 'Hs', 'Mt', 'Ds', 'Rg', 'Cn', 'R', 'X'}';
-0051 elements.names={'carbon', 'nitrogen', 'oxygen', 'sulfur', 'phosphorus', 'hydrogen', 'helium', 'lithium', 'beryllium', 'boron',...
-0052     'fluorine', 'neon', 'sodium', 'magnesium', 'aluminum,', 'silicon',...
-0053     'chlorine', 'argon', 'potassium', 'calcium', 'scandium', 'titanium', 'vanadium',...
-0054     'chromium', 'manganese', 'iron', 'cobalt', 'nickel', 'copper', 'zinc', 'gallium', 'germanium',...
-0055     'arsenic', 'selenium', 'bromine', 'krypton', 'rubidium', 'strontium', 'yttrium', 'zirconium',...
-0056     'niobium', 'molybdenum', 'technetium', 'ruthenium', 'rhodium', 'palladium', 'silver', 'cadmium',...
-0057     'indium', 'tin', 'antimony', 'tellurium', 'iodine', 'xenon', 'cesium', 'barium', 'lanthanum',...
-0058     'cerium', 'praseodymium', 'neodymium', 'promethium', 'samarium', 'europium', 'gadolinium',...
-0059     'terbium', 'dysprosium', 'holmium', 'erbium', 'thulium', 'ytterbium', 'lutetium', 'hafnium',...
-0060     'tantalum', 'tungsten', 'rhenium', 'osmium', 'iridium', 'platinum', 'gold', 'mercury',...
-0061     'thallium', 'lead', 'bismuth', 'polonium', 'astatine', 'radon', 'francium', 'radium',...
-0062     'actinium', 'thorium', 'protactinium', 'uranium', 'neptunium', 'plutonium', 'americium',...
-0063     'curium', 'berkelium', 'californium', 'einsteinium', 'fermium', 'mendelevium', 'nobelium',...
-0064     'lawrencium', 'rutherfordium', 'dubnium', 'seaborgium', 'bohrium', 'hassium', 'meitnerium',...
-0065     'darmstadtium', 'roentgenium', 'copernicium', 'generic group', 'bound protein'}';
-0066 
-0067 EWs=[12.0107 14.0067 15.9994 32.065 30.973762 1.00794 4.002602 6.941 9.012182 10.811 18.9984032 ...
-0068     20.1797 22.98976928 24.305 26.9815386 28.0855 35.453 39.948 39.0983 40.078 44.955912 47.867 50.9415 ...
-0069     51.9961 54.938045 55.845 58.933195 58.6934 63.546 65.39 69.723 72.64 74.9216 78.96 79.904 83.798 ...
-0070     85.4678 87.62 88.90585 91.224 92.906 95.94 97.9072 101.07 102.905 106.42 107.8682 112.411 114.818 ...
-0071     118.71 121.76 127.6 126.904 131.293 132.9054519 137.327 138.90547 140.116 140.90765 144.242 144.9127 ...
-0072     150.36 151.964 157.25 158.92535 162.5 164.93 167.259 168.93421 173.04 174.967 178.49 180.94788 183.84 ...
-0073     186.207 190.23 192.217 195.084 196.966569 200.59 204.3833 207.2 208.9804 208.9824 209.9871 222.0176 ...
-0074     223.0197 226.0254 227.0277 232.03806 231.03588 238.02891 237.0482 244.0642 243.0614 247.0704 247.0703 ...
-0075     251.0796 252.083 257.0951 258.0984 259.101 262.1097 261.1088 262 266 264 277 268 271 272 nan nan nan]';
-0076 
-0077 %Set the EWs of these groups to 0
-0078 if ignoreRX==true
-0079     EWs(end-1:end)=0;
-0080 end
-0081 
-0082 useMat=zeros(numel(formulas),numel(elements.abbrevs));
-0083 
-0084 exitFlag=zeros(numel(formulas),1);
-0085 
-0086 %"H+", if parsed from InChI code, would have the composition "p+1". Change
-0087 %to fit with how the rest of the compounds are written
-0088 formulas=strrep(formulas,'p+1','H+');
-0089 
-0090 %Ignore charge to make the parsing easier
-0091 formulas=strrep(formulas,'+','');
-0092 formulas=strrep(formulas,'-','');
-0093 
-0094 %Loop through each formula
-0095 for i=1:numel(formulas)
-0096     if ~isempty(formulas{i})
-0097         sucess=false; %To see if it works
-0098         formula=formulas{i};
-0099         
-0100         %If it's an InChI code. The composition is found between the first
-0101         %and the second "/" For some simple molecules such as salts only
-0102         %the first "/" is present
-0103         if isInchi==true
-0104             S=regexp(formula,'/','split');
-0105             if numel(S)>=2
-0106                 formula=S{2};
-0107             else
-0108                 formula='';
-0109             end
-0110         end
-0111         %Only look at what's between the parantheses (polymers are not
-0112         %supported in InChI)
-0113         if isInchi==false
-0114             LP=strfind(formula,'(');
-0115             RP=strfind(formula,')n');
-0116             %            if numel(LP)>1 || numel(RP)>1
-0117             %               exitFlag(i)=-1; continue;
-0118             %            end if numel(LP)>1 || numel(RP)>1
-0119             %               exitFlag(i)=-1; continue;
-0120             %            end
-0121             if numel(LP)==1 && numel(RP)==1
-0122                 %This means that the polymer should be regarded as a
-0123                 %monomer
-0124                 if noPolymers==true
-0125                     %This means that there are one set of parantheses
-0126                     formula=strrep(formula,'(','');
-0127                     formula=strrep(formula,')n','');
-0128                 else
-0129                     %This means that polymers should be ignored
-0130                     exitFlag(i)=-1;
-0131                     continue;
-0132                 end
-0133             else
-0134                 if ~isempty(LP) || ~isempty(RP)
-0135                     exitFlag(i)=-1;
-0136                     continue;
-0137                 end
-0138             end
-0139         end
-0140         
-0141         %Get the indexes of the numeric (or ".") characters
-0142         nonNumeric=false(numel(formula),1);
-0143         nonNumeric(regexp(formula,'[^0-9.]'))=true;
-0144         
-0145         %Get the indexes of the upper characters (since each element starts
-0146         %with an upper character)
-0147         upperI=isstrprop(formula,'upper');
-0148         upperX=find(upperI);
-0149         
-0150         for j=1:numel(upperX)
-0151             %The first case is when it's the last character. Then the
-0152             %coefficient must be 1
-0153             isLast=false;
-0154             if upperX(j)==numel(formula)
-0155                 coeff=1;
-0156                 element=formula(upperX(j));
-0157                 isLast=true;
-0158             end
-0159             
-0160             if isLast==false
-0161                 %The second case is when the following character is a
-0162                 %character
-0163                 if nonNumeric(upperX(j)+1)
-0164                     %Is it a new element?
-0165                     if upperI(upperX(j)+1)
-0166                         %New element, that means that the coefficient was 1
-0167                         %and that the element was only one character
-0168                         coeff=1;
-0169                         element=formula(upperX(j));
-0170                     else
-0171                         %This means that it's an element with two
-0172                         %characters
-0173                         if j==numel(upperX)
-0174                             if upperX(j)<numel(formula)-1
-0175                                 coeff=str2double(formula(upperX(j)+2:end));
-0176                             else
-0177                                 coeff=1;
-0178                             end
-0179                         else
-0180                             %Check if there is a number or a new element
-0181                             %after it
-0182                             if nonNumeric(upperX(j)+2)==true
-0183                                 coeff=1;
-0184                             else
-0185                                 coeff=str2double(formula(upperX(j)+2:upperX(j+1)-1));
-0186                             end
-0187                         end
-0188                         element=formula(upperX(j):upperX(j)+1);
-0189                     end
-0190                 else
-0191                     %Then it is a numeral
-0192                     if j==numel(upperX)
-0193                         coeff=str2double(formula(upperX(j)+1:end));
-0194                     else
-0195                         coeff=str2double(formula(upperX(j)+1:upperX(j+1)-1));
-0196                     end
-0197                     element=formula(upperX(j));
-0198                 end
-0199             end
-0200             
-0201             %Find the element
-0202             I=strcmp(element,elements.abbrevs);
-0203             if any(I)
-0204                 if ~isnan(coeff)
-0205                     useMat(i,I)=useMat(i,I)+coeff;
-0206                     sucess=true;
-0207                 else
-0208                     break;
-0209                 end
-0210             else
-0211                 break;
-0212             end
-0213         end
-0214         if sucess==false
-0215             useMat(i,:)=0; %Reset for this formula
-0216             exitFlag(i)=-1;
-0217         else
-0218             exitFlag(i)=1;
-0219         end
-0220     end
-0221 end
-0222 
-0223 %Remove the elements which are never used
-0224 I=~any(useMat);
-0225 useMat(:,I)=[];
-0226 elements.abbrevs(I)=[];
-0227 elements.names(I)=[];
-0228 EWs(I)=[];
-0229 
-0230 %Calcluate the weight contribution of each element in each formula. Note
-0231 %that this will give NaNs for all formulas if R or X groups are in EWs,
-0232 %since 0*NaN is still NaN. Therefore only use elements with known mass
-0233 if nargout>3
-0234     P=bsxfun(@times,useMat(:,~isnan(EWs)),EWs(~isnan(EWs)).');
-0235     MW=sum(P,2);
-0236     
-0237     %Then remove the calculations for elements with unknown mass
-0238     I=find(useMat(:,isnan(EWs)));
-0239     MW(I)=nan;
-0240     MW(exitFlag~=1)=nan;
-0241 end
-0242 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/parseRxnEqu.html b/doc/core/parseRxnEqu.html deleted file mode 100644 index 81d3bff56..000000000 --- a/doc/core/parseRxnEqu.html +++ /dev/null @@ -1,135 +0,0 @@ - - - - Description of parseRxnEqu - - - - - - - - - -
Home > core > parseRxnEqu.m
- - - -

parseRxnEqu -

- -

PURPOSE ^

-
parseRxnEqu
- -

SYNOPSIS ^

-
function metabolites=parseRxnEqu(equations)
- -

DESCRIPTION ^

-
 parseRxnEqu
-   Gets all metabolite names from a cell array of equations
-
-   metabolites=parseRxnEqu(equations)
-
-   equations     A cell array with equation strings
-
-   metabolites   A cell array with the involved metabolites
-
-   The equations should be written like:
-   1 A + 3 B (=> or <=>) 5C + 2 D
-
-   If the equation is expressed as for example '... + (n-1) starch' then
-   '(n-1) starch' will be interpreted as one metabolite
-
- Usage: metabolites=parseRxnEqu(equations)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function metabolites=parseRxnEqu(equations)
-0002 % parseRxnEqu
-0003 %   Gets all metabolite names from a cell array of equations
-0004 %
-0005 %   metabolites=parseRxnEqu(equations)
-0006 %
-0007 %   equations     A cell array with equation strings
-0008 %
-0009 %   metabolites   A cell array with the involved metabolites
-0010 %
-0011 %   The equations should be written like:
-0012 %   1 A + 3 B (=> or <=>) 5C + 2 D
-0013 %
-0014 %   If the equation is expressed as for example '... + (n-1) starch' then
-0015 %   '(n-1) starch' will be interpreted as one metabolite
-0016 %
-0017 % Usage: metabolites=parseRxnEqu(equations)
-0018 
-0019 if ~iscell(equations)
-0020     equations={equations};
-0021 end
-0022 
-0023 metabolites={};
-0024 
-0025 %Replace the the direction arrows and plus signs with a weird character
-0026 %that will be used for parsing
-0027 equations=strrep(equations,' <=> ', '€');
-0028 equations=strrep(equations,' => ', '€');
-0029 equations=strrep(equations,' + ', '€');
-0030 equations=strtrim(equations);
-0031 
-0032 for i=1:numel(equations)
-0033     %Split each equation in possible metabolites
-0034     candidates=regexp(equations{i},'€','split');
-0035     
-0036     %If the splitting character is at the end (if exchange rxns), then an
-0037     %empty string will exist together with the real ones. Remove it
-0038     candidates(cellfun(@isempty,candidates))=[];
-0039     
-0040     %Now remove the potential coefficient before each metabolite
-0041     for j=1:numel(candidates)
-0042         %If the metabolite has a coefficient it will look as 'number name'
-0043         space=strfind(candidates{j},' ');
-0044         
-0045         if isempty(space)
-0046             %Add the metabolite
-0047             metabolites=[metabolites;candidates(j)];
-0048         else
-0049             potNumber=candidates{j}(1:space(1));
-0050             %I use str2double here which can't deal with fractions (1/3 glc
-0051             %and so on). I do this because I don't want to risk calling
-0052             %functions
-0053             [~,isNumber]=str2num(potNumber);
-0054             
-0055             if isNumber==1
-0056                 %Remove the coefficient
-0057                 metName=candidates{j}(space(1)+1:end);
-0058                 metabolites=[metabolites;metName];
-0059             else
-0060                 %The metabolite name contained spaces
-0061                 metabolites=[metabolites;candidates(j)];
-0062             end
-0063         end
-0064     end
-0065 end
-0066 
-0067 metabolites=strtrim(metabolites);
-0068 
-0069 %Upper/lower case is treated as different names. This should be checked for
-0070 %later since it's bad modelling practice
-0071 metabolites=unique(metabolites);
-0072 
-0073 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/parseTaskList.html b/doc/core/parseTaskList.html deleted file mode 100644 index 51aa28e2a..000000000 --- a/doc/core/parseTaskList.html +++ /dev/null @@ -1,441 +0,0 @@ - - - - Description of parseTaskList - - - - - - - - - -
Home > core > parseTaskList.m
- - - -

parseTaskList -

- -

PURPOSE ^

-
parseTaskList
- -

SYNOPSIS ^

-
function taskStruct=parseTaskList(inputFile)
- -

DESCRIPTION ^

-
 parseTaskList
-   Parses a task list file.
-
-   inputFile       a task list in either Excel (*.xlsx, with a sheet named
-                   TASKS with all relevant content) or tab-delimited
-                   (*.txt) format. The file may contain the following
-                   column headers (note, all rows starting with a
-                   non-empty cell are removed. The first row after that
-                   is considered the headers):
-                   ID
-                       the only required header. Each task must have a
-                       unique id (string or numeric). Tasks can span multiple
-                       rows, only the first row in each task should have
-                       an id
-                   DESCRIPTION
-                       description of the task
-                   IN
-                       allowed input(s) for the task. Metabolite names
-                       should be on the form
-                       "model.metName[model.comps]". Several inputs
-                       can be delimited by ";". If so, then the same
-                       bounds are used for all inputs. If that is not
-                       wanted, then use several rows for the task
-                   IN LB
-                       lower bound for the uptake of the metabolites in
-                       the row (optional, default 0 which corresponds to a
-                       minimal uptake of 0 units)
-                   IN UB
-                       upper bound for the uptake of the metabolites in
-                       the row (optional, default 1000 which corresponds to a
-                       maximal uptake of 1000 units)
-                   OUT
-                       allowed output(s) for the task (see IN)
-                   OUT LB
-                       lower bound for the production of the metabolites in
-                       the row (optional, default 0 which corresponds to a
-                       minimal production of 0 units)
-                   OUT UB
-                       upper bound for the production of the metabolites in
-                       the row (optional, default 1000 which corresponds to a
-                       maximal production of 1000 units)
-                   EQU
-                       equation to add. The equation should be on the form
-                       "0.4 A + 2 B <=> (or =>) C" and the metabolites
-                       should be on the form
-                       "model.metName[model.comps]" (optional)
-                   EQU LB
-                       lower bound for the equation (optional, default -1000
-                       for reversible and 0 for irreversible)
-                   EQU UB
-                       upper bound for the equation (optional, default 1000)
-                   CHANGED RXN
-                       reaction ID for which to change the bounds for.
-                       Several IDs can be delimited by ";". If so,
-                       then the same bounds are used for all reactions. If
-                       that is not wanted, then use several rows for the task
-                   CHANGED LB
-                       lower bound for the reaction
-                   CHANGED UB
-                       upper bound for the reaction
-                   SHOULD FAIL
-                       true if the correct behavior of the model is to
-                       not have a feasible solution given the constraints
-                       (optional, default false)
-                   PRINT FLUX
-                       true if the function should print the corresponding
-                       flux distribution for a task. Can be useful for
-                       testing (optional, default false)
-
-   taskStruct      array of structures with the following fields
-       id          the id of the task
-       description the description of the task
-       shouldFail  true if the task should fail
-       printFluxes true if the fluxes should be printed
-       comments    string with comments
-       inputs      cell array with input metabolites (in the form metName[comps])
-       LBin        array with lower bounds on inputs (default, 0)
-       UBin        array with upper bounds on inputs (default, 1000)
-       outputs     cell array with output metabolites (in the form metName[comps])
-       LBout       array with lower bounds on outputs (default, 0)
-       UBout       array with upper bounds on outputs (default, 1000)
-       equations   cell array with equations (with mets in the form metName[comps])
-       LBequ       array with lower bounds on equations (default, -1000 for
-                   reversible and 0 for irreversible)
-       UBequ       array with upper bounds on equations (default, 1000)
-       changed     cell array with reactions to change bounds for
-       LBrxn       array with lower bounds on changed reactions
-       UBrxn       array with upper bounds on changed reactions
-
-   This function is used for defining a set of tasks for a model to
-   perform. The tasks are defined by defining constraints on the model,
-   and if the problem is feasible, then the task is considered successful.
-   In general, each row can contain one constraint on uptakes, one
-   constraint on outputs, one new equation, and one change of reaction
-   bounds. If more bounds are needed to define the task, then several rows
-   can be used for each task. To perform the task use checkTasks or
-   fitTasks.
-
-   NOTE: The general metabolites "ALLMETS" and "ALLMETSIN[comps]"
-   can be used as inputs or outputs in the similar manner to normal
-   metabolites. This is a convenient way to, for example, allow excretion of
-   all metabolites to check whether it's the synthesis of some metabolite
-   that is limiting or whether it's the degradation of some byproduct. One
-   important difference is that only the upper bounds are used for these general
-   metabolites. That is, you can only say that uptake or excretion is
-   allowed, not that it is required. This is to avoid conflicts where the
-   constraints for the general metabolites overwrite those of the real
-   ones.
-
- Usage: taskStruct=parseTaskList(inputFile)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function taskStruct=parseTaskList(inputFile)
-0002 % parseTaskList
-0003 %   Parses a task list file.
-0004 %
-0005 %   inputFile       a task list in either Excel (*.xlsx, with a sheet named
-0006 %                   TASKS with all relevant content) or tab-delimited
-0007 %                   (*.txt) format. The file may contain the following
-0008 %                   column headers (note, all rows starting with a
-0009 %                   non-empty cell are removed. The first row after that
-0010 %                   is considered the headers):
-0011 %                   ID
-0012 %                       the only required header. Each task must have a
-0013 %                       unique id (string or numeric). Tasks can span multiple
-0014 %                       rows, only the first row in each task should have
-0015 %                       an id
-0016 %                   DESCRIPTION
-0017 %                       description of the task
-0018 %                   IN
-0019 %                       allowed input(s) for the task. Metabolite names
-0020 %                       should be on the form
-0021 %                       "model.metName[model.comps]". Several inputs
-0022 %                       can be delimited by ";". If so, then the same
-0023 %                       bounds are used for all inputs. If that is not
-0024 %                       wanted, then use several rows for the task
-0025 %                   IN LB
-0026 %                       lower bound for the uptake of the metabolites in
-0027 %                       the row (optional, default 0 which corresponds to a
-0028 %                       minimal uptake of 0 units)
-0029 %                   IN UB
-0030 %                       upper bound for the uptake of the metabolites in
-0031 %                       the row (optional, default 1000 which corresponds to a
-0032 %                       maximal uptake of 1000 units)
-0033 %                   OUT
-0034 %                       allowed output(s) for the task (see IN)
-0035 %                   OUT LB
-0036 %                       lower bound for the production of the metabolites in
-0037 %                       the row (optional, default 0 which corresponds to a
-0038 %                       minimal production of 0 units)
-0039 %                   OUT UB
-0040 %                       upper bound for the production of the metabolites in
-0041 %                       the row (optional, default 1000 which corresponds to a
-0042 %                       maximal production of 1000 units)
-0043 %                   EQU
-0044 %                       equation to add. The equation should be on the form
-0045 %                       "0.4 A + 2 B <=> (or =>) C" and the metabolites
-0046 %                       should be on the form
-0047 %                       "model.metName[model.comps]" (optional)
-0048 %                   EQU LB
-0049 %                       lower bound for the equation (optional, default -1000
-0050 %                       for reversible and 0 for irreversible)
-0051 %                   EQU UB
-0052 %                       upper bound for the equation (optional, default 1000)
-0053 %                   CHANGED RXN
-0054 %                       reaction ID for which to change the bounds for.
-0055 %                       Several IDs can be delimited by ";". If so,
-0056 %                       then the same bounds are used for all reactions. If
-0057 %                       that is not wanted, then use several rows for the task
-0058 %                   CHANGED LB
-0059 %                       lower bound for the reaction
-0060 %                   CHANGED UB
-0061 %                       upper bound for the reaction
-0062 %                   SHOULD FAIL
-0063 %                       true if the correct behavior of the model is to
-0064 %                       not have a feasible solution given the constraints
-0065 %                       (optional, default false)
-0066 %                   PRINT FLUX
-0067 %                       true if the function should print the corresponding
-0068 %                       flux distribution for a task. Can be useful for
-0069 %                       testing (optional, default false)
-0070 %
-0071 %   taskStruct      array of structures with the following fields
-0072 %       id          the id of the task
-0073 %       description the description of the task
-0074 %       shouldFail  true if the task should fail
-0075 %       printFluxes true if the fluxes should be printed
-0076 %       comments    string with comments
-0077 %       inputs      cell array with input metabolites (in the form metName[comps])
-0078 %       LBin        array with lower bounds on inputs (default, 0)
-0079 %       UBin        array with upper bounds on inputs (default, 1000)
-0080 %       outputs     cell array with output metabolites (in the form metName[comps])
-0081 %       LBout       array with lower bounds on outputs (default, 0)
-0082 %       UBout       array with upper bounds on outputs (default, 1000)
-0083 %       equations   cell array with equations (with mets in the form metName[comps])
-0084 %       LBequ       array with lower bounds on equations (default, -1000 for
-0085 %                   reversible and 0 for irreversible)
-0086 %       UBequ       array with upper bounds on equations (default, 1000)
-0087 %       changed     cell array with reactions to change bounds for
-0088 %       LBrxn       array with lower bounds on changed reactions
-0089 %       UBrxn       array with upper bounds on changed reactions
-0090 %
-0091 %   This function is used for defining a set of tasks for a model to
-0092 %   perform. The tasks are defined by defining constraints on the model,
-0093 %   and if the problem is feasible, then the task is considered successful.
-0094 %   In general, each row can contain one constraint on uptakes, one
-0095 %   constraint on outputs, one new equation, and one change of reaction
-0096 %   bounds. If more bounds are needed to define the task, then several rows
-0097 %   can be used for each task. To perform the task use checkTasks or
-0098 %   fitTasks.
-0099 %
-0100 %   NOTE: The general metabolites "ALLMETS" and "ALLMETSIN[comps]"
-0101 %   can be used as inputs or outputs in the similar manner to normal
-0102 %   metabolites. This is a convenient way to, for example, allow excretion of
-0103 %   all metabolites to check whether it's the synthesis of some metabolite
-0104 %   that is limiting or whether it's the degradation of some byproduct. One
-0105 %   important difference is that only the upper bounds are used for these general
-0106 %   metabolites. That is, you can only say that uptake or excretion is
-0107 %   allowed, not that it is required. This is to avoid conflicts where the
-0108 %   constraints for the general metabolites overwrite those of the real
-0109 %   ones.
-0110 %
-0111 % Usage: taskStruct=parseTaskList(inputFile)
-0112 
-0113 if ~isfile(inputFile)
-0114     error('Task list %s cannot be found',string(inputFile));
-0115 end
-0116 
-0117 %Load the tasks file
-0118 convNumeric = false;
-0119 if strcmp(extractAfter(inputFile,strlength(inputFile) - 4), '.txt')
-0120     %load from tab delimited text file
-0121     fid = fopen(inputFile);
-0122     %Need to read numeric columns as strings, this is converted further
-0123     %down. If not, the titles would be lost.
-0124     convNumeric = true;
-0125     C = textscan(fid,'%q%q%q%q%q%q%q%q%q%q%q%q%q%q%q%q%q%q%q%q%*[^\n]', 'Delimiter', '\t');
-0126     fclose(fid);
-0127     raw = [C{:}];%unnest the cell array of cell arrays into a 2-dim cell array
-0128 else
-0129     [raw,flag]=loadSheet(loadWorkbook(inputFile), 'TASKS');
-0130     if flag~=0
-0131         EM=['Could not load sheet "TASKS" from ' inputFile];
-0132         dispEM(EM);
-0133     end
-0134 end
-0135 
-0136 %Remove all lines starting with "#" (or actually any character) and all
-0137 %empty columns
-0138 raw=cleanSheet(raw);
-0139 
-0140 %Captions
-0141 columns={'ID';'DESCRIPTION';'IN';'IN LB';'IN UB';'OUT';'OUT LB';'OUT UB';'EQU';'EQU LB';'EQU UB';'CHANGED RXN';'CHANGED LB';'CHANGED UB';'SHOULD FAIL';'PRINT FLUX';'COMMENTS'};
-0142 %Match the columns
-0143 [I, colI]=ismember(columns,raw(1,:));
-0144 
-0145 %If read from  a text file, the numbers will be strings - fix that
-0146 if convNumeric % in theory, this if should not be needed, the code should do nothing if all are already numeric. But it is kept as a safeguard.
-0147     numericColumns = [0 0 0 1 1 0 1 1 0 1 1 0 1 1 0 0 0] == 1;
-0148     cols = colI(numericColumns);
-0149     numeric = cellfun(@isnumeric,raw(:,cols));
-0150     %trick to avoid messing up the title row:
-0151     numeric(1,:) = 1;
-0152     for colind = 1:numel(cols)
-0153         col = cols(colind);
-0154         raw(~numeric(:,colind),col) = cellfun(@str2num, raw(~numeric(:,colind),col), 'UniformOutput', false);
-0155     end
-0156 end
-0157 
-0158 %Check that the ID field is present
-0159 if I(1)==0
-0160     EM='The TASKS sheet must have a column named ID';
-0161     dispEM(EM);
-0162 end
-0163 
-0164 %make sure numerical fields are converted from strings
-0165 
-0166 %Add default bounds where needed
-0167 for i=[4 5 7 8]
-0168     I=cellfun(@isempty,raw(:,colI(i)));
-0169     if i==5 || i==8
-0170         raw(I,colI(i))={1000};
-0171     else
-0172         raw(I,colI(i))={0};
-0173     end
-0174 end
-0175 
-0176 %Create an empty task structure
-0177 eTask.id='';
-0178 eTask.description='';
-0179 eTask.shouldFail=false;
-0180 eTask.printFluxes=false;
-0181 eTask.comments='';
-0182 eTask.inputs={};
-0183 eTask.LBin=[];
-0184 eTask.UBin=[];
-0185 eTask.outputs={};
-0186 eTask.LBout=[];
-0187 eTask.UBout=[];
-0188 eTask.equations={};
-0189 eTask.LBequ=[];
-0190 eTask.UBequ=[];
-0191 eTask.changed={};
-0192 eTask.LBrxn=[];
-0193 eTask.UBrxn=[];
-0194 
-0195 %Main loop
-0196 taskStruct=[];
-0197 task=eTask;
-0198 if isnumeric(raw{2,colI(1)})
-0199     task.id=num2str(raw{2,colI(1)});
-0200 else
-0201     task.id=raw{2,colI(1)};
-0202 end
-0203 task.description=raw{2,colI(2)};
-0204 if ~isempty(raw{2,colI(15)})
-0205     task.shouldFail=true;
-0206 end
-0207 if ~isempty(raw{2,colI(16)})
-0208     task.printFluxes=true;
-0209 end
-0210 if ~isempty(raw{2,colI(17)})
-0211     task.comments=raw{2,colI(17)};
-0212 end
-0213 
-0214 for i=2:size(raw,1)
-0215     %Set the inputs
-0216     if ischar(raw{i,colI(3)})
-0217         inputs=regexp(raw{i,colI(3)},';','split');
-0218         task.inputs=[task.inputs;inputs(:)];
-0219         task.LBin=[task.LBin;ones(numel(inputs),1)*raw{i,colI(4)}];
-0220         task.UBin=[task.UBin;ones(numel(inputs),1)*raw{i,colI(5)}];
-0221     end
-0222     %Set the outputs
-0223     if ischar(raw{i,colI(6)})
-0224         outputs=regexp(raw{i,colI(6)},';','split');
-0225         task.outputs=[task.outputs;outputs(:)];
-0226         task.LBout=[task.LBout;ones(numel(outputs),1)*raw{i,colI(7)}];
-0227         task.UBout=[task.UBout;ones(numel(outputs),1)*raw{i,colI(8)}];
-0228     end
-0229     %Add new rxns
-0230     if ischar(raw{i,colI(9)})
-0231         task.equations=[task.equations;raw{i,colI(9)}];
-0232         if ~isempty(raw{i,colI(10)})
-0233             task.LBequ=[task.LBequ;raw{i,colI(10)}];
-0234         else
-0235             if any(strfind(raw{i,colI(9)},'<=>'))
-0236                 task.LBequ=[task.LBequ;-1000];
-0237             else
-0238                 task.LBequ=[task.LBequ;0];
-0239             end
-0240         end
-0241         if ~isempty(raw{i,colI(11)})
-0242             task.UBequ=[task.UBequ;raw{i,colI(11)}];
-0243         else
-0244             task.UBequ=[task.UBequ;1000];
-0245         end
-0246     end
-0247     %Add changed bounds
-0248     if ischar(raw{i,colI(12)})
-0249         changed=regexp(raw{i,colI(12)},';','split');
-0250         task.changed=[task.changed;changed(:)];
-0251         task.LBrxn=[task.LBrxn;ones(numel(changed),1)*raw{i,colI(13)}];
-0252         task.UBrxn=[task.UBrxn;ones(numel(changed),1)*raw{i,colI(14)}];
-0253     end
-0254     
-0255     %Check if it should add more constraints
-0256     if i<size(raw,1)
-0257         if isempty(raw{i+1,colI(1)})
-0258             continue;
-0259         end
-0260     end
-0261     
-0262     taskStruct=[taskStruct;task];
-0263     task=eTask;
-0264     if i<size(raw,1)
-0265         if isnumeric(raw{i+1,colI(1)})
-0266             task.id=num2str(raw{i+1,colI(1)});
-0267         else
-0268             task.id=raw{i+1,colI(1)};
-0269         end
-0270         task.description=raw{i+1,colI(2)};
-0271         if ~isempty(raw{i+1,colI(15)})
-0272             task.shouldFail=true;
-0273         end
-0274         if ~isempty(raw{i+1,colI(16)})
-0275             task.printFluxes=true;
-0276         end
-0277         if ~isempty(raw{i+1,colI(17)})
-0278             task.comments=raw{i+1,colI(17)};
-0279         end
-0280     end
-0281 end
-0282 
-0283 %Should add more checks, such as unique IDs and missing headers
-0284 
-0285 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/permuteModel.html b/doc/core/permuteModel.html deleted file mode 100644 index f86f25f53..000000000 --- a/doc/core/permuteModel.html +++ /dev/null @@ -1,228 +0,0 @@ - - - - Description of permuteModel - - - - - - - - - -
Home > core > permuteModel.m
- - - -

permuteModel -

- -

PURPOSE ^

-
permuteModel
- -

SYNOPSIS ^

-
function newModel=permuteModel(model, indexes, type)
- -

DESCRIPTION ^

-
 permuteModel
-   Changes the order of the reactions or metabolites in a model
-
-   Input:
-   model     a model structure
-   indexes   a vector with the same length as the number of items in the
-             model, which gives the new order of items
-   type      'rxns' for reactions, 'mets' for metabolites, 'genes' for
-             genes, 'comps' for compartments
-
-     Output:
-   newModel  an updated model structure
-
-     Usage: newModel=permuteModel(model, indexes, type)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function newModel=permuteModel(model, indexes, type)
-0002 % permuteModel
-0003 %   Changes the order of the reactions or metabolites in a model
-0004 %
-0005 %   Input:
-0006 %   model     a model structure
-0007 %   indexes   a vector with the same length as the number of items in the
-0008 %             model, which gives the new order of items
-0009 %   type      'rxns' for reactions, 'mets' for metabolites, 'genes' for
-0010 %             genes, 'comps' for compartments
-0011 %
-0012 %     Output:
-0013 %   newModel  an updated model structure
-0014 %
-0015 %     Usage: newModel=permuteModel(model, indexes, type)
-0016 
-0017 newModel=model;
-0018 type=char(type);
-0019 
-0020 switch type
-0021     case 'rxns'
-0022         if isfield(newModel,'rxns')
-0023             newModel.rxns=newModel.rxns(indexes);
-0024         end
-0025         if isfield(newModel,'lb')
-0026             newModel.lb=newModel.lb(indexes);
-0027         end
-0028         if isfield(newModel,'ub')
-0029             newModel.ub=newModel.ub(indexes);
-0030         end
-0031         if isfield(newModel,'rev')
-0032             newModel.rev=newModel.rev(indexes);
-0033         end
-0034         if isfield(newModel,'c')
-0035             newModel.c=newModel.c(indexes);
-0036         end
-0037         if isfield(newModel,'S')
-0038             newModel.S=newModel.S(:,indexes);
-0039         end
-0040         if isfield(newModel,'rxnNames')
-0041             newModel.rxnNames=newModel.rxnNames(indexes);
-0042         end
-0043         if isfield(newModel,'rxnGeneMat')
-0044             newModel.rxnGeneMat=newModel.rxnGeneMat(indexes,:);
-0045         end
-0046         if isfield(newModel,'grRules')
-0047             newModel.grRules=newModel.grRules(indexes);
-0048         end
-0049         if isfield(newModel,'subSystems')
-0050             newModel.subSystems=newModel.subSystems(indexes);
-0051         end
-0052         if isfield(newModel,'eccodes')
-0053             newModel.eccodes=newModel.eccodes(indexes);
-0054         end
-0055         if isfield(newModel,'equations')
-0056             newModel.equations=newModel.equations(indexes);
-0057         end
-0058         if isfield(newModel,'rxnMiriams')
-0059             newModel.rxnMiriams=newModel.rxnMiriams(indexes);
-0060         end
-0061         if isfield(newModel,'rxnComps')
-0062             newModel.rxnComps=newModel.rxnComps(indexes);
-0063         end
-0064         if isfield(newModel,'rxnFrom')
-0065             newModel.rxnFrom=newModel.rxnFrom(indexes);
-0066         end
-0067         if isfield(newModel,'rxnScores')
-0068             newModel.rxnScores=newModel.rxnScores(indexes);
-0069         end
-0070         if isfield(newModel,'rxnNotes')
-0071             newModel.rxnNotes=newModel.rxnNotes(indexes);
-0072         end
-0073         if isfield(newModel,'rxnReferences')
-0074             newModel.rxnReferences=newModel.rxnReferences(indexes);
-0075         end
-0076         if isfield(newModel,'rxnConfidenceScores')
-0077             newModel.rxnConfidenceScores=newModel.rxnConfidenceScores(indexes);
-0078         end
-0079         if isfield(newModel,'rxnDeltaG')
-0080             newModel.rxnDeltaG=newModel.rxnDeltaG(indexes);
-0081         end
-0082     case 'mets'
-0083         if isfield(newModel,'mets')
-0084             newModel.mets=newModel.mets(indexes);
-0085         end
-0086         if isfield(newModel,'metNames')
-0087             newModel.metNames=newModel.metNames(indexes);
-0088         end
-0089         if isfield(newModel,'b')
-0090             newModel.b=newModel.b(indexes,:);
-0091         end
-0092         if isfield(newModel,'metComps')
-0093             newModel.metComps=newModel.metComps(indexes);
-0094         end
-0095         if isfield(newModel,'S')
-0096             newModel.S=newModel.S(indexes,:);
-0097         end
-0098         if isfield(newModel,'unconstrained')
-0099             newModel.unconstrained=newModel.unconstrained(indexes);
-0100         end
-0101         if isfield(newModel,'metMiriams')
-0102             newModel.metMiriams=newModel.metMiriams(indexes,:);
-0103         end
-0104         if isfield(newModel,'inchis')
-0105             newModel.inchis=newModel.inchis(indexes);
-0106         end
-0107         if isfield(newModel,'metSmiles')
-0108             newModel.metSmiles=newModel.metSmiles(indexes);
-0109         end
-0110         if isfield(newModel,'metFormulas')
-0111             newModel.metFormulas=newModel.metFormulas(indexes);
-0112         end
-0113         if isfield(newModel,'metFrom')
-0114             newModel.metFrom=newModel.metFrom(indexes);
-0115         end
-0116         if isfield(newModel,'metCharges')
-0117             newModel.metCharges=newModel.metCharges(indexes);
-0118         end
-0119         if isfield(newModel,'metDeltaG')
-0120             newModel.metDeltaG=newModel.metDeltaG(indexes);
-0121         end
-0122     case 'genes'
-0123         if isfield(newModel,'genes')
-0124             newModel.genes=newModel.genes(indexes);
-0125         end
-0126         if isfield(newModel,'geneComps')
-0127             newModel.geneComps=newModel.geneComps(indexes);
-0128         end
-0129         if isfield(newModel,'geneMiriams')
-0130             newModel.geneMiriams=newModel.geneMiriams(indexes);
-0131         end
-0132         if isfield(newModel,'geneShortNames')
-0133             newModel.geneShortNames=newModel.geneShortNames(indexes);
-0134         end
-0135         if isfield(newModel,'proteins')
-0136             newModel.proteins=newModel.proteins(indexes);
-0137         end
-0138         if isfield(newModel,'rxnGeneMat')
-0139             newModel.rxnGeneMat=newModel.rxnGeneMat(:,indexes);
-0140         end
-0141     case 'comps'
-0142         if isfield(newModel,'comps')
-0143             newModel.comps=newModel.comps(indexes);
-0144         end
-0145         if isfield(newModel,'compNames')
-0146             newModel.compNames=newModel.compNames(indexes);
-0147         end
-0148         if isfield(newModel,'compOutside')
-0149             newModel.compOutside=newModel.compOutside(indexes);
-0150         end
-0151         if isfield(newModel,'compMiriams')
-0152             newModel.compMiriams=newModel.compMiriams(indexes);
-0153         end
-0154         [~,J]=sort(indexes); % The *index* of compartment is used in next fields
-0155         if isfield(newModel,'metComps')
-0156             [toreplace, bywhat] = ismember(newModel.metComps,1:length(J));
-0157             newModel.metComps(toreplace) = J(bywhat(toreplace));
-0158         end
-0159         if isfield(model,'rxnComps')
-0160             [toreplace, bywhat] = ismember(model.rxnComps,1:length(J));
-0161             model.rxnComps(toreplace) = J(bywhat(toreplace));
-0162         end
-0163         if isfield(model,'geneComps')
-0164             [toreplace, bywhat] = ismember(model.geneComps,1:length(J));
-0165             model.geneComps(toreplace) = J(bywhat(toreplace));
-0166         end
-0167 end
-0168 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/predictLocalization.html b/doc/core/predictLocalization.html deleted file mode 100644 index 8b7b0ddfd..000000000 --- a/doc/core/predictLocalization.html +++ /dev/null @@ -1,1247 +0,0 @@ - - - - Description of predictLocalization - - - - - - - - - -
Home > core > predictLocalization.m
- - - -

predictLocalization -

- -

PURPOSE ^

-
predictLocalization
- -

SYNOPSIS ^

-
function [outModel, geneLocalization, transportStruct, scores,removedRxns] = predictLocalization(model, GSS,defaultCompartment, transportCost, maxTime, plotResults)
- -

DESCRIPTION ^

-
 predictLocalization
-    Tries to assign reactions to compartments in a manner that is in
-    agreement with localization predictors while at the same time
-    maintaining connectivity.
-
-   Input:
-    model                   a model structure. If the model contains
-                           several compartments they will be merged
-    GSS                     a gene scoring structure as from parseScores
-    defaultCompartment      transport reactions are expressed as diffusion
-                           between the defaultCompartment and the others.
-                           This is usually the cytosol. The default
-                           compartment must have a match in GSS
-    transportCost           the cost for including a transport reaction. If
-                           this a scalar then the same cost is used for
-                           all metabolites. It can also be a vector of
-                           costs with the same dimension as model.mets.
-                           Note that negative costs will result in that
-                           transport of the metabolite is encouraged (optional,
-                           default 0.5)
-    maxTime                 maximum optimization time in minutes (optional,
-                           default 15)
-    plotResults             true if the results should be plotted during the
-                           optimization (optional, default false)
-
-   Output:
-    outModel                the resulting model structure
-    geneLocalization        structure with the genes and their resulting
-                           localization
-    transportStruct         structure with the transport reactions that had
-                           to be inferred and between which compartments
-    scores                  structure that contains the total score history
-                           together with the score based on gene
-                           localization and the score based on included
-                           transport reactions
-    removedRxns             cell array with the reaction ids that had to be
-                           removed in order to have a connected input
-                           model
-
-    This function requires that the starting network is connected when it
-    is in one compartment. Reactions that are unconnected are removed and
-    saved in removedRxns. Try running fillGaps to have a more connected
-    input model if there are many such reactions. The input model should
-    also not include any exchange, demand or sink reactions, otherwise this
-    function would not provide any results.
-
-    In the final model all metabolites are produced in at least one
-    reaction. This does not guarantee a fully functional model since there
-    can be internal loops. Transport reactions are only included as passive
-    diffusion (A <=> B).
-
-    The score of a model is the sum of scores for all genes in their
-    assigned compartment minus the cost of all transport reactions that had
-    to be included. A gene can only be assigned to one compartment. This is
-    a simplification to keep the problem size down. The problem is solved
-    using simulated annealing.
-
- Usage: [outModel, geneLocalization, transportStruct, scores,...
-       removedRxns] = predictLocalization(model, GSS,...
-       defaultCompartment, transportCost, maxTime, plotResults)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 function [outModel, geneLocalization, transportStruct, scores,...
-0002     removedRxns] = predictLocalization(model, GSS,...
-0003     defaultCompartment, transportCost, maxTime, plotResults)
-0004 % predictLocalization
-0005 %    Tries to assign reactions to compartments in a manner that is in
-0006 %    agreement with localization predictors while at the same time
-0007 %    maintaining connectivity.
-0008 %
-0009 %   Input:
-0010 %    model                   a model structure. If the model contains
-0011 %                           several compartments they will be merged
-0012 %    GSS                     a gene scoring structure as from parseScores
-0013 %    defaultCompartment      transport reactions are expressed as diffusion
-0014 %                           between the defaultCompartment and the others.
-0015 %                           This is usually the cytosol. The default
-0016 %                           compartment must have a match in GSS
-0017 %    transportCost           the cost for including a transport reaction. If
-0018 %                           this a scalar then the same cost is used for
-0019 %                           all metabolites. It can also be a vector of
-0020 %                           costs with the same dimension as model.mets.
-0021 %                           Note that negative costs will result in that
-0022 %                           transport of the metabolite is encouraged (optional,
-0023 %                           default 0.5)
-0024 %    maxTime                 maximum optimization time in minutes (optional,
-0025 %                           default 15)
-0026 %    plotResults             true if the results should be plotted during the
-0027 %                           optimization (optional, default false)
-0028 %
-0029 %   Output:
-0030 %    outModel                the resulting model structure
-0031 %    geneLocalization        structure with the genes and their resulting
-0032 %                           localization
-0033 %    transportStruct         structure with the transport reactions that had
-0034 %                           to be inferred and between which compartments
-0035 %    scores                  structure that contains the total score history
-0036 %                           together with the score based on gene
-0037 %                           localization and the score based on included
-0038 %                           transport reactions
-0039 %    removedRxns             cell array with the reaction ids that had to be
-0040 %                           removed in order to have a connected input
-0041 %                           model
-0042 %
-0043 %    This function requires that the starting network is connected when it
-0044 %    is in one compartment. Reactions that are unconnected are removed and
-0045 %    saved in removedRxns. Try running fillGaps to have a more connected
-0046 %    input model if there are many such reactions. The input model should
-0047 %    also not include any exchange, demand or sink reactions, otherwise this
-0048 %    function would not provide any results.
-0049 %
-0050 %    In the final model all metabolites are produced in at least one
-0051 %    reaction. This does not guarantee a fully functional model since there
-0052 %    can be internal loops. Transport reactions are only included as passive
-0053 %    diffusion (A <=> B).
-0054 %
-0055 %    The score of a model is the sum of scores for all genes in their
-0056 %    assigned compartment minus the cost of all transport reactions that had
-0057 %    to be included. A gene can only be assigned to one compartment. This is
-0058 %    a simplification to keep the problem size down. The problem is solved
-0059 %    using simulated annealing.
-0060 %
-0061 % Usage: [outModel, geneLocalization, transportStruct, scores,...
-0062 %       removedRxns] = predictLocalization(model, GSS,...
-0063 %       defaultCompartment, transportCost, maxTime, plotResults)
-0064 
-0065 if nargin<4
-0066     transportCost=ones(numel(model.mets),1)*0.5;
-0067 end
-0068 if numel(transportCost)==1
-0069     transportCost=ones(numel(model.mets),1)*transportCost;
-0070 end
-0071 transportCost=transportCost(:);
-0072 
-0073 if numel(transportCost)~=numel(model.mets)
-0074     EM='The vector of transport costs must have the same dimension as model.mets';
-0075     dispEM(EM,true);
-0076 end
-0077 if nargin<5
-0078     maxTime=15;
-0079 end
-0080 if nargin<6
-0081     plotResults=false;
-0082 end
-0083 
-0084 if isfield(model,'rxnComps')
-0085     model=rmfield(model,'rxnComps');
-0086     EM='The model structure contains information about reaction compartmentalization. This is not supported by this function. The rxnComps field has been deleted';
-0087     dispEM(EM,false);
-0088 end
-0089 if isfield(model,'geneComps')
-0090     model=rmfield(model,'geneComps');
-0091     EM='The model structure contains information about gene compartmentalization. This is not supported by this function. The geneComps field has been deleted';
-0092     dispEM(EM,false);
-0093 end
-0094 
-0095 defaultCompartment=char(defaultCompartment);
-0096 I=ismember(defaultCompartment,GSS.compartments);
-0097 if I==false
-0098     EM='defaultCompartment not found in GSS';
-0099     dispEM(EM);
-0100 end
-0101 
-0102 if numel(model.comps)>1
-0103     EM='The model has several compartments. All compartments will be merged';
-0104     dispEM(EM,false);
-0105     model=mergeCompartments(model,true,true);
-0106 end
-0107 
-0108 noGenes = ismember(model.genes,GSS.genes);
-0109 if ~all(noGenes)
-0110     EM=['For ' num2str(numel(find(~noGenes))) ' of ' num2str(numel(model.genes)) ' model genes no data was found in GSS'];
-0111     dispEM(EM,false);
-0112 end
-0113 
-0114 %***Begin formating the data structures
-0115 
-0116 %Expand the model so that iso-enzymes have different reactions
-0117 model=expandModel(model);
-0118 
-0119 %Identify reactions that have to be deleted because the involved mets are
-0120 %never produced. This is done in an iterative manner
-0121 removedRxns={};
-0122 %This is to keep track of which metabolites are removed in this step. It is
-0123 %needed to adjust the transport costs
-0124 originalModelMets=model.mets;
-0125 while 1
-0126     irrevModel=convertToIrrev(model);
-0127     
-0128     I=sum(irrevModel.S>0,2);
-0129     
-0130     %Pretend that the unconstrained metabolites are made enough
-0131     if isfield(irrevModel,'unconstrained')
-0132         I(irrevModel.unconstrained~=0)=2;
-0133     end
-0134     metsToDelete=false(numel(model.mets),1);
-0135     
-0136     %This is not very neat but iterate through each metabolite and check
-0137     %whether it can be produced (without using only one isolated reversible
-0138     %reaction)
-0139     for i=1:numel(irrevModel.mets)
-0140         %If something can be made in two reactions then everything is fine.
-0141         %If it can be made in one reaction it is fine unless it is through
-0142         %an isolated reversible reaction (which can act as a mini loop)
-0143         if I(i)<2
-0144             if I(i)==1
-0145                 %Find the reaction where this metabolite is produced
-0146                 [~, J]=find(irrevModel.S(i,:)>0);
-0147                 
-0148                 %Check the metabolites that are consumed in this reaction.
-0149                 %The problem is if any of them is only produced in the
-0150                 %opposite reversible reaction
-0151                 K=irrevModel.S(:,J)<0;
-0152                 check=find(K & I<=1);
-0153                 
-0154                 for j=1:numel(check)
-0155                     %Find the reactions where it participates
-0156                     [~, L]=find(irrevModel.S(check(j),:)>0);
-0157                     
-0158                     if ~isempty(L)
-0159                         rxn=irrevModel.rxns(J);
-0160                         rxnRev=irrevModel.rxns(L);
-0161                         if strcmp(strrep(rxn,'_REV',''),strrep(rxnRev,'_REV',''))
-0162                             metsToDelete(i)=true;
-0163                         end
-0164                     else
-0165                         %If the metabolite was never produced then do
-0166                         %nothing and deal with it when the loop gets there
-0167                         continue;
-0168                     end
-0169                 end
-0170             else
-0171                 %Not made anywhere
-0172                 metsToDelete(i)=true;
-0173             end
-0174         end
-0175     end
-0176     
-0177     if any(metsToDelete)
-0178         %Delete any reactions involving any of the metsToDelete
-0179         [~, I]=find(model.S(metsToDelete,:));
-0180         removedRxns=[removedRxns;model.rxns(I)];
-0181         model=removeReactions(model,I,true,true);
-0182     else
-0183         %All bad reactions deleted
-0184         break;
-0185     end
-0186 end
-0187 
-0188 %Adjust the transport costs
-0189 transportCost=transportCost(ismember(originalModelMets,model.mets));
-0190 
-0191 %Assign fake genes to reactions without genes. This is just to make things
-0192 %easier later on
-0193 I=find(sum(model.rxnGeneMat,2)==0);
-0194 for i=1:numel(I)
-0195     model.genes=[model.genes;['&&FAKE&&' num2str(i)]];
-0196     if isfield(model,'geneShortNames')
-0197         model.geneShortNames=[model.geneShortNames;{''}];
-0198     end
-0199     if isfield(model,'geneMiriams')
-0200         model.geneMiriams=[model.geneMiriams;{[]}];
-0201     end
-0202     if isfield(model,'proteins')
-0203         model.proteins=[model.proteins;{[]}];
-0204     end
-0205     if isfield(model,'geneFrom')
-0206         model.geneFrom=[model.geneFrom;{{'FAKE'}}];
-0207     end
-0208     model.rxnGeneMat(I(i),numel(model.genes))=1;
-0209     model.grRules{I(i)}='';
-0210 end
-0211 
-0212 %Update the GSS. All genes, fake or real, for which there is no evidence
-0213 %gets a score 0.5 in all compartments. Also just to make it easier further
-0214 %on
-0215 I=setdiff(model.genes,GSS.genes);
-0216 GSS.genes=[GSS.genes;I];
-0217 GSS.scores=[GSS.scores;ones(numel(I),numel(GSS.compartments))*0.5];
-0218 
-0219 %Gene complexes should be moved together in order to be biologically
-0220 %relevant. The average score for the genes is used for each compartment.
-0221 %This is done by changing the model so that gene complexes are used as a
-0222 %single gene name and then a score is calculated for that "gene".
-0223 
-0224 %Only "and"-relationships exist after expandModel
-0225 genes=unique(model.grRules);
-0226 nGenes=strrep(genes,'(','');
-0227 nGenes=strrep(nGenes,')','');
-0228 %nGenes=strrep(nGenes,' and ','_and_');
-0229 complexes=setdiff(nGenes,model.genes);
-0230 if ~isempty(complexes)
-0231     if isempty(complexes{1}) %Empty grRules also come up here
-0232         complexes(1)=[];
-0233     end
-0234 end
-0235 cScores=zeros(numel(complexes),numel(GSS.compartments));
-0236 for i=1:numel(complexes)
-0237     genesInComplex=regexp(complexes{i},' and ','split');
-0238     
-0239     %Find these genes in GSS
-0240     [I, J]=ismember(genesInComplex,GSS.genes);
-0241     
-0242     if any(I)
-0243         %Get the average of the genes that were found
-0244         mScores=mean(GSS.scores(J(I),:));
-0245         
-0246         %And add 0.5 for the genes that were not found in order to be
-0247         %consistent with non-complexes
-0248         mScores=(mScores.*sum(I)+(numel(genesInComplex)-sum(I))*0.5)/numel(genesInComplex);
-0249     else
-0250         EM=['Could not parse grRule "' complexes{i} '". Assigning score 0.0 in all compartments'];
-0251         dispEM(EM,false);
-0252         mScores=ones(1,numel(genesInComplex))*0.5;
-0253     end
-0254     cScores(i,:)=mScores;
-0255     
-0256     %Add this complex as a new gene
-0257     model.genes=[model.genes;complexes{i}];
-0258     if isfield(model,'geneMiriams')
-0259         model.geneMiriams=[model.geneMiriams;{[]}];
-0260     end
-0261     if isfield(model,'geneShortNames')
-0262         model.geneShortNames=[model.geneShortNames;{''}];
-0263     end
-0264     if isfield(model,'proteins')
-0265         model.proteins=[model.proteins;{''}];
-0266     end
-0267     if isfield(model,'geneFrom')
-0268         model.geneFrom=[model.geneFrom;{'COMPLEX'}];
-0269     end
-0270     %Find the reactions which had the original complex and change them to
-0271     %use the new "gene"
-0272     I=ismember(model.grRules,['(' complexes{i} ')']);
-0273     
-0274     %Should check more carefully if there can be an error here
-0275     if ~isempty(I)
-0276         model.rxnGeneMat(I,:)=0; %Ok since the split on "or" was applied
-0277         model.rxnGeneMat(I,numel(model.genes))=1;
-0278     end
-0279 end
-0280 
-0281 %Add the new "genes"
-0282 GSS.genes=[GSS.genes;complexes];
-0283 GSS.scores=[GSS.scores;cScores];
-0284 
-0285 %After merging the complexes it could happen that there are genes that are
-0286 %no longer in use. Delete such genes
-0287 model=removeReactions(model,{},false,true);
-0288 
-0289 %Exchange reactions, defined as involving an unconstrained metabolite, are
-0290 %special in that they have to stay in the defaultCompartment. This means
-0291 %that uptake/excretion of metabolites is always via the default
-0292 %compartment. This is a small simplification, but should be valid in most
-0293 %cases
-0294 [~, I]=getExchangeRxns(model);
-0295 
-0296 %It will be easier later on if the same place. Put them in the beginning
-0297 J=1:numel(model.rxns);
-0298 J(I)=[];
-0299 model=permuteModel(model,[I;J'],'rxns');
-0300 
-0301 %Number of exchange reactions
-0302 nER=numel(I);
-0303 
-0304 %Also put the exchange metabolites in the beginning
-0305 if isfield(model,'unconstrained')
-0306     I=find(model.unconstrained);
-0307     J=1:numel(model.mets);
-0308     J(I)=[];
-0309     model=permuteModel(model,[I;J'],'mets');
-0310     %Also reorder the transport costs
-0311     transportCost=transportCost([I;J']);
-0312     %Number of exchange metabolites
-0313     nEM=numel(I);
-0314 else
-0315     nEM=0;
-0316 end
-0317 
-0318 %There is no point of having genes for exchange reactions, so delete them.
-0319 %Also to make computations easier
-0320 model.rxnGeneMat(1:nER,:)=0;
-0321 model.grRules(1:nER)={''};
-0322 
-0323 %Remove unused genes
-0324 model=removeReactions(model,{},false,true);
-0325 
-0326 %Remove genes with no match to the model and reorder so that the genes are
-0327 %in the same order as model.genes. Since the fake genes are already added
-0328 %so that all genes in model exist in GSS it is fine to do like this
-0329 [~, J]=ismember(model.genes,GSS.genes);
-0330 GSS.genes=model.genes;
-0331 GSS.scores=GSS.scores(J,:);
-0332 
-0333 %Reorder the GSS so that the first index corresponds to the default
-0334 %compartment
-0335 [~, J]=ismember(defaultCompartment,GSS.compartments);
-0336 reorder=1:numel(GSS.compartments);
-0337 reorder(J)=[];
-0338 reorder=[J reorder];
-0339 GSS.scores=GSS.scores(:,reorder);
-0340 GSS.compartments=GSS.compartments(reorder);
-0341 
-0342 %Since it is only checked whether the metabolites can be synthesized, there
-0343 %is no need to care about the stoichiometry. Change to -1/1 to simplify
-0344 %later. Keep the S matrix for later though
-0345 oldS=model.S;
-0346 model.S(model.S>0)=1;
-0347 model.S(model.S<0)=-1;
-0348 
-0349 %Here is a bit of a trick. To avoid the recurring calculation which
-0350 %reactions are reversible, the reversible reactions have the coefficients
-0351 %-10/10 instead of -1/1
-0352 model.S(:,model.rev==1)=model.S(:,model.rev==1).*10;
-0353 
-0354 %***Begin problem formulation
-0355 
-0356 %Some numbers that are good to have
-0357 nRxns=numel(model.rxns)-nER; %Excluding exchange rxns
-0358 nMets=numel(model.mets)-nEM; %Excluding exchange mets
-0359 nGenes=numel(model.genes);
-0360 nComps=numel(GSS.compartments);
-0361 
-0362 %Create a big stoichiometric matrix that will be the current model. In
-0363 %order to have faster simulations the maximal model size is declared and
-0364 %reactions are then moved within it.
-0365 
-0366 %First the original model (with the first nE being exchange rxns), then
-0367 %reserve space for number of rxns minus exchange rxns for each non-default
-0368 %compartment, then transport reactions for all non-exchange mets between
-0369 %the default compartment and all others.
-0370 %NOTE: Kept eye()*0 since eye() can be used to include all transport from
-0371 %the beginning
-0372 s=repmat(eye(nMets)*0,1,nComps-1);
-0373 s=[zeros(numel(model.mets)-nMets,size(s,2));s];
-0374 S=[model.S sparse(numel(model.mets),nRxns*(nComps-1)) s];
-0375 s=[sparse(nMets*(nComps-1),numel(model.rxns)+nRxns*(nComps-1)) eye(nMets*(nComps-1))*0];
-0376 S=[S;s];
-0377 
-0378 %Also replicate the transport costs
-0379 transportCost=[transportCost(1:nEM);repmat(transportCost(nEM+1:end),nComps,1)];
-0380 
-0381 %Create a binary matrix that says where the genes are in the current
-0382 %solution
-0383 g2c=false(nGenes,nComps);
-0384 %All genes start in the default compartment
-0385 g2c(:,1)=true;
-0386 
-0387 %Start of main optimization loop
-0388 tic;
-0389 bestScore=-inf;
-0390 bestS=[];
-0391 bestg2c=[];
-0392 
-0393 %Temp for testing
-0394 plotScore=[];
-0395 nTrans=[];
-0396 totScore=[];
-0397 minScore=sum(min(GSS.scores,[],2));
-0398 maxScore=sum(max(GSS.scores,[],2));
-0399 
-0400 while toc<maxTime*60
-0401     %Pick a random gene, weighted by it is current score minus the best
-0402     %score for that gene (often 1.0, but can be 0.5 for no genes or average
-0403     %for complexes). Genes with bad fits are more likely to be moved. This
-0404     %formulation never moves a gene from its best compartment. Therefore a
-0405     %small uniform weight is added
-0406     [I, J]=find(g2c);
-0407     geneToMove=randsample(nGenes,1,true,max(GSS.scores(I,:),[],2)-GSS.scores(sub2ind(size(g2c),I,J))+0.1);
-0408     
-0409     %Sample among possible compartments to move to. Add a larger weight to
-0410     %even out the odds a little. Also a way of getting rid of loops where
-0411     %the same set of genes are moved back and forth several times
-0412     toComp=randsample(nComps,1,true,GSS.scores(geneToMove,:)+0.2);
-0413     
-0414     %Check that it moves to a new compartment
-0415     if toComp==find(g2c(geneToMove,:))
-0416         continue;
-0417     end
-0418     
-0419     %Moves the gene
-0420     [newS, newg2c]=moveGene(S,model,g2c,geneToMove,toComp,nRxns,nMets);
-0421     
-0422     %Tries to connect the network. If this was not possible in 10
-0423     %iterations, then abort. If more than 20 modifications were needed then
-0424     %it is unlikely that it will be a lower score
-0425     wasConnected=false;
-0426     for j=1:10
-0427         %Find the metabolites that are now unconnected
-0428         unconnected=findUnconnected(newS,nEM);
-0429         
-0430         %Continue if there are still unconnected
-0431         if any(unconnected)
-0432             %For each gene find out how many of these could be connected if
-0433             %the gene was moved and how many would be disconnected by
-0434             %moving that gene
-0435             [geneIndex, moveTo, deltaConnected, deltaScore]=selectGenes(newS,nEM,nMets,nER,nRxns,model,unconnected,g2c,GSS);
-0436             
-0437             %Score which gene would be the best to move. The highest
-0438             %deltaScore is 1.0. It should be possible to move a gene from
-0439             %worst to best compartment even if it disconnects, say, 1.5
-0440             %more metabolites
-0441             [score, I]=max(1.5*deltaScore+deltaConnected);
-0442             
-0443             %Check if it has to add a transport or if there is a gene that
-0444             %could be moved order to have a more connected network
-0445             hasToAddTransport=true;
-0446             if ~isempty(deltaConnected)
-0447                 if score>0
-0448                     hasToAddTransport=false;
-0449                 end
-0450             end
-0451             
-0452             %If it is possible to move any gene in order to have a more
-0453             %connected network, then move the best one
-0454             if hasToAddTransport==false
-0455                 [newS, newg2c]=moveGene(newS,model,g2c,geneIndex(I),moveTo(I),nRxns,nMets);
-0456             else
-0457                 %Choose a random unconnected metabolite that should be
-0458                 %connected
-0459                 transMet=unconnected(randsample(numel(unconnected),1));
-0460                 
-0461                 %First get where the metabolite is now
-0462                 comps=ceil((transMet-nEM)/((size(S,1)-nEM)/nComps));
-0463                 
-0464                 %Find the corresponding metabolite index if it were in the
-0465                 %default compartment
-0466                 dcIndex=transMet-(comps-1)*nMets;
-0467                 
-0468                 %Then get the indexes of that metabolite in all
-0469                 %compartments
-0470                 allIndexes=dcIndex;
-0471                 for k=1:nComps-1
-0472                     allIndexes=[allIndexes;dcIndex+nMets*k];
-0473                 end
-0474                 
-0475                 %It could be that some of these are not used in any
-0476                 %reaction. Get only the ones which are
-0477                 I=sum(newS(allIndexes,:)~=0,2)>0;
-0478                 
-0479                 %Then get the ones that are used but not in unconnected.
-0480                 %These are metabolites that could potentially be
-0481                 %transported to connect transMet
-0482                 connectedUsed=setdiff(allIndexes(I),unconnected);
-0483                 
-0484                 %This may be an error but leave it for now. It seems to
-0485                 %happen if nothing can be connected in one step
-0486                 if isempty(connectedUsed)
-0487                     break;
-0488                 end
-0489                 
-0490                 %If transMet is in the default compartment then everything
-0491                 %is fine, just connect it to a random one
-0492                 if transMet==dcIndex
-0493                     newS=addTransport(newS,nRxns,nER,nMets,nEM,nComps,transMet,connectedUsed(randsample(numel(connectedUsed),1)));
-0494                 else
-0495                     %If one of the connectedUsed is in the default
-0496                     %compartment then connect to that one
-0497                     I=connectedUsed(connectedUsed<(nMets+nEM));
-0498                     if any(I)
-0499                         newS=addTransport(newS,nRxns,nER,nMets,nEM,nComps,transMet,I(randsample(numel(I),1)));
-0500                     else
-0501                         %This is if the only way to connect it is by adding
-0502                         %two transport reactions, going via the default
-0503                         %compartment
-0504                         break;
-0505                     end
-0506                 end
-0507             end
-0508         else
-0509             wasConnected=true;
-0510             break;
-0511         end
-0512     end
-0513     
-0514     %If the network was connected in a new way, it is possible that some
-0515     %transport reactions are no longer needed. They should be removed
-0516     if wasConnected==true
-0517         %These are the metabolites that are being transported
-0518         activeTransport=find(sum(newS(:,nER+nRxns*nComps+1:end),2));
-0519         
-0520         %Get the metabolites that are unconnected if transport was not used
-0521         unconnected=findUnconnected(newS(:,1:nER+nRxns*nComps),nEM);
-0522         
-0523         %Find the transport reactions that are not needed and delete them
-0524         I=setdiff(activeTransport,unconnected);
-0525         
-0526         %Since both metabolites in a transport rxns must be connected for
-0527         %the reaction to be deleted, the sum over the colums should be 4
-0528         newS(:,find(sum(newS(I,nER+nRxns*nComps+1:end))==4)+nER+nRxns*nComps)=0;
-0529         
-0530         %Score the solution and determine whether to keep it as a new
-0531         %solution
-0532         [score, geneScore, trCost]=scoreModel(newS,newg2c,GSS,transportCost);
-0533         
-0534         %If it was the best solution so far, keep it
-0535         if score>bestScore
-0536             bestScore=score;
-0537             bestS=newS;
-0538             bestg2c=newg2c;
-0539         end
-0540         
-0541         %This should not be steepest descent later
-0542         if score>=bestScore% || exp((score-bestScore)*7)>rand()
-0543             plotScore=[plotScore;geneScore];
-0544             nTrans=[nTrans;trCost];
-0545             totScore=[totScore;score];
-0546             S=newS;
-0547             g2c=newg2c;
-0548             
-0549             if plotResults==true
-0550                 subplot(3,2,1);
-0551                 spy(S);
-0552                 subplot(3,2,2);
-0553                 plot(plotScore,'r');
-0554                 xlabel('Gene score');
-0555                 subplot(3,2,3);
-0556                 plot((plotScore-minScore)/(maxScore-minScore),'r');
-0557                 xlabel('Gene score relative to predictions');
-0558                 subplot(3,2,4);
-0559                 plot(nTrans,'g');
-0560                 xlabel('Transport cost');
-0561                 subplot(3,2,5);
-0562                 plot(totScore,'b');
-0563                 xlabel('Total score');
-0564                 subplot(3,2,6);
-0565                 pause(0.2);
-0566             end
-0567         end
-0568     end
-0569 end
-0570 scores.totScore=score;
-0571 scores.geneScore=geneScore;
-0572 scores.transCost=trCost;
-0573 
-0574 %Find which metabolites are transported and to where
-0575 [I, J]=find(bestS(nEM+1:nEM+nMets,end-nMets*(nComps-1)+1:end));
-0576 J=ceil(J/nMets+1);
-0577 transportStruct.mets=model.metNames(I+nEM);
-0578 transportStruct.toComp=GSS.compartments(J);
-0579 
-0580 [I, J]=find(bestg2c);
-0581 geneLocalization.genes=GSS.genes(I);
-0582 geneLocalization.comps=GSS.compartments(J);
-0583 
-0584 %Resort the gene names
-0585 [~, I]=sort(geneLocalization.genes);
-0586 geneLocalization.genes=geneLocalization.genes(I);
-0587 geneLocalization.comps=geneLocalization.comps(I);
-0588 
-0589 %Remove the fake genes
-0590 I=strncmp('&&FAKE&&',geneLocalization.genes,8);
-0591 geneLocalization.genes(I)=[];
-0592 geneLocalization.comps(I)=[];
-0593 
-0594 %Put together the model. This is done by first duplicating the S matrix
-0595 %into the different compartments. Then the transport reactions are added
-0596 %based on transportStruct. By now model.S should have the same size as the
-0597 %S matrix used in the optimization, but with conserved stoichiometry. In
-0598 %the final step all reactions and metabolites that are not used in the S
-0599 %matrix from the optimization are deleted from the model
-0600 outModel=model;
-0601 outModel.S=oldS;
-0602 
-0603 %This is the S matrix without exchange rxns or metabolites
-0604 copyPart=outModel.S(nEM+1:end,nER+1:end);
-0605 
-0606 %Replicate to give the rxnGeneMat for the full system
-0607 copyRxnGeneMat=outModel.rxnGeneMat(nER+1:end,:);
-0608 outModel.rxnGeneMat=[outModel.rxnGeneMat;repmat(copyRxnGeneMat,nComps-1,1)];
-0609 
-0610 %First fix the compartments. The model is already ordered with the exchange
-0611 %metabolites first. The original model may contain one or two compartments,
-0612 %depending on whether any exchange metabolites are defined
-0613 nStartComps=numel(outModel.comps);
-0614 if nStartComps==1
-0615     outModel.comps={'1'};
-0616     outModel.compNames=GSS.compartments(1);
-0617 else
-0618     if model.metComps(1)==1
-0619         outModel.compNames(1)=GSS.compartments(1);
-0620     else
-0621         outModel.compNames(2)=GSS.compartments(1);
-0622     end
-0623 end
-0624 outModel.compNames=[outModel.compNames;GSS.compartments(2:end)];
-0625 
-0626 %Ugly little loop
-0627 for i=1:numel(GSS.compartments)-1
-0628     outModel.comps=[outModel.comps;num2str(numel(outModel.comps)+1)];
-0629 end
-0630 %This information is not known from the data, so empty fields are added
-0631 outModel.compOutside=cell(numel(outModel.comps),1);
-0632 outModel.compOutside(:)={''};
-0633 
-0634 for i=1:nComps-1
-0635     outModel.S=[outModel.S sparse(size(outModel.S,1),nRxns)];
-0636     outModel.S=[outModel.S;[sparse(nMets,nRxns*i+nER) copyPart]];
-0637     outModel.rxns=[outModel.rxns;strcat(outModel.rxns(nER+1:nER+nRxns),'_',GSS.compartments{i+1})];
-0638     outModel.rxnNames=[outModel.rxnNames;strcat(outModel.rxnNames(nER+1:nER+nRxns),' (',GSS.compartments{i+1},')')];
-0639     outModel.lb=[outModel.lb;outModel.lb(nER+1:nER+nRxns)];
-0640     outModel.ub=[outModel.ub;outModel.ub(nER+1:nER+nRxns)];
-0641     outModel.rev=[outModel.rev;outModel.rev(nER+1:nER+nRxns)];
-0642     outModel.c=[outModel.c;outModel.c(nER+1:nER+nRxns)];
-0643     if isfield(outModel,'grRules')
-0644         outModel.grRules=[outModel.grRules;outModel.grRules(nER+1:nER+nRxns)];
-0645     end
-0646     if isfield(outModel,'subSystems')
-0647         outModel.subSystems=[outModel.subSystems;outModel.subSystems(nER+1:nER+nRxns)];
-0648     end
-0649     if isfield(outModel,'eccodes')
-0650         outModel.eccodes=[outModel.eccodes;outModel.eccodes(nER+1:nER+nRxns)];
-0651     end
-0652     if isfield(outModel,'rxnFrom')
-0653         outModel.rxnFrom=[outModel.rxnFrom;outModel.rxnFrom(nER+1:nER+nRxns)];
-0654     end
-0655     if isfield(outModel,'rxnMiriams')
-0656         outModel.rxnMiriams=[outModel.rxnMiriams;outModel.rxnMiriams(nER+1:nER+nRxns)];
-0657     end
-0658     if isfield(outModel,'rxnNotes')
-0659         outModel.rxnNotes=[outModel.rxnNotes;outModel.rxnNotes(nER+1:nER+nRxns)];
-0660     end
-0661     if isfield(outModel,'rxnReferences')
-0662         outModel.rxnReferences=[outModel.rxnReferences;outModel.rxnReferences(nER+1:nER+nRxns)];
-0663     end
-0664     if isfield(outModel,'rxnConfidenceScores')
-0665         outModel.rxnConfidenceScores=[outModel.rxnConfidenceScores;outModel.rxnConfidenceScores(nER+1:nER+nRxns)];
-0666     end
-0667     if isfield(outModel,'rxnDeltaG')
-0668         outModel.rxnDeltaG=[outModel.rxnDeltaG;outModel.rxnDeltaG(nER+1:nER+nRxns)];
-0669     end
-0670     outModel.mets=[outModel.mets;strcat(outModel.mets(nEM+1:nEM+nMets),'_',GSS.compartments{i+1})];
-0671     outModel.metNames=[outModel.metNames;outModel.metNames(nEM+1:nEM+nMets)];
-0672     outModel.b=[outModel.b;outModel.b(nEM+1:nEM+nMets,:)];
-0673     I=ones(nMets,1)*nStartComps+i;
-0674     outModel.metComps=[outModel.metComps;I];
-0675     if isfield(outModel,'inchis')
-0676         outModel.inchis=[outModel.inchis;outModel.inchis(nEM+1:nEM+nMets)];
-0677     end
-0678     if isfield(outModel,'metSmiles')
-0679         outModel.metSmiles=[outModel.metSmiles;outModel.metSmiles(nEM+1:nEM+nMets)];
-0680     end
-0681     if isfield(outModel,'unconstrained')
-0682         outModel.unconstrained=[outModel.unconstrained;outModel.unconstrained(nEM+1:nEM+nMets)];
-0683     end
-0684     if isfield(outModel,'metMiriams')
-0685         outModel.metMiriams=[outModel.metMiriams;outModel.metMiriams(nEM+1:nEM+nMets)];
-0686     end
-0687     if isfield(outModel,'metFormulas')
-0688         outModel.metFormulas=[outModel.metFormulas;outModel.metFormulas(nEM+1:nEM+nMets)];
-0689     end
-0690     if isfield(outModel,'metFrom')
-0691         outModel.metFrom=[outModel.metFrom;outModel.metFrom(nEM+1:nEM+nMets)];
-0692     end
-0693     if isfield(outModel,'metCharges')
-0694         outModel.metCharges=[outModel.metCharges;outModel.metCharges(nEM+1:nEM+nMets)];
-0695     end
-0696     if isfield(outModel,'metDeltaG')
-0697         outModel.metDeltaG=[outModel.metDeltaG;outModel.metDeltaG(nEM+1:nEM+nMets)];
-0698     end
-0699 end
-0700 
-0701 %Add the transport reactions
-0702 transS=bestS(:,numel(outModel.rxns)+1:end);
-0703 J=sum(transS)>0; %Active rxns
-0704 
-0705 %Transport reactions are written in a different way compared to a "real"
-0706 %stoichimetric matrix. This is to fix that
-0707 transS(transS~=0)=1;
-0708 transS(1:nEM+nMets,:)=transS(1:nEM+nMets,:)*-1;
-0709 I=find(sum(transS>0,2));
-0710 nTransRxns=numel(I);
-0711 outModel.S=[outModel.S transS(:,J)];
-0712 filler=ones(nTransRxns,1);
-0713 outModel.lb=[outModel.lb;filler*-1000];
-0714 outModel.ub=[outModel.ub;filler*1000];
-0715 outModel.rev=[outModel.rev;filler];
-0716 outModel.c=[outModel.c;filler*0];
-0717 outModel.rxnGeneMat=[outModel.rxnGeneMat;sparse(nTransRxns,numel(outModel.genes))];
-0718 
-0719 for i=1:numel(I)
-0720     outModel.rxns=[outModel.rxns;strcat('transport',num2str(i))];
-0721     outModel.rxnNames=[outModel.rxnNames;['Transport of ',outModel.metNames{I(i)}]];
-0722     if isfield(outModel,'grRules')
-0723         outModel.grRules=[outModel.grRules;{''}];
-0724     end
-0725     if isfield(outModel,'rxnMiriams')
-0726         outModel.rxnMiriams=[outModel.rxnMiriams;{[]}];
-0727     end
-0728     if isfield(outModel,'subSystems')
-0729         if any(cellfun(@(x) iscell(x), outModel.subSystems))
-0730             outModel.subSystems=[outModel.subSystems;{{'Inferred transport reactions'}}];
-0731         else
-0732             outModel.subSystems=[outModel.subSystems;{'Inferred transport reactions'}];
-0733         end
-0734     end
-0735     if isfield(outModel,'eccodes')
-0736         outModel.eccodes=[outModel.eccodes;{''}];
-0737     end
-0738     if isfield(outModel,'rxnFrom')
-0739         outModel.rxnFrom=[outModel.rxnFrom;{''}];
-0740     end
-0741     if isfield(outModel,'rxnNotes')
-0742         outModel.rxnNotes=[outModel.rxnNotes;{''}];
-0743     end
-0744     if isfield(outModel,'rxnReferences')
-0745         outModel.rxnReferences=[outModel.rxnReferences;{''}];
-0746     end
-0747     if isfield(outModel,'rxnConfidenceScores')
-0748         outModel.rxnConfidenceScores=[outModel.rxnConfidenceScores;NaN];
-0749     end
-0750     if isfield(outModel,'rxnDeltaG')
-0751         outModel.rxnDeltaG=[outModel.rxnDeltaG;NaN];
-0752     end
-0753 end
-0754 
-0755 %Then remove all reactions and metabolites that aren't used in the final
-0756 %solution from the optimization
-0757 [~, J]=find(bestS(:,1:nER+nComps*nRxns));
-0758 K=true(numel(outModel.rxns),1);
-0759 K(J)=false;
-0760 K(end-nTransRxns+1:end)=false;
-0761 outModel=removeReactions(outModel,K,true);
-0762 
-0763 %Remove all fake genes
-0764 I=strncmp('&&FAKE&&',outModel.genes,8);
-0765 outModel.genes(I)=[];
-0766 if isfield(outModel,'geneMiriams')
-0767     outModel.geneMiriams(I)=[];
-0768 end
-0769 if isfield(outModel,'geneShortNames')
-0770     outModel.geneShortNames(I)=[];
-0771 end
-0772 if isfield(outModel,'proteins')
-0773     outModel.proteins(I)=[];
-0774 end
-0775 outModel.rxnGeneMat(:,I)=[];
-0776 
-0777 %Fix grRules and reconstruct rxnGeneMat
-0778 [grRules,rxnGeneMat] = standardizeGrRules(outModel,true);
-0779 outModel.grRules = grRules;
-0780 outModel.rxnGeneMat = rxnGeneMat;
-0781 end
-0782 
-0783 %Moves a gene and all associated reactions from one compartment to another
-0784 function [S, g2c]=moveGene(S,model,g2c,geneToMove,toComp,nRxns,nMets)
-0785 %Find the current compartment and update to the new one
-0786 currentComp=find(g2c(geneToMove,:));
-0787 g2c(geneToMove,:)=false;
-0788 g2c(geneToMove,toComp)=true;
-0789 
-0790 %Find the reactions in the original model that the gene controls
-0791 [I, ~]=find(model.rxnGeneMat(:,geneToMove));
-0792 
-0793 %Calculate their current positions in the S matrix
-0794 oldRxns=I+(currentComp-1)*nRxns;
-0795 
-0796 %And their new positions
-0797 newRxns=I+(toComp-1)*nRxns;
-0798 
-0799 %The metabolite ids also have to be changed in order to match the new
-0800 %compartment
-0801 metChange=nMets*(toComp-currentComp);
-0802 
-0803 %Update the reactions
-0804 [I, J, K]=find(S(:,oldRxns));
-0805 I=I+metChange;
-0806 
-0807 %Move the reactions
-0808 S(:,oldRxns)=0;
-0809 S(sub2ind(size(S),I,newRxns(J)))=K;
-0810 end
-0811 
-0812 %Finds which metabolites are unconnected, in the sense that they are never
-0813 %a product or only a product in a reversible reaction where one reactant is
-0814 %only a product in the opposite direction of that reaction. This function
-0815 %ignores exchange metabolites. Returns a vector of metabolite indexes.
-0816 %metsToCheck is an array of metabolite indexes to check for connectivity.
-0817 %If not supplied then all metabolites are checked
-0818 function unconnected=findUnconnected(S,nEM,metsToCheck)
-0819 if nargin>2
-0820     %Do this by deleting everything from the network that is not in
-0821     %metsToCheck and that is not exchange metabolites
-0822     I=false(size(S,1),1);
-0823     I(1:nEM)=true;
-0824     I(metsToCheck)=true;
-0825     S=S(I,:);
-0826 end
-0827 
-0828 em=false(size(S,1),1);
-0829 em(1:nEM)=true;
-0830 
-0831 %Construct a matrix in which the reversible reactions are inverted
-0832 I=sum(S>2,1) | sum(S>2,1);
-0833 revS=S;
-0834 revS(:,I)=revS(:,I)*-1;
-0835 
-0836 %First calculate the ones that are ok
-0837 %Produced in 2 rxns, is exchange, is not used at all, is produced in
-0838 %non-reversible, involved in more than 1 reversible reactions
-0839 connected=sum(S>0,2)>1 | em | sum(S~=0,2)==0 | sum(S(:,~I)>0,2)>0 | sum(S(:,I)~=0,2)>1;
-0840 
-0841 %Then get the ones that are unconnected because they are never produced
-0842 unconnected=sum(S>0 | revS>0,2)==0 & connected==false;
-0843 
-0844 %Then get the ones that are potentially unconnected
-0845 maybeUnconnected=~connected & ~unconnected;
-0846 %maybeUnconnected=find(maybeUnconnectedS);
-0847 
-0848 %The metabolites in maybeUnconnected are involved in one reversible
-0849 %reaction and not produced in any other reaction. This means that the
-0850 %reactions which have at least one met in maybeUnconnected as reactant and
-0851 %one as product are unconnected. The metabolites in maybeUnconnected that
-0852 %are present in those reactions are then dead ends
-0853 deadRxns=any(S(maybeUnconnected,:)>0) & any(S(maybeUnconnected,:)<0);
-0854 
-0855 %Get the mets involved in any of those reactions
-0856 problematic=any(S(:,deadRxns)~=0,2);
-0857 
-0858 %If any of these are in the maybeUnconnected list then the metabolite is
-0859 %unconnected
-0860 unconnected(problematic & maybeUnconnected)=true;
-0861 
-0862 %Map back to metsToCheck
-0863 if nargin>2
-0864     unconnected=metsToCheck(unconnected(nEM+1:end));
-0865 else
-0866     unconnected=find(unconnected);
-0867 end
-0868 end
-0869 
-0870 %Given a set of unconnected metabolites, this function tries to move each
-0871 %gene that could connect any of them, calculates the number of newly
-0872 %connected metabolites minus the number of newly disconnected metabolites.
-0873 %As some metabolites are very connected, only 25 genes are checked. Genes
-0874 %that have a low score in their current compartment are more likely to be
-0875 %moved
-0876 function [geneIndex, moveTo, deltaConnected, deltaScore]=selectGenes(S,nEM,nMets,nER,nRxns,model,unconnected,g2c,GSS)
-0877 %If moveTo is 0 then the gene cannot connect any of the metabolites
-0878 moveTo=zeros(numel(model.genes),1);
-0879 deltaConnected=zeros(numel(model.genes),1);
-0880 
-0881 %First get where the metabolites are now
-0882 nComps=size(g2c,2);
-0883 comps=ceil((unconnected-nEM)/((size(S,1)-nEM)/nComps));
-0884 
-0885 %Find the corresponding metabolite indexes if they all were in the default
-0886 %compartment
-0887 dcIndexes=unique(unconnected-(comps-1)*nMets);
-0888 
-0889 %Then find them if they were in any other compartment
-0890 allIndexes=dcIndexes;
-0891 for i=1:nComps-1
-0892     allIndexes=[allIndexes;dcIndexes+nMets*i];
-0893 end
-0894 
-0895 %Also check which reversible reactions that could be used
-0896 I=sum(S>2,1) | sum(S>2,1);
-0897 revS=S;
-0898 revS(:,I)=revS(:,I)*-1;
-0899 
-0900 %Find all reactions that could make any of the unconnected metabolites in
-0901 %some other compartment
-0902 newMets=setdiff(allIndexes,unconnected);
-0903 [~, potential]=find(S(newMets,:)>0 | revS(newMets,:)>0);
-0904 potential(potential<=nER | potential>nER+nRxns*nComps)=[]; %No exchange rxns or transport rxns
-0905 
-0906 %Map J to the real metabolic reactions in model
-0907 rxnComps=ceil((potential-nER)/(nRxns));
-0908 
-0909 %Find the corresponding reaction indexes if they all were in the default
-0910 %compartment
-0911 dcRxnIndexes=potential-(rxnComps-1)*nRxns;
-0912 
-0913 %Get the genes for those reactions
-0914 genes=find(sum(model.rxnGeneMat(dcRxnIndexes,:)>0,1));
-0915 
-0916 %For some cases there can be very many reactions to connect something. This
-0917 %is in particular true in the beginning of the optimization if, say, ATP is
-0918 %unconnected. Therefore limit the number of genes to be checked to 25.
-0919 %Weigh so that genes with bad scores in their current compartment are more
-0920 %likely to be moved.
-0921 
-0922 %Get scores for these genes
-0923 [~, J]=find(g2c(genes,:));
-0924 
-0925 %Add a small weight so that genes in their best compartment could be moved
-0926 %as well
-0927 geneScores=GSS.scores(sub2ind(size(g2c),genes(:),J));
-0928 modGeneScores=1.1-geneScores;
-0929 if numel(genes)>25
-0930     rGenes=genes(randsample(numel(genes),min(numel(genes),25),true,modGeneScores));
-0931     
-0932     %The sampling with weights could give duplicates
-0933     rGenes=unique(rGenes);
-0934     
-0935     %Reorder the geneScores to match
-0936     [~, I]=ismember(rGenes,genes);
-0937     geneScores=geneScores(I);
-0938     genes=rGenes;
-0939 end
-0940 for i=1:numel(genes)
-0941     %Since one gene is moved at a time, only metabolites involved in any of
-0942     %the reactions for that gene can become unconnected. This helps to
-0943     %speed up the algorithm. First get all involved reactions in the
-0944     %default compartment
-0945     rxns=find(model.rxnGeneMat(:,genes(i)));
-0946     
-0947     %Then get their mets
-0948     mets=find(sum(model.S(:,rxns)~=0,2)>0);
-0949     
-0950     %Then get their indexes in all compartments
-0951     allIndexes=mets;
-0952     for j=1:nComps-1
-0953         allIndexes=[allIndexes;mets+nMets*j];
-0954     end
-0955     
-0956     %Check which of the unconnected metabolites that these reactions
-0957     %correspond to. This could have been done earlier, but it is fast. The
-0958     %reversibility check is skipped because it is unlikely to be an issue
-0959     %here. Worst case is that the gene is tested once to much
-0960     [I, ~]=find(model.S(:,rxns));
-0961     moveToComps=unique(comps(ismember(dcIndexes,I)));
-0962     
-0963     %Try to move the gene to each of the compartments
-0964     bestMove=-inf;
-0965     bestComp=[];
-0966     for j=1:numel(moveToComps)
-0967         newS=moveGene(S,model,g2c,genes(i),moveToComps(j),nRxns,nMets);
-0968         
-0969         %Check how many metabolites that are unconnected after moving the
-0970         %gene
-0971         dConnected=numel(unconnected)-numel(findUnconnected(newS,nEM,[allIndexes;unconnected]));
-0972         if dConnected>bestMove
-0973             bestMove=dConnected;
-0974             bestComp=moveToComps(j);
-0975         end
-0976     end
-0977     
-0978     %Add the difference in connectivity and where the genes should be moved
-0979     moveTo(genes(i))=bestComp;
-0980     deltaConnected(genes(i))=bestMove;
-0981 end
-0982 
-0983 %Finish up
-0984 geneIndex=genes(:);
-0985 moveTo=moveTo(geneIndex);
-0986 deltaConnected=deltaConnected(geneIndex);
-0987 deltaScore=GSS.scores(sub2ind(size(g2c),geneIndex(:),moveTo))-geneScores;
-0988 end
-0989 
-0990 %Small function to add a transport reactions between two metabolites.
-0991 %Transport reactions are written as having a coefficient 2.0 for both
-0992 %reactant and product. This is not a "real" reaction, but since all normal
-0993 %reactions have coefficient -1/1 or -10/10 it is a compact way of writing
-0994 %it
-0995 function S=addTransport(S,nRxns,nER,nMets,nEM,nComps,metA,metB)
-0996 mets=[metA;metB];
-0997 %Find the current compartments for the metabolites
-0998 comps=ceil((mets-nEM)/((size(S,1)-nEM)/nComps));
-0999 
-1000 if sum(comps==1)~=1
-1001     EM='Tried to create a transport reaction from a non-default compartment';
-1002     dispEM(EM);
-1003 end
-1004 
-1005 %Calculate the reaction index
-1006 rIndex=(nER+nRxns*nComps)+mets(comps~=1)-nEM-nMets;
-1007 
-1008 S(mets,rIndex)=2;
-1009 end
-1010 
-1011 %Scores a network based on the localization of the genes and the number of
-1012 %transporter reactions used
-1013 function [score, geneScore, transportCost]=scoreModel(S,g2c,GSS,transportCost)
-1014 [I, J]=find(g2c);
-1015 geneScore=sum(GSS.scores(sub2ind(size(g2c),I,J)));
-1016 [I, ~]=find(S==2);
-1017 I=unique(I);
-1018 transportCost=sum(transportCost(I));
-1019 score=geneScore-transportCost;
-1020 end
-1021 
-1022 % To avoid dependency on stats toolbox, use this alternative implementation
-1023 % of randsample, source:
-1024 % https://github.com/gpeyre/numerical-tours/blob/dacee30081c04ef5f67b26b387ead85f2b193af9/matlab/toolbox_signal/randsample.m
-1025 function y = randsample(n, k, replace, w)
-1026 %RANDSAMPLE Random sample, with or without replacement.
-1027 %   Y = RANDSAMPLE(N,K) returns Y as a vector of K values sampled uniformly
-1028 %   at random, without replacement, from the integers 1:N.
-1029 %
-1030 %   Y = RANDSAMPLE(POPULATION,K) returns K values sampled uniformly at
-1031 %   random, without replacement, from the values in the vector POPULATION.
-1032 %
-1033 %   Y = RANDSAMPLE(...,REPLACE) returns a sample taken with replacement if
-1034 %   REPLACE is true, or without replacement if REPLACE is false (the default).
-1035 %
-1036 %   Y = RANDSAMPLE(...,true,W) returns a weighted sample, using positive
-1037 %   weights W, taken with replacement.  W is often a vector of probabilities.
-1038 %   This function does not support weighted sampling without replacement.
-1039 %
-1040 %   Example:  Generate a random sequence of the characters ACGT, with
-1041 %   replacement, according to specified probabilities.
-1042 %
-1043 %      R = randsample('ACGT',48,true,[0.15 0.35 0.35 0.15])
-1044 %
-1045 %   See also RAND, RANDPERM.
-1046 
-1047 %   Copyright 1993-2008 The MathWorks, Inc.
-1048 %   $Revision: 1.1.4.3 $  $Date: 2008/12/01 08:09:34 $
-1049 
-1050 if nargin < 2
-1051     error('stats:randsample:TooFewInputs','Requires two input arguments.');
-1052 elseif numel(n) == 1
-1053     population = [];
-1054 else
-1055     population = n;
-1056     n = numel(population);
-1057     if length(population)~=n
-1058        error('stats:randsample:BadPopulation','POPULATION must be a vector.');
-1059     end
-1060 end
-1061 
-1062 if nargin < 3
-1063     replace = false;
-1064 end
-1065 
-1066 if nargin < 4
-1067     w = [];
-1068 elseif ~isempty(w)
-1069     if length(w) ~= n
-1070         if isempty(population)
-1071             error('stats:randsample:InputSizeMismatch',...
-1072                   'W must have length equal to N.');
-1073         else
-1074             error('stats:randsample:InputSizeMismatch',...
-1075                   'W must have the same length as the population.');
-1076         end
-1077     else
-1078         p = w(:)' / sum(w);
-1079     end
-1080 end
-1081 
-1082 switch replace
-1083 
-1084 % Sample with replacement
-1085 case {true, 'true', 1}
-1086     if isempty(w)
-1087         y = ceil(n .* rand(k,1));
-1088     else
-1089         [dum, y] = histc(rand(k,1),[0 cumsum(p)]);
-1090     end
-1091 
-1092 % Sample without replacement
-1093 case {false, 'false', 0}
-1094     if k > n
-1095         if isempty(population)
-1096             error('stats:randsample:SampleTooLarge',...
-1097         'K must be less than or equal to N for sampling without replacement.');
-1098         else
-1099             error('stats:randsample:SampleTooLarge',...
-1100                   'K must be less than or equal to the population size.');
-1101         end
-1102     end
-1103 
-1104     if isempty(w)
-1105         % If the sample is a sizeable fraction of the population,
-1106         % just randomize the whole population (which involves a full
-1107         % sort of n random values), and take the first k.
-1108         if 4*k > n
-1109             rp = randperm(n);
-1110             y = rp(1:k);
-1111 
-1112         % If the sample is a small fraction of the population, a full sort
-1113         % is wasteful.  Repeatedly sample with replacement until there are
-1114         % k unique values.
-1115         else
-1116             x = zeros(1,n); % flags
-1117             sumx = 0;
-1118             while sumx < k
-1119                 x(ceil(n * rand(1,k-sumx))) = 1; % sample w/replacement
-1120                 sumx = sum(x); % count how many unique elements so far
-1121             end
-1122             y = find(x > 0);
-1123             y = y(randperm(k));
-1124         end
-1125     else
-1126         error('stats:randsample:NoWeighting',...
-1127               'Weighted sampling without replacement is not supported.');
-1128     end
-1129 otherwise
-1130     error('stats:randsample:BadReplaceValue',...
-1131           'REPLACE must be either true or false.');
-1132 end
-1133 
-1134 if ~isempty(population)
-1135     y = population(y);
-1136 else
-1137     y = y(:);
-1138 end
-1139 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/printFluxes.html b/doc/core/printFluxes.html deleted file mode 100644 index 58765a14c..000000000 --- a/doc/core/printFluxes.html +++ /dev/null @@ -1,270 +0,0 @@ - - - - Description of printFluxes - - - - - - - - - -
Home > core > printFluxes.m
- - - -

printFluxes -

- -

PURPOSE ^

-
printFluxes
- -

SYNOPSIS ^

-
function printFluxes(model, fluxes, onlyExchange, cutOffFlux, outputFile,outputString,metaboliteList)
- -

DESCRIPTION ^

-
 printFluxes
-   Prints reactions and fluxes to the screen or to a file
-
- Input:
-   model           a model structure
-   fluxes          a vector with fluxes
-   onlyExchange    only print exchange fluxes (optional, default true)
-   cutOffFlux      only print fluxes with absolute values above or equal
-                   to this value (optional, default 10^-8)
-   outputFile      a file to save the print-out to (optional, default is
-                   output to the command window)
-   outputString    a string that specifies the output of each reaction
-                   (optional, default '%rxnID\t(%rxnName):\t%flux\n')
-   metaboliteList  cell array of metabolite names. Only reactions
-                   involving any of these metabolites will be
-                   printed (optional)
-
- The following codes are available for user-defined output strings:
-
- %rxnID      reaction ID
- %rxnName    reaction name
- %lower      lower bound
- %upper      upper bound
- %obj        objective coefficient
- %eqn        equation
- %flux       flux
- %element    equation using the metabolite formulas rather than
-             metabolite names
- %unbalanced "(*)" if the reaction is unbalanced and "(-)" if it could
-             not be parsed
- %lumped     equation where the elemental compositions for the left/right
-             hand sides are lumped
-
- Usage: printFluxes(model, fluxes, onlyExchange, cutOffFlux, outputFile,...
-                    outputString, metaboliteList)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function printFluxes(model, fluxes, onlyExchange, cutOffFlux, outputFile,outputString,metaboliteList)
-0002 % printFluxes
-0003 %   Prints reactions and fluxes to the screen or to a file
-0004 %
-0005 % Input:
-0006 %   model           a model structure
-0007 %   fluxes          a vector with fluxes
-0008 %   onlyExchange    only print exchange fluxes (optional, default true)
-0009 %   cutOffFlux      only print fluxes with absolute values above or equal
-0010 %                   to this value (optional, default 10^-8)
-0011 %   outputFile      a file to save the print-out to (optional, default is
-0012 %                   output to the command window)
-0013 %   outputString    a string that specifies the output of each reaction
-0014 %                   (optional, default '%rxnID\t(%rxnName):\t%flux\n')
-0015 %   metaboliteList  cell array of metabolite names. Only reactions
-0016 %                   involving any of these metabolites will be
-0017 %                   printed (optional)
-0018 %
-0019 % The following codes are available for user-defined output strings:
-0020 %
-0021 % %rxnID      reaction ID
-0022 % %rxnName    reaction name
-0023 % %lower      lower bound
-0024 % %upper      upper bound
-0025 % %obj        objective coefficient
-0026 % %eqn        equation
-0027 % %flux       flux
-0028 % %element    equation using the metabolite formulas rather than
-0029 %             metabolite names
-0030 % %unbalanced "(*)" if the reaction is unbalanced and "(-)" if it could
-0031 %             not be parsed
-0032 % %lumped     equation where the elemental compositions for the left/right
-0033 %             hand sides are lumped
-0034 %
-0035 % Usage: printFluxes(model, fluxes, onlyExchange, cutOffFlux, outputFile,...
-0036 %                    outputString, metaboliteList)
-0037 
-0038 if nargin<3
-0039     onlyExchange=true;
-0040 end
-0041 if nargin<4
-0042     cutOffFlux=10^-8;
-0043 end
-0044 if isempty(cutOffFlux)
-0045     cutOffFlux=10^-8;
-0046 end
-0047 if nargin<5
-0048     fid=1;
-0049 else
-0050     if ~isempty(outputFile)
-0051         outputFile=char(outputFile);
-0052         fid=fopen(outputFile,'w');
-0053     else
-0054         fid=1;
-0055     end
-0056 end
-0057 if nargin<6 || isempty(outputString)
-0058     outputString='%rxnID\t(%rxnName):\t%flux\n';
-0059 else
-0060     outputString=char(outputString);
-0061 end
-0062 if nargin<7
-0063     metaboliteList={};
-0064 else
-0065     metaboliteList=convertCharArray(metaboliteList);
-0066 end
-0067 if isempty(fluxes)
-0068     EM='Empty vector of fluxes, solveLP possibly returned infeasible';
-0069     dispEM(EM);
-0070 elseif size(fluxes,1)~=numel(model.rxns)
-0071     EM='The number of fluxes and the number of reactions must be the same';
-0072     dispEM(EM);
-0073 end
-0074 
-0075 %Only keep reactions involving the defined metabolites
-0076 if ~isempty(metaboliteList)
-0077     I=ismember(upper(model.metNames),upper(metaboliteList));
-0078     [~, K]=find(model.S(I,:));
-0079     
-0080     %Delete all other reactions
-0081     toDelete=true(numel(model.rxns),1);
-0082     toDelete(K)=false;
-0083     model=removeReactions(model,toDelete);
-0084     fluxes(toDelete,:)=[];
-0085 end
-0086 
-0087 if onlyExchange==true
-0088     fprintf(fid,'EXCHANGE FLUXES:\n');
-0089 else
-0090     fprintf(fid,'FLUXES:\n');
-0091 end
-0092 
-0093 %Remove reactions which are below the cut off
-0094 toDelete=abs(fluxes)<cutOffFlux;
-0095 toDelete=all(toDelete,2);
-0096 model=removeReactions(model,toDelete,true,true);
-0097 fluxes(toDelete,:)=[];
-0098 
-0099 if any(strfind(outputString,'%eqn'))
-0100     %Construct the equations
-0101     eqn=constructEquations(model);
-0102 else
-0103     eqn=cell(numel(model.rxns),1);
-0104     eqn(:)={''};
-0105 end
-0106 if any(strfind(outputString,'%element'))
-0107     %For printing equations using the composition
-0108     cModel=model;
-0109     cModel.metNames=cModel.metFormulas;
-0110     cModel.metNames(cellfun(@isempty,cModel.metNames))={'?'};
-0111     element=constructEquations(cModel);
-0112 else
-0113     element=cell(numel(model.rxns),1);
-0114     element(:)={''};
-0115 end
-0116 
-0117 if any(strfind(outputString,'%unbalanced')) || any(strfind(outputString,'%lumped'))
-0118     balanceStructure=getElementalBalance(model);
-0119 end
-0120 
-0121 unbalanced=cell(numel(model.rxns),1);
-0122 unbalanced(:)={''};
-0123 if any(strfind(outputString,'%unbalanced'))
-0124     unbalanced(balanceStructure.balanceStatus==0)={'(*)'};
-0125     unbalanced(balanceStructure.balanceStatus<0)={'(-)'};
-0126 end
-0127 
-0128 lumped=cell(numel(model.rxns),1);
-0129 lumped(:)={''};
-0130 if any(strfind(outputString,'%lumped'))
-0131     for i=1:numel(model.rxns)
-0132         leftGroup='';
-0133         rightGroup='';
-0134         for j=1:numel(balanceStructure.elements.names)
-0135             I=balanceStructure.leftComp(i,j);
-0136             if I~=0
-0137                 if I==1
-0138                     leftGroup=[leftGroup balanceStructure.elements.abbrevs{j}];
-0139                 else
-0140                     leftGroup=[leftGroup balanceStructure.elements.abbrevs{j} num2str(I)];
-0141                 end
-0142             end
-0143             I=balanceStructure.rightComp(i,j);
-0144             if I~=0
-0145                 if I==1
-0146                     rightGroup=[rightGroup balanceStructure.elements.abbrevs{j}];
-0147                 else
-0148                     rightGroup=[rightGroup balanceStructure.elements.abbrevs{j} num2str(I)];
-0149                 end
-0150             end
-0151         end
-0152         if model.rev(i)
-0153             lumped{i}=[leftGroup ' <=> ' rightGroup];
-0154         else
-0155             lumped{i}=[leftGroup ' => ' rightGroup];
-0156         end
-0157     end
-0158 end
-0159 
-0160 for i=1:numel(model.rxns)
-0161     %Only print if it's an exchange reaction or if all reactions should be
-0162     %printed. Exchange reactions only have reactants or only products.
-0163     reactants=model.S(:,i)<0;
-0164     products=model.S(:,i)>0;
-0165     
-0166     %Only print if the absolute value is >= cutOffFlux
-0167     if (onlyExchange==false || (~any(reactants) || ~any(products)))
-0168         printString=outputString;
-0169         
-0170         %Produce the final string
-0171         printString=strrep(printString,'%rxnID',model.rxns{i});
-0172         printString=strrep(printString,'%eqn',eqn{i});
-0173         printString=strrep(printString,'%rxnName',model.rxnNames{i});
-0174         printString=strrep(printString,'%lower',num2str(model.lb(i)));
-0175         printString=strrep(printString,'%upper',num2str(model.ub(i)));
-0176         printString=strrep(printString,'%obj',num2str(model.c(i)));
-0177         printString=strrep(printString,'%flux',num2str(fluxes(i,:)));
-0178         printString=strrep(printString,'%element',element{i});
-0179         printString=strrep(printString,'%unbalanced',unbalanced{i});
-0180         printString=strrep(printString,'%lumped',lumped{i});
-0181         fprintf(fid,printString);
-0182     end
-0183 end
-0184 
-0185 if fid~=1
-0186     fprintf('File successfully saved.\n');
-0187     fclose(fid);
-0188 end
-0189 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/printModel.html b/doc/core/printModel.html deleted file mode 100644 index 887a7beb1..000000000 --- a/doc/core/printModel.html +++ /dev/null @@ -1,147 +0,0 @@ - - - - Description of printModel - - - - - - - - - -
Home > core > printModel.m
- - - -

printModel -

- -

PURPOSE ^

-
printModel
- -

SYNOPSIS ^

-
function printModel(model,rxnList,outputString,outputFile,metaboliteList)
- -

DESCRIPTION ^

-
 printModel
-   Prints reactions to the screen or to a file
-
-   model           a model structure
-   rxnList         either a cell array of reaction IDs, a logical vector 
-                   with the same number of elements as reactions in the model,
-                   or a vector of indexes to remove (optional, default
-                   model.rxns)
-   outputString    a string that specifies the output of each reaction (optional,
-                   default '%rxnID (%rxnName)\n\t%eqn [%lower %upper]\n')
-   outputFile      a file to save the print-out to (optional, default is output to
-                   the command window)
-   metaboliteList  cell array of metabolite names. Only reactions
-                   involving any of these metabolites will be 
-                   printed (optional)
-
-   The following codes are available for user-defined output strings:
-
-   %rxnID      reaction ID
-   %rxnName    reaction name
-   %lower      lower bound
-   %upper      upper bound
-   %obj        objective coefficient
-   %eqn        equation
-   %element    equation using the metabolite formulas rather than
-               metabolite names
-   %unbalanced "(*)" if the reaction is unbalanced and "(-)" if it could not
-               be parsed
-   %lumped     equation where the elemental compositions for the left/right
-               hand sides are lumped
-
-   NOTE: This is just a wrapper function around printFluxes. It is
-           intended to be used when there is no flux distribution.
-
- Usage: printModel(model,rxnList,outputString,outputFile,metaboliteList)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function printModel(model,rxnList,outputString,outputFile,metaboliteList)
-0002 % printModel
-0003 %   Prints reactions to the screen or to a file
-0004 %
-0005 %   model           a model structure
-0006 %   rxnList         either a cell array of reaction IDs, a logical vector
-0007 %                   with the same number of elements as reactions in the model,
-0008 %                   or a vector of indexes to remove (optional, default
-0009 %                   model.rxns)
-0010 %   outputString    a string that specifies the output of each reaction (optional,
-0011 %                   default '%rxnID (%rxnName)\n\t%eqn [%lower %upper]\n')
-0012 %   outputFile      a file to save the print-out to (optional, default is output to
-0013 %                   the command window)
-0014 %   metaboliteList  cell array of metabolite names. Only reactions
-0015 %                   involving any of these metabolites will be
-0016 %                   printed (optional)
-0017 %
-0018 %   The following codes are available for user-defined output strings:
-0019 %
-0020 %   %rxnID      reaction ID
-0021 %   %rxnName    reaction name
-0022 %   %lower      lower bound
-0023 %   %upper      upper bound
-0024 %   %obj        objective coefficient
-0025 %   %eqn        equation
-0026 %   %element    equation using the metabolite formulas rather than
-0027 %               metabolite names
-0028 %   %unbalanced "(*)" if the reaction is unbalanced and "(-)" if it could not
-0029 %               be parsed
-0030 %   %lumped     equation where the elemental compositions for the left/right
-0031 %               hand sides are lumped
-0032 %
-0033 %   NOTE: This is just a wrapper function around printFluxes. It is
-0034 %           intended to be used when there is no flux distribution.
-0035 %
-0036 % Usage: printModel(model,rxnList,outputString,outputFile,metaboliteList)
-0037 
-0038 if nargin<2 || isempty(rxnList)
-0039     rxnList=model.rxns;
-0040 elseif ~islogical(rxnList) && ~isnumeric(rxnList)
-0041     rxnList=convertCharArray(rxnList);
-0042 end
-0043 if nargin<3 || isempty(outputString)
-0044     outputString='%rxnID (%rxnName)\n\t%eqn [%lower %upper]\n';
-0045 else
-0046     outputString=char(outputString);
-0047 end
-0048 if nargin<4
-0049     outputFile=[];
-0050 else
-0051     outputFile=char(outputFile);
-0052 end
-0053 if nargin<5
-0054     metaboliteList=[];
-0055 else
-0056     metaboliteList=convertCharArray(metaboliteList);
-0057 end
-0058 
-0059 I=getIndexes(model,rxnList,'rxns',true)*1.00; %To convert it to "fluxes"
-0060 
-0061 if ~isempty(metaboliteList)
-0062     printFluxes(model, I, false, 0.1, outputFile,outputString,metaboliteList);
-0063 else
-0064     printFluxes(model, I, false, 0.1, outputFile,outputString);
-0065 end
-0066 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/printModelStats.html b/doc/core/printModelStats.html deleted file mode 100644 index f7abf19aa..000000000 --- a/doc/core/printModelStats.html +++ /dev/null @@ -1,221 +0,0 @@ - - - - Description of printModelStats - - - - - - - - - -
Home > core > printModelStats.m
- - - -

printModelStats -

- -

PURPOSE ^

-
printModelStats
- -

SYNOPSIS ^

-
function printModelStats(model, printModelIssues, printDetails)
- -

DESCRIPTION ^

-
 printModelStats
-   prints some statistics about a model to the screen
-
-   model               a model structure
-   printModelIssues    true if information about unconnected
-                       reactions/metabolites and elemental balancing
-                       should be printed (optional, default false)
-   printDetails        true if detailed information should be printed
-                       about model issues. Only used if printModelIssues
-                       is true (optional, default true)
-
- Usage: printModelStats(model,printModelIssues, printDetails)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function printModelStats(model, printModelIssues, printDetails)
-0002 % printModelStats
-0003 %   prints some statistics about a model to the screen
-0004 %
-0005 %   model               a model structure
-0006 %   printModelIssues    true if information about unconnected
-0007 %                       reactions/metabolites and elemental balancing
-0008 %                       should be printed (optional, default false)
-0009 %   printDetails        true if detailed information should be printed
-0010 %                       about model issues. Only used if printModelIssues
-0011 %                       is true (optional, default true)
-0012 %
-0013 % Usage: printModelStats(model,printModelIssues, printDetails)
-0014 
-0015 if nargin<2
-0016     printModelIssues=false;
-0017 end
-0018 if nargin<3
-0019     printDetails=true;
-0020 end
-0021 
-0022 fprintf(['Network statistics for ' model.id ': ' model.name '\n']);
-0023 
-0024 %Get which reactions are present in each compartment
-0025 rxnComps=sparse(numel(model.rxns),numel(model.comps));
-0026 
-0027 %For each compartment, find the metabolites that are present in that
-0028 %compartment and then the reactions they are involved in
-0029 for i=1:numel(model.comps)
-0030     [~, I]=find(model.S(model.metComps==i,:));
-0031     rxnComps(I,i)=1;
-0032 end
-0033 
-0034 if isfield(model,'eccodes')
-0035     fprintf(['EC-numbers\t\t\t' num2str(numel(unique(model.eccodes))) '\n']);
-0036 end
-0037 
-0038 %Print information about genes
-0039 if isfield(model,'genes')
-0040     fprintf(['Genes*\t\t\t\t' num2str(numel(model.genes)) '\n']);
-0041     %Find the genes in each compartment
-0042     for i=1:numel(model.comps)
-0043         [~, I]=find(model.rxnGeneMat(rxnComps(:,i)==1,:));
-0044         fprintf(['\t' model.compNames{i} '\t' num2str(numel(unique(I))) '\n']);
-0045     end
-0046 end
-0047 
-0048 %Print information about reactions
-0049 fprintf(['\nReactions*\t\t\t' num2str(numel(model.rxns)) '\n']);
-0050 for i=1:numel(model.comps)
-0051     fprintf(['\t' model.compNames{i} '\t' num2str(sum(rxnComps(:,i))) '\n']);
-0052 end
-0053 
-0054 %Removes the effect of compartments and removes duplicate reactions
-0055 temp=model;
-0056 temp.comps(:)={'s'}; %Set all compartments to be the same
-0057 equ=constructEquations(sortModel(temp,true,true),temp.rxns,false);
-0058 
-0059 fprintf(['Unique reactions**\t' num2str(numel(unique(equ))) '\n']);
-0060 
-0061 %Print information about metabolites
-0062 fprintf(['\nMetabolites\t\t\t' num2str(numel(model.mets)) '\n']);
-0063 for i=1:numel(model.comps)
-0064     fprintf(['\t' model.compNames{i} '\t' num2str(sum(model.metComps==i)) '\n']);
-0065 end
-0066 
-0067 fprintf(['Unique metabolites\t' num2str(numel(unique(model.metNames))) '\n']);
-0068 
-0069 fprintf('\n* Genes and reactions are counted for each compartment if any of the corresponding metabolites are in that compartment. The sum may therefore not add up to the total number.\n');
-0070 fprintf('** Unique reactions are defined as being biochemically unique (no compartmentalization)\n');
-0071 
-0072 %Also print some potential problems if there are any
-0073 if printModelIssues==true
-0074     fprintf(['\nShort model quality summary for ' model.id ': ' model.name '\n']);
-0075     
-0076     %Check that all the metabolites are being used
-0077     involvedMat=model.S;
-0078     involvedMat(involvedMat~=0)=1;
-0079     usedMets=sum(involvedMat,2);
-0080     notPresent=find(usedMets==0);
-0081     if ~isempty(notPresent)
-0082         errorText=['Non-used metabolites\t' num2str(numel(notPresent)) '\n'];
-0083         if printDetails==true
-0084             for i=1:numel(notPresent)
-0085                 errorText=[errorText '\t(' model.mets{notPresent(i)} ') ' model.metNames{notPresent(i)} '\n'];
-0086             end
-0087             errorText=[errorText '\n'];
-0088         end
-0089         fprintf(errorText);
-0090     end
-0091     
-0092     %Check if there are empty reactions
-0093     usedRxns=sum(involvedMat,1);
-0094     notUsed=find(usedRxns==0);
-0095     if ~isempty(notUsed)
-0096         errorText=['Empty reactions\t' num2str(numel(notUsed)) '\n'];
-0097         if printDetails==true
-0098             for i=1:numel(notUsed)
-0099                 errorText=[errorText '\t' model.rxns{notUsed(i)} '\n'];
-0100             end
-0101             errorText=[errorText '\n'];
-0102         end
-0103         fprintf(errorText);
-0104     end
-0105     
-0106     %Check if there are dead-end reactions/metabolites
-0107     [~, deletedReactions, deletedMetabolites]=simplifyModel(model,true,false,false,true);
-0108     
-0109     if ~isempty(deletedReactions)
-0110         errorText=['Dead-end reactions\t' num2str(numel(deletedReactions)) '\n'];
-0111         if printDetails==true
-0112             for i=1:numel(deletedReactions)
-0113                 errorText=[errorText '\t' deletedReactions{i} '\n'];
-0114             end
-0115             errorText=[errorText '\n'];
-0116         end
-0117         fprintf(errorText);
-0118     end
-0119     
-0120     %Ignore non-used metabolites
-0121     deletedMetabolites=setdiff(deletedMetabolites,model.mets(notPresent));
-0122     %Must map to indexes in order to print names
-0123     deletedMetabolites=find(ismember(model.mets,deletedMetabolites));
-0124     if ~isempty(deletedMetabolites)
-0125         errorText=['Dead-end metabolites\t' num2str(numel(deletedMetabolites)) '\n'];
-0126         if printDetails==true
-0127             for i=1:numel(deletedMetabolites)
-0128                 errorText=[errorText '\t(' model.mets{deletedMetabolites(i)} ') ' model.metNames{deletedMetabolites(i)} '\n'];
-0129             end
-0130             errorText=[errorText '\n'];
-0131         end
-0132         fprintf(errorText);
-0133     end
-0134     
-0135     balanceStructure=getElementalBalance(model);
-0136     
-0137     notParsed=find(balanceStructure.balanceStatus<0);
-0138     notBalanced=find(balanceStructure.balanceStatus==0);
-0139     
-0140     if ~isempty(notParsed)
-0141         errorText=['Reactions which could not be elementally balanced\t' num2str(numel(notParsed)) '\n'];
-0142         if printDetails==true
-0143             for i=1:numel(notParsed)
-0144                 errorText=[errorText '\t' model.rxns{notParsed(i)} '\n'];
-0145             end
-0146             errorText=[errorText '\n'];
-0147         end
-0148         fprintf(errorText);
-0149     end
-0150     if ~isempty(notBalanced)
-0151         errorText=['Reactions which are elementally unbalanced\t' num2str(numel(notBalanced)) '\n'];
-0152         if printDetails==true
-0153             names=strcat(balanceStructure.elements.names,{', '});
-0154             for i=1:numel(notBalanced)
-0155                 badOnes=sprintf('%s', names{abs(balanceStructure.leftComp(notBalanced(i),:)-balanceStructure.rightComp(notBalanced(i),:))>10^-7});
-0156                 errorText=[errorText '\t' model.rxns{notBalanced(i)} '\t' badOnes(1:end-2) '\n'];
-0157             end
-0158             errorText=[errorText '\n'];
-0159         end
-0160         fprintf(errorText);
-0161     end
-0162 end
-0163 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/printOrange.html b/doc/core/printOrange.html deleted file mode 100644 index 20753a03a..000000000 --- a/doc/core/printOrange.html +++ /dev/null @@ -1,78 +0,0 @@ - - - - Description of printOrange - - - - - - - - - -
Home > core > printOrange.m
- - - -

printOrange -

- -

PURPOSE ^

-
printOrange
- -

SYNOPSIS ^

-
function orangeString = printOrange(stringToPrint)
- -

DESCRIPTION ^

-
 printOrange
-   Print orange-colored stringToPrint to the MATLAB Command Window. Only
-   if MATLAB is open with GUI, does not work with command-line MATLAB.
-
- Input: 
-   stringToPrint   string that should be printed in orange color
-
- Usage: printOrange(stringToPrint)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function orangeString = printOrange(stringToPrint)
-0002 % printOrange
-0003 %   Print orange-colored stringToPrint to the MATLAB Command Window. Only
-0004 %   if MATLAB is open with GUI, does not work with command-line MATLAB.
-0005 %
-0006 % Input:
-0007 %   stringToPrint   string that should be printed in orange color
-0008 %
-0009 % Usage: printOrange(stringToPrint)
-0010 
-0011 try useDesktop = usejava('desktop'); catch, useDesktop = false; end
-0012 if useDesktop
-0013     orangeString = ['[\b' stringToPrint,']\b'];
-0014 else
-0015     orangeString = stringToPrint;
-0016 end
-0017 if nargout < 1
-0018     % Wrap text to command window size
-0019     sz = get(0, 'CommandWindowSize');
-0020     orangeString = textwrap({orangeString},sz(1));
-0021     orangeString = strjoin(orangeString,'\n');
-0022     fprintf(orangeString);
-0023 end
-0024 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/randomSampling.html b/doc/core/randomSampling.html deleted file mode 100644 index 17bf0e439..000000000 --- a/doc/core/randomSampling.html +++ /dev/null @@ -1,317 +0,0 @@ - - - - Description of randomSampling - - - - - - - - - -
Home > core > randomSampling.m
- - - -

randomSampling -

- -

PURPOSE ^

-
randomSampling
- -

SYNOPSIS ^

-
function [solutions, goodRxns]=randomSampling(model,nSamples,replaceBoundsWithInf,supressErrors,runParallel,goodRxns,minFlux)
- -

DESCRIPTION ^

-
 randomSampling
-   Performs random sampling of the solution space, as described in Bordel
-   et al. (2010) PLOS Compt Biol (doi:10.1371/journal.pcbi.1000859).
-
- Input:
-   model                   a model structure
-   nSamples                the number of solutions to return
-                           (optional, default 1000)
-   replaceBoundsWithInf    replace the largest upper bounds with Inf and
-                           the smallest lower bounds with -Inf. This is
-                           needed in order to get solutions without loops
-                           if your model has for example 1000/-1000 as
-                           arbitary large bounds. If your model only has
-                           "biologically relevant" bounds, then set this
-                           to false (optional, default true)
-   supressErrors           the program will halt if it has problems
-                           finding non-zero solutions which are not
-                           involved in loops. This could be because the
-                           constraints on the model are too relaxed (such
-                           as unlimited glucose uptake) or too strict
-                           (such as too many and too narrow constraints)
-                           (optional, default false)
-   runParallel             speed up calculations by parallel processing.
-                           Requires MATLAB Parallel Computing Toolbox. If
-                           this is not installed, the calculations will
-                           not be parallelized, regardless what is
-                           indicated as runParallel. (optional, default
-                           true)
-   goodRxns                double vector of indexes of those reactions
-                           that are not involved in loops and can be used
-                           as random objective functions, as generated by
-                           a previous run of randomSampling on the same
-                           model (optional, default empty)
-   minFlux                 determines if a second optimization should be
-                           performed for each random sample, to minimize
-                           the number of fluxes and thereby preventing
-                           loops. Typically, loops are averaged out when a
-                           large number of samples are taken, but this is
-                           not always the case (optional, default false)
-
- Output:
-   solutions               matrix with the solutions
-   goodRxns                double vector of indexes of those reactions
-                           that are not involved in loops or always carry
-                           zero flux and can be used as random objective
-                           functions
-
- Note: The solutions are generated by maximizing (with random weights) for
- a random set of three reactions. For reversible reactions it randomly
- chooses between maximizing and minimizing.
-
- If the model is a GECKO v3+ ecModel, then usage_prot reactions are not
- selected for sampling, instead focusing on sampling from the metabolic
- aspects that form the solution space.
-
- Usage: solutions = randomSampling(model, nSamples, replaceBoundsWithInf,...
-                       supressErrors, runParallel, goodRxns, minFlux)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 function [solutions, goodRxns]=randomSampling(model,nSamples,replaceBoundsWithInf,supressErrors,runParallel,goodRxns,minFlux)
-0002 % randomSampling
-0003 %   Performs random sampling of the solution space, as described in Bordel
-0004 %   et al. (2010) PLOS Compt Biol (doi:10.1371/journal.pcbi.1000859).
-0005 %
-0006 % Input:
-0007 %   model                   a model structure
-0008 %   nSamples                the number of solutions to return
-0009 %                           (optional, default 1000)
-0010 %   replaceBoundsWithInf    replace the largest upper bounds with Inf and
-0011 %                           the smallest lower bounds with -Inf. This is
-0012 %                           needed in order to get solutions without loops
-0013 %                           if your model has for example 1000/-1000 as
-0014 %                           arbitary large bounds. If your model only has
-0015 %                           "biologically relevant" bounds, then set this
-0016 %                           to false (optional, default true)
-0017 %   supressErrors           the program will halt if it has problems
-0018 %                           finding non-zero solutions which are not
-0019 %                           involved in loops. This could be because the
-0020 %                           constraints on the model are too relaxed (such
-0021 %                           as unlimited glucose uptake) or too strict
-0022 %                           (such as too many and too narrow constraints)
-0023 %                           (optional, default false)
-0024 %   runParallel             speed up calculations by parallel processing.
-0025 %                           Requires MATLAB Parallel Computing Toolbox. If
-0026 %                           this is not installed, the calculations will
-0027 %                           not be parallelized, regardless what is
-0028 %                           indicated as runParallel. (optional, default
-0029 %                           true)
-0030 %   goodRxns                double vector of indexes of those reactions
-0031 %                           that are not involved in loops and can be used
-0032 %                           as random objective functions, as generated by
-0033 %                           a previous run of randomSampling on the same
-0034 %                           model (optional, default empty)
-0035 %   minFlux                 determines if a second optimization should be
-0036 %                           performed for each random sample, to minimize
-0037 %                           the number of fluxes and thereby preventing
-0038 %                           loops. Typically, loops are averaged out when a
-0039 %                           large number of samples are taken, but this is
-0040 %                           not always the case (optional, default false)
-0041 %
-0042 % Output:
-0043 %   solutions               matrix with the solutions
-0044 %   goodRxns                double vector of indexes of those reactions
-0045 %                           that are not involved in loops or always carry
-0046 %                           zero flux and can be used as random objective
-0047 %                           functions
-0048 %
-0049 % Note: The solutions are generated by maximizing (with random weights) for
-0050 % a random set of three reactions. For reversible reactions it randomly
-0051 % chooses between maximizing and minimizing.
-0052 %
-0053 % If the model is a GECKO v3+ ecModel, then usage_prot reactions are not
-0054 % selected for sampling, instead focusing on sampling from the metabolic
-0055 % aspects that form the solution space.
-0056 %
-0057 % Usage: solutions = randomSampling(model, nSamples, replaceBoundsWithInf,...
-0058 %                       supressErrors, runParallel, goodRxns, minFlux)
-0059 
-0060 if nargin<2 | isempty(nSamples)
-0061     nSamples=1000;
-0062 end
-0063 if nargin<3 | isempty(replaceBoundsWithInf)
-0064     replaceBoundsWithInf=true;
-0065 end
-0066 if nargin<4 | isempty(supressErrors)
-0067     supressErrors=false;
-0068 end
-0069 if nargin<5 | isempty(runParallel)
-0070     runParallel=true;
-0071 end
-0072 if nargin<7 | isempty(minFlux)
-0073     minFlux=false;
-0074 end
-0075 
-0076 [ps, oldPoolAutoCreateSetting] = parallelPoolRAVEN(runParallel);
-0077 
-0078 nObjRxns=2; %Number of reactions in the objective function in each iteration
-0079 
-0080 %Simplify the model to speed stuff up a little. Keep original mapping
-0081 originalRxns=model.rxns;
-0082 model=simplifyModel(model,false,false,true,true);
-0083 
-0084 %Then change the bounds to +/- Inf. This is needed in order to not have
-0085 %loops in the solutions
-0086 if replaceBoundsWithInf==true
-0087     model.ub(model.ub==max(model.ub))=Inf;
-0088     if min(model.lb)<0 % Only negative lower bounds should be set to -Inf
-0089         model.lb(model.lb==min(model.lb))=-Inf;
-0090     end
-0091 end
-0092 
-0093 %Check that the model is feasible given the constraints
-0094 [sol,~]=solveLP(model);
-0095 if isempty(sol.x)
-0096     EM='The model has no feasible solution, likely due to incompatible constraints';
-0097     dispEM(EM);
-0098 elseif sol.f==0 && showProgress
-0099     warning('The model objective function cannot reach a non-zero value. This might be intended, so randomSampling will continue, but this could indicate problems with your model')
-0100 end
-0101 
-0102 nRxns = numel(model.rxns);
-0103 %Reactions which can be involved in loops should not be optimized for.
-0104 %Check which reactions reach an arbitary high upper bound
-0105 if nargin<6 || isempty(goodRxns)
-0106     revRxns = transpose(find(model.lb < 0));
-0107     fwdRxns = transpose(find(model.ub > 0));
-0108     rxnList = [fwdRxns,revRxns];
-0109     objList = [ones(numel(fwdRxns),1);-ones(numel(revRxns),1)];
-0110     testSol = zeros(numel(objList),1);
-0111     PB = ProgressBar2(nRxns,'Prepare goodRxns not involved in loops','cli');
-0112 
-0113     parfor i = 1:numel(objList)
-0114         testModel=setParam(model,'obj',rxnList(i),objList(i));
-0115         sol=solveLP(testModel,0);
-0116         if ~isempty(sol.f)
-0117             testSol(i) = sol.x(rxnList(i));
-0118         end
-0119         count(PB);
-0120     end
-0121     testSol  = testSol.*objList;
-0122     goodRxns = true(nRxns,1);
-0123     % Filter out reactions that can reach (-)1000 (= involved in loop)
-0124     goodRxns(fwdRxns(testSol(1:numel(fwdRxns)) > 999)) = false;
-0125     goodRxns(revRxns(testSol(numel(fwdRxns)+1:end) > 999)) = false;
-0126     testSol(revRxns) = testSol(revRxns) + testSol(numel(fwdRxns)+1:end);
-0127     % Filter out reactions that cannot carry flux
-0128     goodRxns(testSol(1:nRxns) == 0) = false;
-0129     % In ecModels do not sample from usage_prot reactions
-0130     if isfield(model,'ec')
-0131         usageRxns = startsWith(model.rxns,'usage_prot_');
-0132         goodRxns(usageRxns) = false;
-0133     end
-0134     goodRxns = find(goodRxns);
-0135 end
-0136 
-0137 %Reserve space for a solution matrix
-0138 sols = zeros(numel(model.rxns),nSamples);
-0139 sols = num2cell(sols,1);
-0140 
-0141 %Main loop
-0142 if nSamples > 0
-0143 
-0144     PB = ProgressBar2(nSamples,'Performing random sampling','cli');
-0145     parfor i=1:nSamples
-0146         badSolutions = 1;
-0147         tmpModel = model;
-0148         while lt(0,badSolutions)
-0149             rxns = randsample(numel(goodRxns),nObjRxns);
-0150             tmpModel.c = zeros(numel(tmpModel.rxns),1);
-0151             
-0152             multipliers = randsample([-1 1],nObjRxns,true);
-0153             multipliers(tmpModel.ub(goodRxns(rxns))<0) = 1;
-0154             
-0155             tmpModel.c(goodRxns(rxns)) = rand(nObjRxns,1).*multipliers;
-0156 
-0157             if true(minFlux)
-0158                 sol=solveLP(tmpModel,1);
-0159             else
-0160                 sol=solveLP(tmpModel,0);
-0161             end
-0162             if any(sol.x) && abs(sol.f)>10^-8
-0163                 sols{i} = sol.x;
-0164                 badSolutions = 0;
-0165             else
-0166                 badSolutions = badSolutions+1;
-0167                 %If it only finds bad solutions then throw an error.
-0168                 if badSolutions == 100 && supressErrors==false
-0169                     error('The program is having problems finding non-zero solutions (ignoring reactions that might be involved in loops). Review the constraints on your model. Set supressErrors to true to ignore this error');
-0170                 end
-0171             end
-0172         end
-0173         count(PB);
-0174     end
-0175 
-0176     %Map to original model
-0177     sols = cell2mat(sols);
-0178     [~, I]=ismember(model.rxns,originalRxns);
-0179     solutions=zeros(numel(originalRxns),nSamples);
-0180     solutions(I,:)=sols;
-0181 else
-0182     solutions=[];
-0183 end
-0184 % Reset original Parallel setting
-0185 ps.Pool.AutoCreate = oldPoolAutoCreateSetting;
-0186 end
-0187 
-0188 %To use instead of the normal Matlab randsample function. This is in order
-0189 %to not depend on the Matlab statistical toolbox.
-0190 function I=randsample(n,k,replacement)
-0191 if nargin<3
-0192     replacement=false;
-0193 end
-0194 %n can be a integer, which leads to I being sampled from 1:n, or it can be
-0195 %a population to sample from.
-0196 if numel(n)==1 && isnumeric(n)
-0197     n=1:n;
-0198 end
-0199 %Loop and get random numbers until the list is unique. This is only a good
-0200 %option is the number of samples is small compared to the population. There
-0201 %are several checks that should be made here, for example regarding size
-0202 %and that the number of samples is <=population size if replacement==false.
-0203 %This is not the case in randomSampling, so such checks are ignored
-0204 while true
-0205     J=randi(numel(n),[k,1]);
-0206     if replacement==true || numel(J)==numel(unique(J))
-0207         I=n(J);
-0208         break;
-0209     end
-0210 end
-0211 I=I(:);
-0212 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/removeBadRxns.html b/doc/core/removeBadRxns.html deleted file mode 100644 index 2c3e20e2a..000000000 --- a/doc/core/removeBadRxns.html +++ /dev/null @@ -1,357 +0,0 @@ - - - - Description of removeBadRxns - - - - - - - - - -
Home > core > removeBadRxns.m
- - - -

removeBadRxns -

- -

PURPOSE ^

-
removeBadRxns
- -

SYNOPSIS ^

-
function [newModel, removedRxns]=removeBadRxns(model,rxnRules,ignoreMets,isNames,balanceElements,refModel,ignoreIntBounds,printReport)
- -

DESCRIPTION ^

-
 removeBadRxns
-   Iteratively removes reactions which enable production/consumption of some
-   metabolite without any uptake/excretion
-
-   model                   a model structure. For the intented function,
-                           the model shouldn't allow for any uptake/excretion.
-                           The easiest way to achieve this is to import the
-                           model using importModel('filename',false)
-   rxnRules                1: only remove reactions which are unbalanced
-                           2: also remove reactions which couldn't be checked for
-                           mass balancing
-                           3: all reactions can be removed
-                           (optional, default 1)
-   ignoreMets              either a cell array of metabolite IDs, a logical vector
-                           with the same number of elements as metabolites in the model,
-                           of a vector of indexes for metabolites to exclude from
-                           this analysis (optional, default [])
-   isNames                 true if the supplied mets represent metabolite names
-                           (as opposed to IDs). This is a way to delete
-                           metabolites in several compartments at once without
-                           knowing the exact IDs. This only works if ignoreMets
-                           is a cell array (optional, default false)
-   balanceElements         a cell array with the elements for which to
-                           balance the reactions. May contain any
-                           combination of the elements defined in parseFormulas
-                           (optional, default {'C';'P';'S';'N';'O'})
-   refModel                a reference model which can be used to ensure
-                           that the resulting model is still functional.
-                           The intended use is that the reference model is
-                           a copy of model, but with uptake/excretion allowed and
-                           some objectives (such as production of biomass)
-                           constrained to a non-zero flux. Before a
-                           reaction is removed from "model" the function first
-                           checks that the same deletion in "refModel"
-                           doesn't render the problem unfeasible (optional)
-   ignoreIntBounds         true if internal bounds (including reversibility)
-                           should be ignored. Exchange reactions are not affected.
-                           This can be used to find unbalanced solutions which are
-                           not possible using the default constraints (optional,
-                           default false)
-   printReport             true if a report should be printed (optional,
-                           default false)
-
-   newModel                   a model structure after the problematic
-                           reactions have been deleted
-   removedRxns             a cell array with the reactions that were
-                           removed
-
-   The purpose of this function is to remove reactions which enable
-   production/consumption of metabolites even when exchange reactions aren't used.
-   Many models, especially if they are automatically inferred from
-   databases, will have unbalanced reactions which allow for
-   net-production/consumption of metabolites without any consumption/excretion.
-   A common reason for this is when general compounds have different meaning
-   in different reactions (as DNA has in these two reactions).
-       dATP + dGTP + dCTP + dTTP <=> DNA + 4 PPi
-       0.25 dATP + 0.25 dGTP + 0.25 dCTP + 0.25 dTTP <=> DNA + PPi
-   Reactions that are problematic like this are always elementally
-   unbalanced, but it is not always that you would like to exclude all
-   unbalanced reactions from your model.
-   This function tries to remove as few problematic reactions as possible
-   so that the model cannot produce/consume anything from nothing. This is done by
-   repeatedly calling makeSomething/consumeSomething, checking if any of
-   the involved reactions are elementally unbalanced, remove one of them,
-   and then iterating until no metabolites can be produced/consumed.
-   makeSomething is called before consumeSomething.
-
- Usage: [newModel, removedRxns]=removeBadRxns(model,rxnRules,...
-       ignoreMets,isNames,refModel,ignoreIntBounds,printReport)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function [newModel, removedRxns]=removeBadRxns(model,rxnRules,ignoreMets,isNames,balanceElements,refModel,ignoreIntBounds,printReport)
-0002 % removeBadRxns
-0003 %   Iteratively removes reactions which enable production/consumption of some
-0004 %   metabolite without any uptake/excretion
-0005 %
-0006 %   model                   a model structure. For the intented function,
-0007 %                           the model shouldn't allow for any uptake/excretion.
-0008 %                           The easiest way to achieve this is to import the
-0009 %                           model using importModel('filename',false)
-0010 %   rxnRules                1: only remove reactions which are unbalanced
-0011 %                           2: also remove reactions which couldn't be checked for
-0012 %                           mass balancing
-0013 %                           3: all reactions can be removed
-0014 %                           (optional, default 1)
-0015 %   ignoreMets              either a cell array of metabolite IDs, a logical vector
-0016 %                           with the same number of elements as metabolites in the model,
-0017 %                           of a vector of indexes for metabolites to exclude from
-0018 %                           this analysis (optional, default [])
-0019 %   isNames                 true if the supplied mets represent metabolite names
-0020 %                           (as opposed to IDs). This is a way to delete
-0021 %                           metabolites in several compartments at once without
-0022 %                           knowing the exact IDs. This only works if ignoreMets
-0023 %                           is a cell array (optional, default false)
-0024 %   balanceElements         a cell array with the elements for which to
-0025 %                           balance the reactions. May contain any
-0026 %                           combination of the elements defined in parseFormulas
-0027 %                           (optional, default {'C';'P';'S';'N';'O'})
-0028 %   refModel                a reference model which can be used to ensure
-0029 %                           that the resulting model is still functional.
-0030 %                           The intended use is that the reference model is
-0031 %                           a copy of model, but with uptake/excretion allowed and
-0032 %                           some objectives (such as production of biomass)
-0033 %                           constrained to a non-zero flux. Before a
-0034 %                           reaction is removed from "model" the function first
-0035 %                           checks that the same deletion in "refModel"
-0036 %                           doesn't render the problem unfeasible (optional)
-0037 %   ignoreIntBounds         true if internal bounds (including reversibility)
-0038 %                           should be ignored. Exchange reactions are not affected.
-0039 %                           This can be used to find unbalanced solutions which are
-0040 %                           not possible using the default constraints (optional,
-0041 %                           default false)
-0042 %   printReport             true if a report should be printed (optional,
-0043 %                           default false)
-0044 %
-0045 %   newModel                   a model structure after the problematic
-0046 %                           reactions have been deleted
-0047 %   removedRxns             a cell array with the reactions that were
-0048 %                           removed
-0049 %
-0050 %   The purpose of this function is to remove reactions which enable
-0051 %   production/consumption of metabolites even when exchange reactions aren't used.
-0052 %   Many models, especially if they are automatically inferred from
-0053 %   databases, will have unbalanced reactions which allow for
-0054 %   net-production/consumption of metabolites without any consumption/excretion.
-0055 %   A common reason for this is when general compounds have different meaning
-0056 %   in different reactions (as DNA has in these two reactions).
-0057 %       dATP + dGTP + dCTP + dTTP <=> DNA + 4 PPi
-0058 %       0.25 dATP + 0.25 dGTP + 0.25 dCTP + 0.25 dTTP <=> DNA + PPi
-0059 %   Reactions that are problematic like this are always elementally
-0060 %   unbalanced, but it is not always that you would like to exclude all
-0061 %   unbalanced reactions from your model.
-0062 %   This function tries to remove as few problematic reactions as possible
-0063 %   so that the model cannot produce/consume anything from nothing. This is done by
-0064 %   repeatedly calling makeSomething/consumeSomething, checking if any of
-0065 %   the involved reactions are elementally unbalanced, remove one of them,
-0066 %   and then iterating until no metabolites can be produced/consumed.
-0067 %   makeSomething is called before consumeSomething.
-0068 %
-0069 % Usage: [newModel, removedRxns]=removeBadRxns(model,rxnRules,...
-0070 %       ignoreMets,isNames,refModel,ignoreIntBounds,printReport)
-0071 
-0072 if nargin<2
-0073     rxnRules=1;
-0074 end
-0075 if nargin<3
-0076     ignoreMets=[];
-0077 elseif ~islogical(ignoreMets) && ~isnumeric(ignoreMets)
-0078     ignoreMets=convertCharArray(ignoreMets);
-0079 end
-0080 if nargin<4
-0081     isNames=false;
-0082 end
-0083 if nargin<5
-0084     balanceElements={'C';'P';'S';'N';'O'};
-0085 else
-0086     balanceElements=convertCharArray(balanceElements);
-0087 end
-0088 if nargin<6
-0089     refModel=[];
-0090 else
-0091     if ~isempty(refModel)
-0092         EM='The feature to supply a reference model is currently not supported';
-0093         dispEM(EM,false);
-0094     end
-0095 end
-0096 if nargin<7
-0097     ignoreIntBounds=false;
-0098 end
-0099 if nargin<8
-0100     printReport=false;
-0101 end
-0102 
-0103 %Check if the model has open exchange reactions and print a warning in that
-0104 %case
-0105 if ~isfield(model,'unconstrained')
-0106     [~, I]=getExchangeRxns(model);
-0107     if any(I)
-0108         if any(model.lb(I)~=0) || any(model.ub(I)~=0)
-0109             EM='The model contains open exchange reactions. This is not the intended use of this function. Consider importing your model using importModel(filename,false)';
-0110             dispEM(EM,false);
-0111         end
-0112     end
-0113 end
-0114 
-0115 %Check that the model is feasible
-0116 sol=solveLP(model);
-0117 if isempty(sol.f)
-0118     EM='The model is not feasible. Consider removing lower bounds (such as ATP maintenance)';
-0119     dispEM(EM);
-0120 end
-0121 
-0122 %Check that the reference model is feasible
-0123 if any(refModel)
-0124     sol=solveLP(refModel);
-0125     if isempty(sol.f)
-0126         EM='The reference model is not feasible';
-0127         dispEM(EM);
-0128     end
-0129 end
-0130 
-0131 %Initialize some stuff
-0132 removedRxns={};
-0133 balanceStructure=getElementalBalance(model);
-0134 
-0135 %Check which elements to balance for
-0136 if ~isempty(setdiff(balanceElements,balanceStructure.elements.abbrevs))
-0137     EM='Could not recognize all elements to balance for';
-0138     dispEM(EM);
-0139 end
-0140 bal=ismember(balanceStructure.elements.abbrevs,balanceElements);
-0141 
-0142 %Main loop. First run for makeSomething, second for consumeSomething
-0143 warned=false(2,1); %This is to prevent the same warning being printed multiple times if rxnRules==3
-0144 for i=1:2
-0145     while 1
-0146         %Make some metabolite using as few reactions as possible
-0147         if i==1
-0148             [solution, metabolite]=makeSomething(model,ignoreMets,isNames,false,true,[],ignoreIntBounds);
-0149             if ~isempty(solution)
-0150                 if printReport
-0151                     fprintf(['Can make: ' model.metNames{metabolite(1)} '\n']);
-0152                 end
-0153             else
-0154                 %If no solution could be found, then finish
-0155                 break;
-0156             end
-0157         else
-0158             [solution, metabolite]=consumeSomething(model,ignoreMets,isNames,false,[],ignoreIntBounds);
-0159             if ~isempty(solution)
-0160                 if printReport
-0161                     fprintf(['Can consume: ' model.metNames{metabolite(1)} '\n']);
-0162                 end
-0163             else
-0164                 %If no solution could be found, then finish
-0165                 break;
-0166             end
-0167         end
-0168         
-0169         %Find all reactions that are unbalanced and still carry flux
-0170         I=find(abs(solution)>10^-8 & balanceStructure.balanceStatus>=0 & ~all(balanceStructure.leftComp(:,bal)==balanceStructure.rightComp(:,bal),2));
-0171         
-0172         %If there are unbalanced rxns then delete one of them and iterate
-0173         if any(I)
-0174             rxnToRemove=I(randperm(numel(I),1));
-0175         else
-0176             %If there are no unbalanced rxns in the solution
-0177             if rxnRules==1
-0178                 if i==1
-0179                     EM=['No unbalanced reactions were found in the solution, but the model can still make "' model.metNames{metabolite} '". Aborting search. Consider setting rxnRules to 2 or 3 for a more exhaustive search'];
-0180                     dispEM(EM,false);
-0181                 else
-0182                     EM=['No unbalanced reactions were found in the solution, but the model can still consume "' model.metNames{metabolite} '". Aborting search. Consider setting rxnRules to 2 or 3 for a more exhaustive search'];
-0183                     dispEM(EM,false);
-0184                 end
-0185                 break;
-0186             else
-0187                 %Find reactions which are not checked for mass balancing,
-0188                 %but that still carry flux
-0189                 I=find(abs(solution)>10^-8 & balanceStructure.balanceStatus<0);
-0190                 
-0191                 %If there are any such reactions, remove one of them and
-0192                 %iterate
-0193                 if any(I)
-0194                     rxnToRemove=I(randperm(numel(I),1));
-0195                 else
-0196                     if rxnRules==2
-0197                         %This happens when all reactions used are balanced
-0198                         %according to the metabolite formulas. This cannot
-0199                         %be, and indicates that one or more of the formulas
-0200                         %are wrong. Print a warning and delete any reaction
-0201                         %with flux
-0202                         if i==1
-0203                             EM=['No unbalanced or unparsable reactions were found in the solution, but the model can still make "' model.metNames{metabolite} '". Aborting search. Consider setting rxnRules to 3 for a more exhaustive search'];
-0204                             dispEM(EM,false);
-0205                         else
-0206                             EM=['No unbalanced or unparsable reactions were found in the solution, but the model can still consume "' model.metNames{metabolite} '". Aborting search. Consider setting rxnRules to 3 for a more exhaustive search'];
-0207                             dispEM(EM,false);
-0208                         end
-0209                         break;
-0210                     else
-0211                         if i==1
-0212                             if warned(1)==false
-0213                                 EM=['No unbalanced or unparsable reactions were found in the solution, but the model can still make "' model.metNames{metabolite} '". This indicates some error in the metabolite formulas. Removing random reactions in the solution'];
-0214                                 dispEM(EM,false);
-0215                                 warned(1)=true;
-0216                             end
-0217                         else
-0218                             if warned(2)==false
-0219                                 EM=['No unbalanced or unparsable reactions were found in the solution, but the model can still consume "' model.metNames{metabolite} '". This indicates some error in the metabolite formulas. Removing random reactions in the solution'];
-0220                                 dispEM(EM,false);
-0221                                 warned(2)=true;
-0222                             end
-0223                         end
-0224                         I=find(abs(solution)>10^-8);
-0225                         rxnToRemove=I(randperm(numel(I),1));
-0226                     end
-0227                 end
-0228             end
-0229         end
-0230         removedRxns=[removedRxns;model.rxns(rxnToRemove)];
-0231         if printReport
-0232             fprintf(['\tRemoved: '  model.rxns{rxnToRemove} '\n']);
-0233         end
-0234         model=removeReactions(model,rxnToRemove);
-0235         balanceStructure.balanceStatus(rxnToRemove)=[];
-0236         balanceStructure.leftComp(rxnToRemove,:)=[];
-0237         balanceStructure.rightComp(rxnToRemove,:)=[];
-0238     end
-0239 end
-0240 
-0241 newModel=model;
-0242 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/removeGenes.html b/doc/core/removeGenes.html deleted file mode 100644 index 387120255..000000000 --- a/doc/core/removeGenes.html +++ /dev/null @@ -1,194 +0,0 @@ - - - - Description of removeGenes - - - - - - - - - -
Home > core > removeGenes.m
- - - -

removeGenes -

- -

PURPOSE ^

-
removeGenes
- -

SYNOPSIS ^

-
function reducedModel = removeGenes(model,genesToRemove,removeUnusedMets,removeBlockedRxns,standardizeRules)
- -

DESCRIPTION ^

-
 removeGenes
-   Deletes a set of genes from a model
-
-   model                   a model structure
-   genesToRemove           either a cell array of gene IDs, a logical vector
-                           with the same number of elements as genes in the model,
-                           or a vector of indexes to remove
-   removeUnusedMets        remove metabolites that are no longer in use (optional, default
-                           false)
-   removeBlockedRxns       remove reactions that get blocked after deleting the genes
-                           (optional, default false)
-   standardizeRules        format gene rules to be compliant with standard format
-                           (optional, default true)
-
-   reducedModel            an updated model structure
-
- Usage: reducedModel = removeGenes(model,genesToRemove,removeUnusedMets,removeBlockedRxns)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 function reducedModel = removeGenes(model,genesToRemove,removeUnusedMets,removeBlockedRxns,standardizeRules)
-0002 % removeGenes
-0003 %   Deletes a set of genes from a model
-0004 %
-0005 %   model                   a model structure
-0006 %   genesToRemove           either a cell array of gene IDs, a logical vector
-0007 %                           with the same number of elements as genes in the model,
-0008 %                           or a vector of indexes to remove
-0009 %   removeUnusedMets        remove metabolites that are no longer in use (optional, default
-0010 %                           false)
-0011 %   removeBlockedRxns       remove reactions that get blocked after deleting the genes
-0012 %                           (optional, default false)
-0013 %   standardizeRules        format gene rules to be compliant with standard format
-0014 %                           (optional, default true)
-0015 %
-0016 %   reducedModel            an updated model structure
-0017 %
-0018 % Usage: reducedModel = removeGenes(model,genesToRemove,removeUnusedMets,removeBlockedRxns)
-0019 
-0020 if nargin<3
-0021     removeUnusedMets = false;
-0022 end
-0023 if nargin<4
-0024     removeBlockedRxns = false;
-0025 end
-0026 if nargin<5
-0027     standardizeRules = true;
-0028 end
-0029 %Format grRules and rxnGeneMatrix:
-0030 if standardizeRules
-0031     [grRules,rxnGeneMat,toCheck] = standardizeGrRules(model,true);
-0032     model.grRules    = grRules;
-0033     model.rxnGeneMat = rxnGeneMat;
-0034 else
-0035     toCheck    = [];
-0036     rxnGeneMat = model.rxnGeneMat;
-0037 end
-0038 reducedModel = model;
-0039 %Only remove genes that are actually in the model
-0040 if ~(islogical(genesToRemove) || isnumeric(genesToRemove))
-0041     genesToRemove=convertCharArray(genesToRemove);
-0042     genesToRemove=genesToRemove(ismember(genesToRemove,model.genes));
-0043 end
-0044 if ~isempty(genesToRemove)
-0045     indexesToRemove = getIndexes(model,genesToRemove,'genes');
-0046     if ~isempty(indexesToRemove)
-0047         %Make 0 corresponding columns from rxnGeneMat:
-0048         reducedModel.rxnGeneMat(:,indexesToRemove) = 0;        
-0049         genes = model.genes(indexesToRemove);
-0050         %Check if conflicting grRules contain any of the genes to remove
-0051         if ~isempty(toCheck)
-0052             for i=1:numel(toCheck)
-0053                 index   = toCheck(i);
-0054                 gIdxs   = find(rxnGeneMat(index,:));
-0055                 g2check = model.genes(gIdxs);
-0056                 if any(ismember(g2check,genes))
-0057                     warning(['Conflicting grRule #' num2str(index) ' (' model.rxns{index} ') contains at least one of the genes to be removed, this grRule will be bypassed in order to avoid logical errors'])
-0058                 end
-0059             end
-0060         end
-0061         canCarryFlux = true(size(model.rxns));       
-0062         %Loop through genes and adapt rxns:
-0063         for i = 1:length(genes)
-0064             %Find all reactions for this gene and loop through them:
-0065             geneRxns = find(rxnGeneMat(:,indexesToRemove(i)));
-0066             if ~isempty(geneRxns)
-0067                 for j = 1:numel(geneRxns)
-0068                     index  = geneRxns(j);
-0069                     grRule = reducedModel.grRules{index};
-0070                     ruleGenes = reducedModel.genes(logical(rxnGeneMat(index,:)));
-0071                     if ~ismember(index,toCheck) && canCarryFlux(index) && ~isempty(grRule)
-0072                         %Check if rxn can carry flux without this gene:
-0073                         canCarryFlux(index) = canRxnCarryFlux(ruleGenes,grRule,genes{i});
-0074                         %Adapt gene rule & gene matrix:
-0075                         grRule = removeGeneFromRule(grRule,genes{i});
-0076                         reducedModel.grRules{index} = grRule;
-0077                     end
-0078                 end
-0079             end
-0080         end
-0081         %Delete or block the reactions that cannot carry flux:
-0082         if removeBlockedRxns
-0083             rxnsToRemove = reducedModel.rxns(~canCarryFlux);
-0084             reducedModel = removeReactions(reducedModel,rxnsToRemove,removeUnusedMets,true);
-0085         else
-0086             reducedModel = removeReactions(reducedModel,[],removeUnusedMets,true);
-0087             reducedModel.lb(~canCarryFlux) = 0;
-0088             reducedModel.ub(~canCarryFlux) = 0;
-0089         end
-0090     end
-0091 end
-0092 %Format grRules and rxnGeneMatrix after all modifications
-0093 if standardizeRules
-0094     [grRules,rxnGeneMat] = standardizeGrRules(reducedModel,true);
-0095     reducedModel.grRules = grRules;
-0096     reducedModel.rxnGeneMat = rxnGeneMat;
-0097 end
-0098 end
-0099 
-0100 function canIt = canRxnCarryFlux(ruleGenes,geneRule,geneToRemove)
-0101 %This function converts a gene rule to a logical statement, and then
-0102 %asseses if the rule is true (i.e. rxn can still carry flux) or not (cannot
-0103 %carry flux).
-0104 geneRule = [' ', geneRule, ' '];
-0105 for i = 1:length(ruleGenes)
-0106     if strcmp(ruleGenes{i},geneToRemove)
-0107         geneRule = strrep(geneRule,[' ' ruleGenes{i} ' '],' false ');
-0108         geneRule = strrep(geneRule,['(' ruleGenes{i} ' '],'(false ');
-0109         geneRule = strrep(geneRule,[' ' ruleGenes{i} ')'],' false)');
-0110     else
-0111         geneRule = strrep(geneRule,[' ' ruleGenes{i} ' '],' true ');
-0112         geneRule = strrep(geneRule,['(' ruleGenes{i} ' '],'(true ');
-0113         geneRule = strrep(geneRule,[' ' ruleGenes{i} ')'],' true)');
-0114     end
-0115 end
-0116 geneRule = strtrim(geneRule);
-0117 geneRule = strrep(geneRule,'and','&&');
-0118 geneRule = strrep(geneRule,'or','||');
-0119 canIt    = eval(geneRule);
-0120 end
-0121 
-0122 function geneRule = removeGeneFromRule(geneRule,geneToRemove)
-0123 %This function receives a standard gene rule and it returns it without the
-0124 %chosen gene.
-0125 geneSets = strsplit(geneRule,' or ');
-0126 hasGene  = ~cellfun(@isempty,strfind(geneSets,geneToRemove));
-0127 geneSets = geneSets(~hasGene);
-0128 geneRule = strjoin(geneSets,' or ');
-0129 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/removeMets.html b/doc/core/removeMets.html deleted file mode 100644 index 4a3d2d269..000000000 --- a/doc/core/removeMets.html +++ /dev/null @@ -1,198 +0,0 @@ - - - - Description of removeMets - - - - - - - - - -
Home > core > removeMets.m
- - - -

removeMets -

- -

PURPOSE ^

-
removeMets
- -

SYNOPSIS ^

-
function reducedModel=removeMets(model,metsToRemove,isNames,removeUnusedRxns,removeUnusedGenes,removeUnusedComps)
- -

DESCRIPTION ^

-
 removeMets
-   Deletes a set of metabolites from a model
-
-   model             a model structure
-   metsToRemove      either a cell array of metabolite IDs, a logical vector
-                     with the same number of elements as metabolites in the model,
-                     of a vector of indexes to remove
-   isNames           true if the supplied mets represent metabolite names
-                     (as opposed to IDs). This is a way to delete
-                     metabolites in several compartments at once without
-                     knowing the exact IDs. This only works if metsToRemove
-                     is a cell array (optional, default false)
-   removeUnusedRxns  remove reactions that are no longer in use (optional,
-                     default false)
-   removeUnusedGenes remove genes that are no longer in use (optional,
-                     default false)
-   removeUnusedComps remove compartments that are no longer in use (optional,
-                     default false)
-
-   reducedModel      an updated model structure
-
- Usage: reducedModel=removeMets(model,metsToRemove,isNames,...
-           removeUnusedRxns,removeUnusedGenes,removeUnusedComps)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function reducedModel=removeMets(model,metsToRemove,isNames,removeUnusedRxns,removeUnusedGenes,removeUnusedComps)
-0002 % removeMets
-0003 %   Deletes a set of metabolites from a model
-0004 %
-0005 %   model             a model structure
-0006 %   metsToRemove      either a cell array of metabolite IDs, a logical vector
-0007 %                     with the same number of elements as metabolites in the model,
-0008 %                     of a vector of indexes to remove
-0009 %   isNames           true if the supplied mets represent metabolite names
-0010 %                     (as opposed to IDs). This is a way to delete
-0011 %                     metabolites in several compartments at once without
-0012 %                     knowing the exact IDs. This only works if metsToRemove
-0013 %                     is a cell array (optional, default false)
-0014 %   removeUnusedRxns  remove reactions that are no longer in use (optional,
-0015 %                     default false)
-0016 %   removeUnusedGenes remove genes that are no longer in use (optional,
-0017 %                     default false)
-0018 %   removeUnusedComps remove compartments that are no longer in use (optional,
-0019 %                     default false)
-0020 %
-0021 %   reducedModel      an updated model structure
-0022 %
-0023 % Usage: reducedModel=removeMets(model,metsToRemove,isNames,...
-0024 %           removeUnusedRxns,removeUnusedGenes,removeUnusedComps)
-0025 if ~islogical(metsToRemove) && ~isnumeric(metsToRemove)
-0026     metsToRemove=convertCharArray(metsToRemove);
-0027 end
-0028 
-0029 if nargin<3
-0030     isNames=false;
-0031 end
-0032 
-0033 if nargin<4
-0034     removeUnusedRxns=false;
-0035 end
-0036 
-0037 if nargin<5
-0038     removeUnusedGenes=false;
-0039 end
-0040 
-0041 if nargin<6
-0042     removeUnusedComps=false;
-0043 end
-0044 
-0045 %Check that metsToRemove is a cell array
-0046 if isNames==true && ~iscell(metsToRemove)
-0047     error('Must supply a cell array of strings if isNames=true');
-0048 end
-0049 
-0050 reducedModel=model;
-0051 
-0052 if isNames==false
-0053     indexesToDelete=getIndexes(model,metsToRemove,'mets');
-0054 else
-0055     indexesToDelete=[];
-0056     for i=1:numel(metsToRemove)
-0057         indexesToDelete=[indexesToDelete;find(strcmp(metsToRemove(i),model.metNames))];
-0058     end
-0059 end
-0060 
-0061 %Remove metabolites
-0062 if ~isempty(indexesToDelete)
-0063     reducedModel.mets(indexesToDelete)=[];
-0064     reducedModel.S(indexesToDelete,:)=[];
-0065     if isfield(reducedModel,'b')
-0066         reducedModel.b(indexesToDelete,:)=[];
-0067     end
-0068     if isfield(reducedModel,'metNames')
-0069         reducedModel.metNames(indexesToDelete)=[];
-0070     end
-0071     if isfield(reducedModel,'metComps')
-0072         reducedModel.metComps(indexesToDelete)=[];
-0073     end
-0074     if isfield(reducedModel,'inchis')
-0075         reducedModel.inchis(indexesToDelete)=[];
-0076     end
-0077     if isfield(reducedModel,'metSmiles')
-0078         reducedModel.metSmiles(indexesToDelete)=[];
-0079     end
-0080     if isfield(reducedModel,'metFormulas')
-0081         reducedModel.metFormulas(indexesToDelete)=[];
-0082     end
-0083     if isfield(reducedModel,'metMiriams')
-0084         reducedModel.metMiriams(indexesToDelete)=[];
-0085     end
-0086     if isfield(reducedModel,'unconstrained')
-0087         reducedModel.unconstrained(indexesToDelete)=[];
-0088     end
-0089     if isfield(reducedModel,'metFrom')
-0090         reducedModel.metFrom(indexesToDelete)=[];
-0091     end
-0092     if isfield(reducedModel,'metCharges')
-0093         reducedModel.metCharges(indexesToDelete)=[];
-0094     end
-0095     if isfield(reducedModel,'metDeltaG')
-0096         reducedModel.metDeltaG(indexesToDelete)=[];
-0097     end
-0098     if isfield(reducedModel,'metNotes')
-0099         reducedModel.metNotes(indexesToDelete)=[];
-0100     end    
-0101 end
-0102 
-0103 %Remove unused reactions
-0104 if removeUnusedRxns==true
-0105     %Get unused reactions
-0106     [~, a]=find(reducedModel.S);
-0107     rxnsToRemove=1:numel(reducedModel.rxns);
-0108     rxnsToRemove(a)=[];
-0109     reducedModel=removeReactions(reducedModel,rxnsToRemove,false,removeUnusedGenes);
-0110 end
-0111 
-0112 %Remove unused compartments
-0113 if removeUnusedComps==true
-0114     oldComps=reducedModel.comps;
-0115     I=ismember(1:numel(oldComps),reducedModel.metComps);
-0116     if ~all(I)
-0117         reducedModel.comps(~I)=[];
-0118         reducedModel.compNames(~I)=[];
-0119         if isfield(reducedModel,'compOutside')
-0120             reducedModel.compOutside(~I)=[];
-0121         end
-0122         if isfield(reducedModel,'compMiriams')
-0123             reducedModel.compMiriams(~I)=[];
-0124         end
-0125         [~, J]=ismember(oldComps(reducedModel.metComps),reducedModel.comps);
-0126         reducedModel.metComps=J;
-0127     end
-0128 end
-0129 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/removeReactions.html b/doc/core/removeReactions.html deleted file mode 100644 index 0f658fe0e..000000000 --- a/doc/core/removeReactions.html +++ /dev/null @@ -1,218 +0,0 @@ - - - - Description of removeReactions - - - - - - - - - -
Home > core > removeReactions.m
- - - -

removeReactions -

- -

PURPOSE ^

-
removeReactions
- -

SYNOPSIS ^

-
function reducedModel=removeReactions(model,rxnsToRemove,removeUnusedMets,removeUnusedGenes,removeUnusedComps)
- -

DESCRIPTION ^

-
 removeReactions
-   Deletes a set of reactions from a model
-
- Input:
-   model             a model structure
-   rxnsToRemove      either a cell array of reaction IDs, a logical vector
-                     with the same number of elements as reactions in the
-                     model, or a vector of indexes to remove
-   removeUnusedMets  remove metabolites that are no longer in use
-                     (optional, default false)
-   removeUnusedGenes remove genes that are no longer in use (optional,
-                     default false)
-   removeUnusedComps remove compartments that are no longer in use
-                     (optional, default false)
-
- Output:
-   reducedModel      an updated model structure
-
- Usage: reducedModel = removeReactions(model, rxnsToRemove, removeUnusedMets,...
-                           removeUnusedGenes, removeUnusedComps)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function reducedModel=removeReactions(model,rxnsToRemove,removeUnusedMets,removeUnusedGenes,removeUnusedComps)
-0002 % removeReactions
-0003 %   Deletes a set of reactions from a model
-0004 %
-0005 % Input:
-0006 %   model             a model structure
-0007 %   rxnsToRemove      either a cell array of reaction IDs, a logical vector
-0008 %                     with the same number of elements as reactions in the
-0009 %                     model, or a vector of indexes to remove
-0010 %   removeUnusedMets  remove metabolites that are no longer in use
-0011 %                     (optional, default false)
-0012 %   removeUnusedGenes remove genes that are no longer in use (optional,
-0013 %                     default false)
-0014 %   removeUnusedComps remove compartments that are no longer in use
-0015 %                     (optional, default false)
-0016 %
-0017 % Output:
-0018 %   reducedModel      an updated model structure
-0019 %
-0020 % Usage: reducedModel = removeReactions(model, rxnsToRemove, removeUnusedMets,...
-0021 %                           removeUnusedGenes, removeUnusedComps)
-0022 
-0023 if nargin<3
-0024     removeUnusedMets=false;
-0025 end
-0026 if nargin<4
-0027     removeUnusedGenes=false;
-0028 end
-0029 if nargin<5
-0030     removeUnusedComps=false;
-0031 end
-0032 if ~islogical(rxnsToRemove) && ~isnumeric(rxnsToRemove)
-0033     rxnsToRemove=convertCharArray(rxnsToRemove);
-0034 end
-0035 
-0036 reducedModel=model;
-0037 
-0038 if ~isempty(rxnsToRemove) || removeUnusedMets || removeUnusedGenes
-0039     indexesToDelete=getIndexes(model,rxnsToRemove,'rxns');
-0040     
-0041     %Remove reactions
-0042     if ~isempty(indexesToDelete)
-0043         reducedModel.rxns(indexesToDelete)=[];
-0044         if isfield(reducedModel,'lb')
-0045             reducedModel.lb(indexesToDelete)=[];
-0046         end
-0047         if isfield(reducedModel,'ub')
-0048             reducedModel.ub(indexesToDelete)=[];
-0049         end
-0050         if isfield(reducedModel,'rev')
-0051             reducedModel.rev(indexesToDelete)=[];
-0052         end
-0053         if isfield(reducedModel,'c')
-0054             reducedModel.c(indexesToDelete)=[];
-0055         end
-0056         if isfield(reducedModel,'S')
-0057             reducedModel.S(:,indexesToDelete)=[];
-0058         end
-0059         if isfield(reducedModel,'rxnNames')
-0060             reducedModel.rxnNames(indexesToDelete)=[];
-0061         end
-0062         if isfield(reducedModel,'rxnGeneMat')
-0063             reducedModel.rxnGeneMat(indexesToDelete,:)=[];
-0064         end
-0065         if isfield(reducedModel,'grRules')
-0066             reducedModel.grRules(indexesToDelete,:)=[];
-0067         end
-0068         if isfield(reducedModel,'subSystems')
-0069             reducedModel.subSystems(indexesToDelete,:)=[];
-0070         end
-0071         if isfield(reducedModel,'eccodes')
-0072             reducedModel.eccodes(indexesToDelete,:)=[];
-0073         end
-0074         if isfield(reducedModel,'equations')
-0075             reducedModel.equations(indexesToDelete,:)=[];
-0076         end
-0077         if isfield(reducedModel,'rxnMiriams')
-0078             reducedModel.rxnMiriams(indexesToDelete,:)=[];
-0079         end
-0080         if isfield(reducedModel,'rxnComps')
-0081             reducedModel.rxnComps(indexesToDelete,:)=[];
-0082         end
-0083         if isfield(reducedModel,'rxnFrom')
-0084             reducedModel.rxnFrom(indexesToDelete,:)=[];
-0085         end
-0086         if isfield(reducedModel,'rxnScores')
-0087             reducedModel.rxnScores(indexesToDelete,:)=[];
-0088         end
-0089         if isfield(reducedModel,'rxnNotes')
-0090             reducedModel.rxnNotes(indexesToDelete,:)=[];
-0091         end
-0092         if isfield(reducedModel,'rxnReferences')
-0093             reducedModel.rxnReferences(indexesToDelete,:)=[];
-0094         end
-0095         if isfield(reducedModel,'rxnConfidenceScores')
-0096             reducedModel.rxnConfidenceScores(indexesToDelete,:)=[];
-0097         end
-0098         if isfield(reducedModel,'rxnDeltaG')
-0099             reducedModel.rxnDeltaG(indexesToDelete,:)=[];
-0100         end
-0101         if isfield(reducedModel,'pwys')
-0102             reducedModel.pwys(indexesToDelete,:)=[];
-0103         end
-0104         if isfield(reducedModel,'spontaneous')
-0105             reducedModel.spontaneous(indexesToDelete)=[];
-0106         end
-0107     end
-0108     
-0109     %Remove unused metabolites
-0110     if removeUnusedMets==true
-0111         if isfield(reducedModel,'S')
-0112             [usedMets, ~]=find(reducedModel.S);
-0113             unUsedMets=true(numel(reducedModel.mets),1);
-0114             unUsedMets(usedMets)=false;
-0115             reducedModel=removeMets(reducedModel,unUsedMets,false,false,false,removeUnusedComps);
-0116         end
-0117     end
-0118     
-0119     %Remove unused genes
-0120     if removeUnusedGenes==true && isfield(reducedModel,'rxnGeneMat')
-0121         %Find all genes that are not used
-0122         [~, b]=find(reducedModel.rxnGeneMat);
-0123         toKeep=false(numel(reducedModel.genes),1);
-0124         toKeep(b)=true;
-0125         
-0126         reducedModel.genes=reducedModel.genes(toKeep);
-0127         reducedModel.rxnGeneMat=reducedModel.rxnGeneMat(:,toKeep);
-0128         
-0129         if isfield(reducedModel,'geneShortNames')
-0130             reducedModel.geneShortNames=reducedModel.geneShortNames(toKeep);
-0131         end
-0132 
-0133         if isfield(reducedModel,'proteins')
-0134             reducedModel.proteins=reducedModel.proteins(toKeep);
-0135         end
-0136         
-0137         if isfield(reducedModel,'geneMiriams')
-0138             reducedModel.geneMiriams=reducedModel.geneMiriams(toKeep);
-0139         end
-0140         
-0141         if isfield(reducedModel,'geneFrom')
-0142             reducedModel.geneFrom=reducedModel.geneFrom(toKeep);
-0143         end
-0144         
-0145         if isfield(reducedModel,'geneComps')
-0146             reducedModel.geneComps=reducedModel.geneComps(toKeep);
-0147         end
-0148     end
-0149 else
-0150     reducedModel=model;
-0151 end
-0152 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/replaceMets.html b/doc/core/replaceMets.html deleted file mode 100644 index 6f4319513..000000000 --- a/doc/core/replaceMets.html +++ /dev/null @@ -1,226 +0,0 @@ - - - - Description of replaceMets - - - - - - - - - -
Home > core > replaceMets.m
- - - -

replaceMets -

- -

PURPOSE ^

-
replaceMets
- -

SYNOPSIS ^

-
function [model, removedRxns, idxDuplRxns]=replaceMets(model,metabolite,replacement,verbose,identifiers)
- -

DESCRIPTION ^

-
 replaceMets
-   Replaces metabolite names and annotation with replacement metabolite
-   that is already in the model. If this results in duplicate metabolites,
-   the replacement metabolite will be kept, while the S matrix is updated
-   to use the replacement metabolite instead. At the end, contractModel is
-   run to remove any duplicate reactions that might have occured.
-
- Input:
-   model           a model structure
-   metabolite      string with name of metabolite to be replace
-   replacement     string with name of replacement metabolite
-   verbose         logical whether to print the ids of reactions that
-                   involve the replaced metabolite (optional, default
-                   false)
-   identifiers     true if 'metabolite' and 'replacement' refer to
-                   metabolite identifiers instead of metabolite names
-                   (optional, default false)
- 
- Output:
-   model           model structure with selected metabolites replaced
-   removedRxns     identifiers of duplicate reactions that were removed
-   idxDuplRxns     index of removedRxns in original model
-
- Note: This function is useful when the model contains both 'oxygen' and
- 'o2' as metabolite names. If 'oxygen' and 'o2' are identifiers instead,
- then the 'identifiers' flag should be set to true.
-
- Usage: [model, removedRxns, idxDuplRxns] = replaceMets(model, metabolite, replacement, verbose)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function [model, removedRxns, idxDuplRxns]=replaceMets(model,metabolite,replacement,verbose,identifiers)
-0002 % replaceMets
-0003 %   Replaces metabolite names and annotation with replacement metabolite
-0004 %   that is already in the model. If this results in duplicate metabolites,
-0005 %   the replacement metabolite will be kept, while the S matrix is updated
-0006 %   to use the replacement metabolite instead. At the end, contractModel is
-0007 %   run to remove any duplicate reactions that might have occured.
-0008 %
-0009 % Input:
-0010 %   model           a model structure
-0011 %   metabolite      string with name of metabolite to be replace
-0012 %   replacement     string with name of replacement metabolite
-0013 %   verbose         logical whether to print the ids of reactions that
-0014 %                   involve the replaced metabolite (optional, default
-0015 %                   false)
-0016 %   identifiers     true if 'metabolite' and 'replacement' refer to
-0017 %                   metabolite identifiers instead of metabolite names
-0018 %                   (optional, default false)
-0019 %
-0020 % Output:
-0021 %   model           model structure with selected metabolites replaced
-0022 %   removedRxns     identifiers of duplicate reactions that were removed
-0023 %   idxDuplRxns     index of removedRxns in original model
-0024 %
-0025 % Note: This function is useful when the model contains both 'oxygen' and
-0026 % 'o2' as metabolite names. If 'oxygen' and 'o2' are identifiers instead,
-0027 % then the 'identifiers' flag should be set to true.
-0028 %
-0029 % Usage: [model, removedRxns, idxDuplRxns] = replaceMets(model, metabolite, replacement, verbose)
-0030 
-0031 metabolite=char(metabolite);
-0032 replacement=char(replacement);
-0033 
-0034 if nargin<4 || isempty(verbose)
-0035     verbose=false;
-0036 end
-0037 if nargin<5
-0038     identifiers = false;
-0039 end
-0040 
-0041 % Find occurence of replacement metabolites. Annotation will be taken from
-0042 % first metabolite found.
-0043 if identifiers
-0044     repIdx = find(strcmp(replacement,model.mets));
-0045 else
-0046     repIdx = find(strcmp(replacement,model.metNames));
-0047 end
-0048 if isempty(repIdx)
-0049     error('The replacement metabolite cannot be found in the model.');
-0050 end
-0051 
-0052 % Change name and information from metabolite to replacement metabolite
-0053 if identifiers
-0054     metIdx = find(strcmp(metabolite,model.mets));
-0055 else
-0056     metIdx = find(strcmp(metabolite,model.metNames));
-0057 end
-0058 if isempty(metIdx)
-0059     error('The to-be-replaced metabolite cannot be found in the model.');
-0060 end
-0061 
-0062 rxnsWithMet = find(model.S(metIdx,:));
-0063 if verbose==true
-0064     fprintf('\n\nThe following reactions contain the to-be-replaced metabolite as reactant:\n')
-0065     fprintf(strjoin(model.rxns(rxnsWithMet),'\n'))
-0066     fprintf('\n')
-0067 end
-0068 
-0069 model.metNames(metIdx) = model.metNames(repIdx(1));
-0070 if isfield(model,'metFormulas')
-0071     model.metFormulas(metIdx) = model.metFormulas(repIdx(1));
-0072 end
-0073 if isfield(model,'metMiriams')
-0074     model.metMiriams(metIdx) = model.metMiriams(repIdx(1));
-0075 end
-0076 if isfield(model,'metCharges')
-0077     model.metCharges(metIdx) = model.metCharges(repIdx(1));
-0078 end
-0079 if isfield(model,'metDeltaG')
-0080     model.metDeltaG(metIdx) = model.metDeltaG(repIdx(1));
-0081 end
-0082 if isfield(model,'inchis')
-0083     model.inchis(metIdx) = model.inchis(repIdx(1));
-0084 end
-0085 if isfield(model,'metSmiles')
-0086     model.metSmiles(metIdx) = model.metSmiles(repIdx(1));
-0087 end
-0088 
-0089 idxDelete=[];
-0090 if identifiers
-0091     originalStoch = model.S(metIdx,rxnsWithMet);
-0092     model.S(repIdx,rxnsWithMet) = originalStoch;
-0093     model.S(metIdx,rxnsWithMet) = 0;
-0094     idxDelete = metIdx;
-0095 else
-0096     % Run through replacement metabolites and their compartments. If any of the
-0097     % to-be-replaced metabolites is already present (checked by
-0098     % metaboliteName[compartment], then the replacement metabolite is kept and
-0099     % the to-be-replace metabolite ID deleted.
-0100     
-0101     % Build list of metaboliteName[compartment]
-0102     metCompsN =cellstr(num2str(model.metComps));
-0103     map = containers.Map(cellstr(num2str(transpose(1:length(model.comps)))),model.comps);
-0104     metCompsN = map.values(metCompsN);
-0105     metCompsN = strcat(lower(model.metNames),'[',metCompsN,']');
-0106     
-0107     for i = 1:length(repIdx)
-0108         metCompsNidx=find(strcmp(metCompsN(repIdx(i)), metCompsN));
-0109         if length(metCompsNidx)>1
-0110             for j = 2:length(metCompsNidx)
-0111                 model.S(metCompsNidx(1),:) = model.S(metCompsNidx(1),:) + model.S(metCompsNidx(j),:);
-0112                 idxDelete=[idxDelete; metCompsNidx(j)]; % Make list of metabolite IDs to delete
-0113             end
-0114         end
-0115     end
-0116 end
-0117 
-0118 if ~isempty(idxDelete)
-0119     model.S(idxDelete,:) =[];
-0120     model.mets(idxDelete) = [];
-0121     model.metNames(idxDelete) = [];
-0122     model.metComps(idxDelete) = [];
-0123     model.b(idxDelete) = [];
-0124     if isfield(model,'metFormulas')
-0125         model.metFormulas(idxDelete) = [];
-0126     end
-0127     if isfield(model,'unconstrained')
-0128         model.unconstrained(idxDelete) = [];
-0129     end
-0130     if isfield(model,'metMiriams')
-0131         model.metMiriams(idxDelete) = [];
-0132     end
-0133     if isfield(model,'metCharges')
-0134         model.metCharges(idxDelete) = [];
-0135     end
-0136     if isfield(model,'metDeltaG')
-0137         model.metDeltaG(idxDelete) = [];
-0138     end
-0139     if isfield(model,'inchis')
-0140         model.inchis(idxDelete) = [];
-0141     end
-0142     if isfield(model,'metSmiles')
-0143         model.metSmiles(idxDelete) = [];
-0144     end
-0145     if isfield(model,'metFrom')
-0146         model.metFrom(idxDelete) = [];
-0147     end
-0148 end
-0149 
-0150 % This could now have created duplicate reactions. Contract model.
-0151 model=contractModel(model,[],repIdx);
-0152 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/reporterMetabolites.html b/doc/core/reporterMetabolites.html deleted file mode 100644 index d3c5d2309..000000000 --- a/doc/core/reporterMetabolites.html +++ /dev/null @@ -1,274 +0,0 @@ - - - - Description of reporterMetabolites - - - - - - - - - -
Home > core > reporterMetabolites.m
- - - -

reporterMetabolites -

- -

PURPOSE ^

-
reporterMetabolites
- -

SYNOPSIS ^

-
function repMets=reporterMetabolites(model,genes,genePValues,printResults,outputFile,geneFoldChanges)
- -

DESCRIPTION ^

-
 reporterMetabolites
-   The Reporter Metabolites algorithm for identifying metabolites around
-   which transcriptional changes occur
-
-   model           a model structure
-   genes           a cell array of gene names (should match with
-                   model.genes)
-   genePValues     P-values for differential expression of the genes
-   printResults    true if the top 20 Reporter Metabolites should be
-                   printed to the screen (optional, default false)
-   outputFile      the results are printed to this file (optional)
-   geneFoldChanges log-fold changes for the genes. If supplied, then
-                   Reporter Metabolites are calculated for only up/down-
-                   regulated genes in addition to the full test (optional)
-
-   repMets         an array of structures with the following fields.
-       test            a string the describes the genes that were used to
-                       calculate the Reporter Metabolites ('all', 'only up',
-                       or 'only down'). The two latter structures are
-                       only calculated if geneFoldChanges are supplied.
-       mets            a cell array of metabolite IDs for the metabolites for
-                       which a score could be calculated
-       metZScores      Z-scores for differential expression around each
-                       metabolite in "mets"
-       metPValues      P-values for differential expression around each
-                       metabolite in "mets"
-       metNGenes       number of neighbouring genes for each metabolite in
-                       "mets"
-       meanZ           average Z-scores for the genes around each metabolite
-                       in "mets"
-       stdZ            standard deviations of the Z-scores around each
-                       metabolite in "mets"
-
-   NOTE: For details about the algorithm, see Patil KR, Nielsen J,
-   Uncovering transcriptional regulation of metabolism by using metabolic
-   network topology. Proc. Natl Acad. Sci. USA 2005;102:2685-2689.
-
- Usage: repMets=reporterMetabolites(model,genes,genePValues,printResults,...
-           outputFile,geneFoldChanges)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function repMets=reporterMetabolites(model,genes,genePValues,printResults,outputFile,geneFoldChanges)
-0002 % reporterMetabolites
-0003 %   The Reporter Metabolites algorithm for identifying metabolites around
-0004 %   which transcriptional changes occur
-0005 %
-0006 %   model           a model structure
-0007 %   genes           a cell array of gene names (should match with
-0008 %                   model.genes)
-0009 %   genePValues     P-values for differential expression of the genes
-0010 %   printResults    true if the top 20 Reporter Metabolites should be
-0011 %                   printed to the screen (optional, default false)
-0012 %   outputFile      the results are printed to this file (optional)
-0013 %   geneFoldChanges log-fold changes for the genes. If supplied, then
-0014 %                   Reporter Metabolites are calculated for only up/down-
-0015 %                   regulated genes in addition to the full test (optional)
-0016 %
-0017 %   repMets         an array of structures with the following fields.
-0018 %       test            a string the describes the genes that were used to
-0019 %                       calculate the Reporter Metabolites ('all', 'only up',
-0020 %                       or 'only down'). The two latter structures are
-0021 %                       only calculated if geneFoldChanges are supplied.
-0022 %       mets            a cell array of metabolite IDs for the metabolites for
-0023 %                       which a score could be calculated
-0024 %       metZScores      Z-scores for differential expression around each
-0025 %                       metabolite in "mets"
-0026 %       metPValues      P-values for differential expression around each
-0027 %                       metabolite in "mets"
-0028 %       metNGenes       number of neighbouring genes for each metabolite in
-0029 %                       "mets"
-0030 %       meanZ           average Z-scores for the genes around each metabolite
-0031 %                       in "mets"
-0032 %       stdZ            standard deviations of the Z-scores around each
-0033 %                       metabolite in "mets"
-0034 %
-0035 %   NOTE: For details about the algorithm, see Patil KR, Nielsen J,
-0036 %   Uncovering transcriptional regulation of metabolism by using metabolic
-0037 %   network topology. Proc. Natl Acad. Sci. USA 2005;102:2685-2689.
-0038 %
-0039 % Usage: repMets=reporterMetabolites(model,genes,genePValues,printResults,...
-0040 %           outputFile,geneFoldChanges)
-0041 
-0042 genes=convertCharArray(genes);
-0043 if nargin<4
-0044     printResults=false;
-0045 end
-0046 if nargin<5
-0047     outputFile=[];
-0048 end
-0049 if nargin<6
-0050     geneFoldChanges=[];
-0051 end
-0052 
-0053 %Check some stuff
-0054 if numel(genes)~=numel(genePValues)
-0055     EM='The number of genes and the number of Z-scores must be the same';
-0056     dispEM(EM);
-0057 end
-0058 if ~isfield(model,'rxnGeneMat')
-0059     EM='The model structure must have a rxnGeneMat field';
-0060     dispEM(EM);
-0061 end
-0062 
-0063 %Remove the genes which are not in the model
-0064 genePValues(~ismember(genes,model.genes))=[];
-0065 if any(geneFoldChanges)
-0066     geneFoldChanges(~ismember(genes,model.genes))=[];
-0067 end
-0068 genes(~ismember(genes,model.genes))=[];
-0069 
-0070 %Remove the genes that has NA P-value
-0071 genes(isnan(genePValues))=[];
-0072 if any(geneFoldChanges)
-0073     geneFoldChanges(isnan(genePValues))=[];
-0074 end
-0075 genePValues(isnan(genePValues))=[];
-0076 
-0077 %Convert p-values to Z-scores
-0078 geneZScores=norminv(genePValues)*-1;
-0079 
-0080 %This is to prevent errors if the p-values are exactly 0 or 1
-0081 geneZScores(geneZScores==-inf)=-15;
-0082 geneZScores(geneZScores==inf)=15;
-0083 
-0084 %For each metabolite, calculate the aggregate Z-score and keep track of the
-0085 %number of neighbouring genes
-0086 metZScores=nan(numel(model.mets),1);
-0087 metNGenes=nan(numel(model.mets),1);
-0088 meanZ=nan(numel(model.mets),1);
-0089 stdZ=nan(numel(model.mets),1);
-0090 for i=1:numel(model.mets)
-0091     %Get the involved rxns
-0092     I=model.S(i,:);
-0093     
-0094     %Get the involved genes
-0095     [~, J]=find(model.rxnGeneMat(I~=0,:));
-0096     
-0097     %Find the genes in the gene list
-0098     K=find(ismember(genes,model.genes(J)));
-0099     
-0100     %Calculate the aggregated Z-score for the metabolite
-0101     if any(K)
-0102         metZScores(i)=sum(geneZScores(K))/sqrt(numel(K));
-0103         meanZ(i)=mean(geneZScores(K));
-0104         stdZ(i)=std(geneZScores(K));
-0105         metNGenes(i)=numel(K);
-0106     end
-0107 end
-0108 
-0109 %Remove the metabolites which have no Z-scores
-0110 mets=model.mets(~isnan(metZScores));
-0111 metNames=model.metNames(~isnan(metZScores));
-0112 metZScores(isnan(metZScores))=[];
-0113 metNGenes(isnan(metNGenes))=[];
-0114 meanZ(isnan(meanZ))=[];
-0115 stdZ(isnan(stdZ))=[];
-0116 
-0117 %Then correct for background by calculating the mean Z-score for random
-0118 %sets of the same size as the ones that were found for the metabolites
-0119 sizes=unique(metNGenes);
-0120 nGenes=numel(genes);
-0121 
-0122 for i=1:numel(sizes)
-0123     %Sample 100000 sets for each size. Sample with replacement, which may
-0124     %or may not be the best choice.
-0125     I=ceil(rand(100000,sizes(i))*nGenes);
-0126     J=geneZScores(I);
-0127     K=sum(J,2)/sqrt(sizes(i));
-0128     
-0129     %Correct all elements of this size
-0130     mK=mean(K);
-0131     stdK=std(K);
-0132     metZScores(metNGenes==sizes(i))=(metZScores(metNGenes==sizes(i))-mK)/stdK;
-0133 end
-0134 
-0135 %Calculate the P-values
-0136 metPValues=1-normcdf(metZScores);
-0137 
-0138 %Sort the results
-0139 [metZScores, I]=sort(metZScores,'descend');
-0140 mets=mets(I);
-0141 metNames=metNames(I);
-0142 metPValues=metPValues(I);
-0143 metNGenes=metNGenes(I);
-0144 meanZ=meanZ(I);
-0145 stdZ=stdZ(I);
-0146 
-0147 %Prepare the output
-0148 repMets.mets=mets;
-0149 repMets.metNames=metNames;
-0150 repMets.metZScores=metZScores;
-0151 repMets.metPValues=metPValues;
-0152 repMets.metNGenes=metNGenes;
-0153 repMets.meanZ=meanZ;
-0154 repMets.stdZ=stdZ;
-0155 
-0156 %Call this function recursively if geneFoldChanges has been specified
-0157 repMets(1).test='all';
-0158 if any(geneFoldChanges)
-0159     repMets=[repMets;reporterMetabolites(model,genes(geneFoldChanges>=0),genePValues(geneFoldChanges>=0))];
-0160     repMets=[repMets;reporterMetabolites(model,genes(geneFoldChanges<0),genePValues(geneFoldChanges<0))];
-0161     repMets(2).test='only up';
-0162     repMets(3).test='only down';
-0163 end
-0164 
-0165 %This is for printing results to the screen. For printing a full list of
-0166 %all scores, specify a output file
-0167 if printResults==true
-0168     for i=1:numel(repMets)
-0169         fprintf(['TOP 20 REPORTER METABOLITES\nTEST TYPE: ' repMets(i).test '\nID\tNAME\tP-VALUE\n']);
-0170         for j=1:min(20,numel(repMets(i).mets))
-0171             fprintf([repMets(i).mets{j} '\t' repMets(i).metNames{j} '\t' num2str(repMets(i).metPValues(j)) '\n']);
-0172         end
-0173         fprintf('\n');
-0174     end
-0175 end
-0176 
-0177 %Print results to file
-0178 if any(outputFile)
-0179     fid=fopen(outputFile,'w');
-0180     for i=1:numel(repMets)
-0181         fprintf(fid,['REPORTER METABOLITES USING TEST TYPE: ' repMets(i).test '\n']);
-0182         fprintf(fid,'ID\tNAME\tZ-SCORE\tP-VALUE\tNUMBER OF NEIGHBOURS\tAVERAGE Z-SCORE\tSTD Z-SCORE\n');
-0183         for j=1:numel(repMets(i).mets)
-0184             fprintf(fid,[repMets(i).mets{j} '\t' repMets(i).metNames{j} '\t' num2str(repMets(i).metZScores(j)) '\t' num2str(repMets(i).metPValues(j)) '\t' num2str(repMets(i).metNGenes(j)) '\t' num2str(repMets(i).meanZ(j)) '\t' num2str(repMets(i).stdZ(j)) '\n']);
-0185         end
-0186     end
-0187     fclose(fid);
-0188 end
-0189 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/runDynamicFBA.html b/doc/core/runDynamicFBA.html deleted file mode 100644 index 252a1cbec..000000000 --- a/doc/core/runDynamicFBA.html +++ /dev/null @@ -1,218 +0,0 @@ - - - - Description of runDynamicFBA - - - - - - - - - -
Home > core > runDynamicFBA.m
- - - -

runDynamicFBA -

- -

PURPOSE ^

-
runDynamicFBA
- -

SYNOPSIS ^

-
function [concentrationMatrix, excRxnNames, timeVec, biomassVec] = runDynamicFBA(model, substrateRxns, initConcentrations, initBiomass, timeStep, nSteps, plotRxns, exclUptakeRxns)
- -

DESCRIPTION ^

-
 runDynamicFBA
-   Performs dynamic FBA simulation using the static optimization approach
-
- Input:
-   model               a model structure
-   substrateRxns       cell array with exchange reaction identifiers for
-                       substrates that are initially in the media, whose
-                       concentration may change (e.g. not h2o or co2)
-   initConcentrations  numeric initial concentrations of substrates
-                       (matching substrateRxns)
-   initBiomass         numeric initial biomass (must be non-zero)
-   timeStep            numeric time step size
-   nSteps              numeric maximum number of time steps
-   plotRxns            cell array with exchange reaction identifiers for
-                       substrates whose concentration should be plotted
-   exclUptakeRxns      cell array with exchange reaction identifiers for
-                       substrates whose concentration does not change
-                       (e.g. co2, o2, h2o, h)
-
- Output:
-   concentrationMatrix numeric matrix with extracellular metabolite
-                       concentrations
-   excRxnNames         cell array with exchange reaction identifiers that
-                       match the metabolites included in the
-                       concentrationMatrix
-   timeVec             numeric vector of time points
-   biomassVec          numeric vector with biomass concentrations
-
- If no initial concentration is given for a substrate that has an open
- uptake in the model (i.e. `model.lb < 0`) the concentration is assumed to
- be high enough to not be limiting. If the uptake rate for a nutrient is
- calculated to exceed the maximum uptake rate for that nutrient specified
- in the model and the max uptake rate specified is > 0, the maximum uptake
- rate specified in the model is used instead of the calculated uptake
- rate.
-
- Modified from COBRA Toolbox dynamicFBA.m
-
- Usage: [concentrationMatrix, excRxnNames, timeVec, biomassVec] = runDynamicFBA(model, substrateRxns, initConcentrations, initBiomass, timeStep, nSteps, plotRxns, exclUptakeRxns)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function [concentrationMatrix, excRxnNames, timeVec, biomassVec] = runDynamicFBA(model, substrateRxns, initConcentrations, initBiomass, timeStep, nSteps, plotRxns, exclUptakeRxns)
-0002 % runDynamicFBA
-0003 %   Performs dynamic FBA simulation using the static optimization approach
-0004 %
-0005 % Input:
-0006 %   model               a model structure
-0007 %   substrateRxns       cell array with exchange reaction identifiers for
-0008 %                       substrates that are initially in the media, whose
-0009 %                       concentration may change (e.g. not h2o or co2)
-0010 %   initConcentrations  numeric initial concentrations of substrates
-0011 %                       (matching substrateRxns)
-0012 %   initBiomass         numeric initial biomass (must be non-zero)
-0013 %   timeStep            numeric time step size
-0014 %   nSteps              numeric maximum number of time steps
-0015 %   plotRxns            cell array with exchange reaction identifiers for
-0016 %                       substrates whose concentration should be plotted
-0017 %   exclUptakeRxns      cell array with exchange reaction identifiers for
-0018 %                       substrates whose concentration does not change
-0019 %                       (e.g. co2, o2, h2o, h)
-0020 %
-0021 % Output:
-0022 %   concentrationMatrix numeric matrix with extracellular metabolite
-0023 %                       concentrations
-0024 %   excRxnNames         cell array with exchange reaction identifiers that
-0025 %                       match the metabolites included in the
-0026 %                       concentrationMatrix
-0027 %   timeVec             numeric vector of time points
-0028 %   biomassVec          numeric vector with biomass concentrations
-0029 %
-0030 % If no initial concentration is given for a substrate that has an open
-0031 % uptake in the model (i.e. `model.lb < 0`) the concentration is assumed to
-0032 % be high enough to not be limiting. If the uptake rate for a nutrient is
-0033 % calculated to exceed the maximum uptake rate for that nutrient specified
-0034 % in the model and the max uptake rate specified is > 0, the maximum uptake
-0035 % rate specified in the model is used instead of the calculated uptake
-0036 % rate.
-0037 %
-0038 % Modified from COBRA Toolbox dynamicFBA.m
-0039 %
-0040 % Usage: [concentrationMatrix, excRxnNames, timeVec, biomassVec] = runDynamicFBA(model, substrateRxns, initConcentrations, initBiomass, timeStep, nSteps, plotRxns, exclUptakeRxns)
-0041 
-0042 % Find exchange rxns
-0043 excRxnNames = getExchangeRxns(model);
-0044 excRxnNames(ismember(excRxnNames,exclUptakeRxns))=[];
-0045 excInd = getIndexes(model,excRxnNames,'rxns');
-0046 % Figure out if substrate reactions are correct
-0047 missingInd = find(~ismember(substrateRxns,excRxnNames));
-0048 if (~isempty(missingInd))
-0049     for i = 1:length(missingInd)
-0050         fprintf('%s\n',substrateRxns{missingInd(i)});
-0051     end
-0052     error('Invalid substrate uptake reaction!');
-0053 end
-0054 
-0055 % Initialize concentrations
-0056 [~, substrateMatchInd] = ismember(substrateRxns,excRxnNames);
-0057 concentrations = zeros(length(excRxnNames),1);
-0058 concentrations(substrateMatchInd) = initConcentrations;
-0059 
-0060 % Deal with reactions for which there are no initial concentrations
-0061 originalBound = -model.lb(excInd);
-0062 noInitConcentration = (concentrations == 0 & originalBound > 0);
-0063 concentrations(noInitConcentration) = 1000;
-0064 
-0065 biomass = initBiomass;
-0066 
-0067 % Initialize bounds
-0068 uptakeBound =  concentrations/(biomass*timeStep);
-0069 
-0070 % Make sure bounds are not higher than what are specified in the model
-0071 aboveOriginal = (uptakeBound > originalBound) & (originalBound > 0);
-0072 uptakeBound(aboveOriginal) = originalBound(aboveOriginal);
-0073 model.lb(excInd) = -uptakeBound;
-0074 
-0075 concentrationMatrix = concentrations;
-0076 biomassVec = biomass;
-0077 timeVec(1) = 0;
-0078 [~,hsSol]=solveLP(model,1);
-0079 PB = ProgressBar2(nSteps,'Running dynamic FBA analysis','cli');
-0080 for stepNo = 1:nSteps
-0081     % Run FBA
-0082     [sol,hsSol] = solveLP(model,1,[],hsSol);
-0083     mu = sol.f;
-0084     if (sol.stat ~= 1 || mu == 0)
-0085         fprintf('\nNo feasible solution - nutrients exhausted. Biomass:\t %f\n', biomass);
-0086         break;
-0087     end
-0088     uptakeFlux = sol.x(excInd);
-0089     biomass = biomass*exp(mu*timeStep);
-0090     biomassVec(end+1) = biomass;
-0091 
-0092     % Update concentrations
-0093     concentrations = concentrations - uptakeFlux/mu*biomass*(1-exp(mu*timeStep));
-0094     concentrations(concentrations <= 0) = 0;
-0095     concentrationMatrix(:,end+1) = concentrations;
-0096 
-0097     % Update bounds for uptake reactions
-0098     uptakeBound =  concentrations/(biomass*timeStep);
-0099     % This is to avoid any numerical issues
-0100     uptakeBound(uptakeBound > 1000) = 1000;
-0101     % Figure out if the computed bounds were above the original bounds
-0102     aboveOriginal = (uptakeBound > originalBound) & (originalBound > 0);
-0103     % Revert to original bounds if the rate was too high
-0104     uptakeBound(aboveOriginal) = originalBound(aboveOriginal);
-0105     uptakeBound(abs(uptakeBound) < 1e-9) = 0;
-0106 
-0107     model.lb(excInd) = -uptakeBound;
-0108     timeVec(stepNo+1) = stepNo*timeStep;
-0109 
-0110     count(PB);
-0111 end
-0112 
-0113 selNonZero = any(concentrationMatrix>0,2);
-0114 concentrationMatrix = concentrationMatrix(selNonZero,:);
-0115 excRxnNames = excRxnNames(selNonZero);
-0116 selPlot = ismember(excRxnNames,plotRxns);
-0117 
-0118 % Plot concentrations as a function of time
-0119 clf
-0120 subplot(1,2,1);
-0121 plot(timeVec,biomassVec);
-0122 axis tight
-0123 title('Biomass');
-0124 xlabel('Time (h)');
-0125 ylabel('Concentration (g/L)');
-0126 subplot(1,2,2);
-0127 plot(timeVec,concentrationMatrix(selPlot,:));
-0128 axis tight
-0129 title('Substrates and/or products');
-0130 xlabel('Time (h)');
-0131 ylabel('Concentration (mmol/L)');
-0132 legend(strrep(excRxnNames(selPlot),'EX_',''));
-0133 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/runPhenotypePhasePlane.html b/doc/core/runPhenotypePhasePlane.html deleted file mode 100644 index 8cf0ac25d..000000000 --- a/doc/core/runPhenotypePhasePlane.html +++ /dev/null @@ -1,161 +0,0 @@ - - - - Description of runPhenotypePhasePlane - - - - - - - - - -
Home > core > runPhenotypePhasePlane.m
- - - -

runPhenotypePhasePlane -

- -

PURPOSE ^

-
runPhenotypePhasePlane
- -

SYNOPSIS ^

-
function [growthRates, shadowPrices1, shadowPrices2] = runPhenotypePhasePlane(model, controlRxn1, controlRxn2, nPts, range1, range2)
- -

DESCRIPTION ^

-
 runPhenotypePhasePlane
-   Runs phenotype phase plane analysis and plots the results. The first
-   plot is a 3D surface plot showing the phenotype phase plane, the other
-   two plots show the shadow prices of the metabolites from the two
-   control reactions, which define the phases. Modified from the COBRA
-   phenotypePhasePlane function.
-
- Input:
-   model           a model structure
-   controlRxn1     reaction identifier of the first reaction to be plotted
-   controlRxn2     reaction identifier of the second reaction to be plotted
-   nPts            the number of points to plot in each dimension (optional,
-                   default 50)
-   range1          the range [from 0 to range1] of reaction 1 to plot
-                   (optional, default 20)
-   range2          the range [from 0 to range2] of reaction 2 to plot
-                   (optional, default 20)
-
- Output:
-   growthRates1    a matrix of maximum growth rates
-   shadowPrices1   a matrix with shadow prices for reaction 1
-   shadowPrices2   a matrix with shadow prices for reaction 2
-
- Modified from COBRA Toolbox phenotypePhasePlane.m
-
- Usage: [growthRates, shadowPrices1, shadowPrices2] = runPhenotypePhasePlane(model, controlRxn1, controlRxn2, nPts, range1, range2)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function [growthRates, shadowPrices1, shadowPrices2] = runPhenotypePhasePlane(model, controlRxn1, controlRxn2, nPts, range1, range2)
-0002 % runPhenotypePhasePlane
-0003 %   Runs phenotype phase plane analysis and plots the results. The first
-0004 %   plot is a 3D surface plot showing the phenotype phase plane, the other
-0005 %   two plots show the shadow prices of the metabolites from the two
-0006 %   control reactions, which define the phases. Modified from the COBRA
-0007 %   phenotypePhasePlane function.
-0008 %
-0009 % Input:
-0010 %   model           a model structure
-0011 %   controlRxn1     reaction identifier of the first reaction to be plotted
-0012 %   controlRxn2     reaction identifier of the second reaction to be plotted
-0013 %   nPts            the number of points to plot in each dimension (optional,
-0014 %                   default 50)
-0015 %   range1          the range [from 0 to range1] of reaction 1 to plot
-0016 %                   (optional, default 20)
-0017 %   range2          the range [from 0 to range2] of reaction 2 to plot
-0018 %                   (optional, default 20)
-0019 %
-0020 % Output:
-0021 %   growthRates1    a matrix of maximum growth rates
-0022 %   shadowPrices1   a matrix with shadow prices for reaction 1
-0023 %   shadowPrices2   a matrix with shadow prices for reaction 2
-0024 %
-0025 % Modified from COBRA Toolbox phenotypePhasePlane.m
-0026 %
-0027 % Usage: [growthRates, shadowPrices1, shadowPrices2] = runPhenotypePhasePlane(model, controlRxn1, controlRxn2, nPts, range1, range2)
-0028 close all force % Close all existing figure windows (if open)
-0029 if nargin < 4
-0030     nPts = 50;
-0031 end
-0032 if nargin < 5
-0033     range1 = 20;
-0034 end
-0035 if nargin < 6
-0036     range2 = 20;
-0037 end
-0038 
-0039 rxnID1 = getIndexes(model,controlRxn1,'rxns',true);
-0040 metID1 = find(model.S(:,rxnID1));
-0041 rxnID2 = getIndexes(model,controlRxn2,'rxns',true);
-0042 metID2 = find(model.S(:,rxnID2));
-0043 
-0044 % Create empty vectors for the results
-0045 ind1 = linspace(0,range1,nPts);
-0046 ind2 = linspace(0,range2,nPts);
-0047 growthRates = zeros(nPts);
-0048 shadowPrices1 = zeros(nPts);
-0049 shadowPrices2 = zeros(nPts);
-0050 [~,hsSol] = solveLP(model);
-0051 % Calulate points
-0052 PB = ProgressBar2(nPts,'Running PhPP analysis','cli');
-0053 for i = 1:nPts %ind1
-0054     for j = 1:nPts %ind2
-0055         model1 = setParam(model,'eq',controlRxn1,-1*ind1(i));
-0056         model1 = setParam(model1,'eq',controlRxn2,-1*ind2(j));
-0057         [fbasol,hsSol] = solveLP(model1,0,[],hsSol);
-0058         try
-0059             growthRates(j,i) = fbasol.x(logical(model1.c));
-0060             shadowPrices1(j,i) = fbasol.sPrice(metID1);
-0061             shadowPrices2(j,i) = fbasol.sPrice(metID2);   
-0062         end
-0063     end
-0064     count(PB);
-0065 end
-0066 fprintf('\b\b\b\b\b\b\b\b\b\b\b\b\bCOMPLETE\n');
-0067 
-0068 % Plot the points
-0069 figure(2);
-0070 pcolor(ind1,ind2,shadowPrices1);
-0071 xlabel(strrep(strcat(controlRxn1,' (mmol/g DW-hr)'),'_','\_')), ylabel(strrep(strcat(controlRxn2,' (mmol/g DW-hr)'),'_','\_')), zlabel('growth rate (1/hr)');
-0072 title(['Shadow price ' strrep(model.mets{metID1},'_','-')]);
-0073 colorbar();
-0074 xticklabels(sprintfc('%d', -xticks))
-0075 yticklabels(sprintfc('%d', -yticks))
-0076 figure(3);
-0077 pcolor(ind1,ind2,shadowPrices2);
-0078 xlabel(strrep(strcat(controlRxn1,' (mmol/g DW-hr)'),'_','\_')), ylabel(strrep(strcat(controlRxn2,' (mmol/g DW-hr)'),'_','\_')), zlabel('growth rate (1/hr)');
-0079 title(['Shadow price ' strrep(model.mets{metID2},'_','-')]);
-0080 colorbar();
-0081 xticklabels(sprintfc('%d', -xticks))
-0082 yticklabels(sprintfc('%d', -yticks))
-0083 figure(1);
-0084 surfl(ind1,ind2,growthRates);
-0085 xlabel(strrep(strcat(controlRxn1,' (mmol/g DW-hr)'),'_','\_')), ylabel(strrep(strcat(controlRxn2,' (mmol/g DW-hr)'),'_','\_')), zlabel('growth rate (1/hr)');
-0086 colormap(hsv(17));
-0087 xticklabels(sprintfc('%d', -xticks))
-0088 yticklabels(sprintfc('%d', -yticks))
-0089 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/runProductionEnvelope.html b/doc/core/runProductionEnvelope.html deleted file mode 100644 index 6c243ae88..000000000 --- a/doc/core/runProductionEnvelope.html +++ /dev/null @@ -1,127 +0,0 @@ - - - - Description of runProductionEnvelope - - - - - - - - - -
Home > core > runProductionEnvelope.m
- - - -

runProductionEnvelope -

- -

PURPOSE ^

-
runProductionEnvelope
- -

SYNOPSIS ^

-
function [biomassValues, targetValues] = runProductionEnvelope(model, targetRxn, biomassRxn, nPts)
- -

DESCRIPTION ^

-
 runProductionEnvelope
-   Calculates the byproduct secretion envelope
-
- Input:
-   model            a model structure
-   targetRxn        identifier of target metabolite production reaction
-   biomassRxn       identifier of biomass reaction
-   nPts             number of points in the plot (optional, default 20)
-
- Output:
-   biomassValues    Biomass values for plotting
-   targetValues     Target upper and lower bounds for plotting
-
- Modified from COBRA Toolbox productionEnvelope.m
-
- Usage: [biomassValues, targetValues] = runProductionEnvelope(model,...
-               targetRxn, biomassRxn, nPts)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function [biomassValues, targetValues] = runProductionEnvelope(model, targetRxn, biomassRxn, nPts)
-0002 % runProductionEnvelope
-0003 %   Calculates the byproduct secretion envelope
-0004 %
-0005 % Input:
-0006 %   model            a model structure
-0007 %   targetRxn        identifier of target metabolite production reaction
-0008 %   biomassRxn       identifier of biomass reaction
-0009 %   nPts             number of points in the plot (optional, default 20)
-0010 %
-0011 % Output:
-0012 %   biomassValues    Biomass values for plotting
-0013 %   targetValues     Target upper and lower bounds for plotting
-0014 %
-0015 % Modified from COBRA Toolbox productionEnvelope.m
-0016 %
-0017 % Usage: [biomassValues, targetValues] = runProductionEnvelope(model,...
-0018 %               targetRxn, biomassRxn, nPts)
-0019 
-0020 if nargin < 4
-0021     nPts = 20;
-0022 end
-0023 
-0024 % Run FBA to get upper bound for biomass
-0025 model   = setParam(model,'obj',biomassRxn,1);
-0026 [solMax,hsSol]  = solveLP(model);
-0027 solMax  = solMax.x(logical(model.c));
-0028 model.c = -model.c;
-0029 solMin  = solveLP(model,0,[],hsSol);
-0030 solMin  = solMin.x(logical(model.c));
-0031 
-0032 % Create biomass range vector
-0033 biomassValues = linspace(solMin,solMax,nPts);
-0034 targetUpperBound = nan(1,numel(biomassValues));
-0035 targetLowerBound = nan(1,numel(biomassValues));
-0036 
-0037 PB = ProgressBar2(length(biomassValues),'Creating production envelope','cli');
-0038 % Max/min for target production
-0039 model = setParam(model,'obj',targetRxn,1);
-0040 for i = 1:length(biomassValues)
-0041     model1 = setParam(model,'eq',biomassRxn,biomassValues(i));
-0042     sol = solveLP(model1,0,[],hsSol);
-0043     if (sol.stat > 0)
-0044         targetUpperBound(i) = sol.x(logical(model.c));
-0045     else
-0046         targetUpperBound(i) = NaN;
-0047     end
-0048     model1.c = -model1.c;
-0049     sol = solveLP(model1,0,[],hsSol);
-0050     if (sol.stat > 0)
-0051         targetLowerBound(i) = sol.x(logical(model1.c));
-0052     else
-0053         targetLowerBound(i) = NaN;
-0054     end
-0055     count(PB);
-0056 end
-0057 
-0058 % Plot results
-0059 plot([biomassValues fliplr(biomassValues)],[targetUpperBound fliplr(targetLowerBound)],'blue','LineWidth',2);
-0060 axis tight;
-0061 ylabel([strrep(targetRxn,'_','-') ' (mmol/gDW h)']);
-0062 xlabel('Growth rate (1/h)');
-0063 targetValues = [targetLowerBound; targetUpperBound];
-0064 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/runRobustnessAnalysis.html b/doc/core/runRobustnessAnalysis.html deleted file mode 100644 index 7a7187156..000000000 --- a/doc/core/runRobustnessAnalysis.html +++ /dev/null @@ -1,140 +0,0 @@ - - - - Description of runRobustnessAnalysis - - - - - - - - - -
Home > core > runRobustnessAnalysis.m
- - - -

runRobustnessAnalysis -

- -

PURPOSE ^

-
runRobustnessAnalysis
- -

SYNOPSIS ^

-
function [controlFlux, objFlux] = runRobustnessAnalysis(model, controlRxn, nPoints, objRxn, plotRedCost)
- -

DESCRIPTION ^

-
 runRobustnessAnalysis
-   Performs robustness analysis for a reaction of interest and an objective
-   of interest. Modified from the COBRA robustnessAnalysis function.
-
- Input:
-   model           a model structure
-   controlRxn      reaction of interest whose value is to be controlled
-   nPoints         number of points to show on plot (optional, default 20)
-   objRxn          reaction identifier of objective to be maximized (optional,
-                   default it uses the objective defined in the model)
-   plotRedCost     logical whether reduced cost should also be plotted
-                   (optional, default false)
-
- Output:
-   controlFlux     flux values of the reaction of interest, ranging from
-                   its minimum to its maximum value
-   objFlux         optimal values of objective reaction at each control
-                   reaction flux value
-
- Modified from COBRA Toolbox robustnessAnalysis.m
-
- Usage: runRobustnessAnalysis(model, controlRxn, nPoints, objRxn)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function [controlFlux, objFlux] = runRobustnessAnalysis(model, controlRxn, nPoints, objRxn, plotRedCost)
-0002 % runRobustnessAnalysis
-0003 %   Performs robustness analysis for a reaction of interest and an objective
-0004 %   of interest. Modified from the COBRA robustnessAnalysis function.
-0005 %
-0006 % Input:
-0007 %   model           a model structure
-0008 %   controlRxn      reaction of interest whose value is to be controlled
-0009 %   nPoints         number of points to show on plot (optional, default 20)
-0010 %   objRxn          reaction identifier of objective to be maximized (optional,
-0011 %                   default it uses the objective defined in the model)
-0012 %   plotRedCost     logical whether reduced cost should also be plotted
-0013 %                   (optional, default false)
-0014 %
-0015 % Output:
-0016 %   controlFlux     flux values of the reaction of interest, ranging from
-0017 %                   its minimum to its maximum value
-0018 %   objFlux         optimal values of objective reaction at each control
-0019 %                   reaction flux value
-0020 %
-0021 % Modified from COBRA Toolbox robustnessAnalysis.m
-0022 %
-0023 % Usage: runRobustnessAnalysis(model, controlRxn, nPoints, objRxn)
-0024 
-0025 if nargin < 3
-0026     nPoints = 20;
-0027 end
-0028 if nargin < 4
-0029     baseModel = model;
-0030 else
-0031     baseModel = setParam(model,'obj',objRxn,1);
-0032 end
-0033 if nargin < 5
-0034     plotRedCost = false;
-0035 end
-0036 
-0037 if any(ismember(model.rxns,controlRxn))
-0038     controlRxnIdx = getIndexes(model,controlRxn,'rxns');
-0039     tmpModel = setParam(model,'obj',controlRxnIdx,1);
-0040     solMax = solveLP(tmpModel);
-0041     solMax = solMax.x(logical(tmpModel.c));
-0042     tmpModel.c = -tmpModel.c;
-0043     solMin = solveLP(tmpModel);
-0044     solMin = solMin.x(logical(tmpModel.c));
-0045 else
-0046     error('Control reaction does not exist!');
-0047 end
-0048 
-0049 objFlux = zeros(nPoints,1);
-0050 redCost = zeros(nPoints,1);
-0051 controlFlux = linspace(solMin,solMax,nPoints)';
-0052 
-0053 
-0054 PB = ProgressBar2(length(controlFlux),'Running robustness analysis','cli');
-0055 for i=1:length(controlFlux)
-0056     modelControlled = setParam(baseModel,'eq',controlRxnIdx,controlFlux(i));
-0057     solControlled = solveLP(modelControlled);
-0058     objFlux(i) = solControlled.x(logical(modelControlled.c));
-0059     redCost(i) = solControlled.rCost(controlRxnIdx);
-0060     count(PB);
-0061 end
-0062 
-0063 if plotRedCost
-0064     yyaxis right
-0065     plot(controlFlux,redCost)
-0066     ylabel([strrep(controlRxn,'_','-') ' reduced cost']);
-0067     yyaxis left
-0068 end
-0069 plot(controlFlux,objFlux)
-0070 xlabel(strrep(controlRxn,'_','-'));
-0071 ylabel('Objective');
-0072 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/runSimpleOptKnock.html b/doc/core/runSimpleOptKnock.html deleted file mode 100644 index 048f89006..000000000 --- a/doc/core/runSimpleOptKnock.html +++ /dev/null @@ -1,198 +0,0 @@ - - - - Description of runSimpleOptKnock - - - - - - - - - -
Home > core > runSimpleOptKnock.m
- - - -

runSimpleOptKnock -

- -

PURPOSE ^

-
runSimpleOptKnock
- -

SYNOPSIS ^

-
function out = runSimpleOptKnock(model, targetRxn, biomassRxn, deletions, genesOrRxns, maxNumKO, minGrowth)
- -

DESCRIPTION ^

-
 runSimpleOptKnock
-   Simple OptKnock algorithm that checks all gene or reaction deletions
-   for growth-coupled metabolite production, by testing all possible
-   combinations. This is not defined as MILP, and is therefore slow (but
-   simple).
-
- Input:
-    model          a model structure
-    targetRxn      identifier of target reaction
-    biomassRxn     identifier of biomass reaction
-    deletions      cell array with gene or reaction identifiers that
-                   should be considered for knockout
-                   (optional, default = model.rxns)
-    genesOrRxns    string indicating whether deletions parameter is given
-                   with 'genes' or 'rxns' identifiers (optional, default
-                   'rxns')
-    maxNumKO       numeric with maximum number of simulatenous knockout
-                   (optional, default 1)
-    minGrowth      numeric of minimum growth rate (optional, default 0.05)
-
- Output:
-    out            structure with deletions strategies that result in
-                   growth-coupled production
-       KO          cell array with gene(s) or reaction(s) to be deleted
-       growthRate  vector with growth rates after deletion
-       prodRate    vector with production rates after deletion
-
- Usage: out = runSimpleOptKnock(model, targetRxn, biomassRxn, deletions,...
-                   genesOrRxns, maxNumKO, minGrowth)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 function out = runSimpleOptKnock(model, targetRxn, biomassRxn, deletions, genesOrRxns, maxNumKO, minGrowth)
-0002 % runSimpleOptKnock
-0003 %   Simple OptKnock algorithm that checks all gene or reaction deletions
-0004 %   for growth-coupled metabolite production, by testing all possible
-0005 %   combinations. This is not defined as MILP, and is therefore slow (but
-0006 %   simple).
-0007 %
-0008 % Input:
-0009 %    model          a model structure
-0010 %    targetRxn      identifier of target reaction
-0011 %    biomassRxn     identifier of biomass reaction
-0012 %    deletions      cell array with gene or reaction identifiers that
-0013 %                   should be considered for knockout
-0014 %                   (optional, default = model.rxns)
-0015 %    genesOrRxns    string indicating whether deletions parameter is given
-0016 %                   with 'genes' or 'rxns' identifiers (optional, default
-0017 %                   'rxns')
-0018 %    maxNumKO       numeric with maximum number of simulatenous knockout
-0019 %                   (optional, default 1)
-0020 %    minGrowth      numeric of minimum growth rate (optional, default 0.05)
-0021 %
-0022 % Output:
-0023 %    out            structure with deletions strategies that result in
-0024 %                   growth-coupled production
-0025 %       KO          cell array with gene(s) or reaction(s) to be deleted
-0026 %       growthRate  vector with growth rates after deletion
-0027 %       prodRate    vector with production rates after deletion
-0028 %
-0029 % Usage: out = runSimpleOptKnock(model, targetRxn, biomassRxn, deletions,...
-0030 %                   genesOrRxns, maxNumKO, minGrowth)
-0031 
-0032 if nargin < 4
-0033     params.deletions = model.rxns;
-0034 else
-0035     params.deletions = deletions;
-0036 end
-0037 if nargin < 5
-0038     params.genesOrRxns = 'rxns';
-0039 else
-0040     params.genesOrRxns = genesOrRxns;
-0041 end
-0042 if nargin < 6
-0043     params.maxNumKO = 1;
-0044 else
-0045     params.maxNumKO = maxNumKO;
-0046 end
-0047 if nargin < 7
-0048     params.minGrowth = 0.05;
-0049 else
-0050     params.minGrowth = minGrowth;
-0051 end
-0052 
-0053 % Number of deletions
-0054 out.KO         = cell(0,params.maxNumKO); % The KO genes/rxns
-0055 out.growthRate = zeros(0);
-0056 out.prodRate   = zeros(0);
-0057 out.score      = zeros(0);
-0058 
-0059 params.biomassIdx  = getIndexes(model,biomassRxn,'rxns');
-0060 params.targetIdx   = getIndexes(model,targetRxn,'rxns');
-0061 
-0062 model = setParam(model,'obj',params.biomassIdx,1);
-0063 [solWT, hsSol] = solveLP(model);
-0064 WT.minScore = solWT.x(params.targetIdx)*solWT.f;
-0065 
-0066 fprintf('Running simple OptKnock analysis...   0%% complete');
-0067 KO=zeros(1,params.maxNumKO);
-0068 [~,~,out,~] = knockoutIteration(model,params,WT,out,params.maxNumKO,KO,[],hsSol);
-0069 
-0070 if size(out.KO,2)>1
-0071     singleKO = cellfun(@isempty,out.KO(:,1));
-0072     if any(singleKO)
-0073         singleKO = out.KO{singleKO,2};
-0074         singleKO = strcmp(out.KO(:,1),singleKO);
-0075         out.KO(singleKO,:) = [];
-0076         out.growthRate(singleKO,:) = [];
-0077         out.prodRate(singleKO,:) = [];
-0078         out.score(singleKO,:) = [];
-0079     end
-0080 end
-0081 
-0082 
-0083 fprintf('\b\b\b\b\b\b\b\b\b\b\b\b\bCOMPLETE\n');
-0084 end
-0085 
-0086 function [model,iteration,out,KO,hsSol] = knockoutIteration(model,params,WT,out,iteration,KO,minScore,hsSol)
-0087 if nargin<7 || isempty(minScore)
-0088     minScore = WT.minScore;
-0089 end
-0090 iteration = iteration - 1;
-0091 for i = 1:numel(params.deletions)
-0092     if iteration+1==params.maxNumKO
-0093         progress=pad(num2str(floor(i/numel(params.deletions)*100)),3,'left');
-0094         fprintf('\b\b\b\b\b\b\b\b\b\b\b\b\b%s%% complete',progress);
-0095     end
-0096     KO(iteration+1)=i;
-0097     switch params.genesOrRxns
-0098         case 'rxns'
-0099             modelKO = setParam(model,'eq',params.deletions{i},0);
-0100         case 'genes'
-0101             modelKO = removeGenes(model,params.deletions{i},false,false,false);
-0102     end
-0103     solKO = solveLP(modelKO,0,[],hsSol);
-0104     if ~isempty(solKO.f)
-0105         growthRate = solKO.f;
-0106         prodRate   = solKO.x(params.targetIdx);
-0107         prodRate(prodRate<1e-10)=0; % Filter out results from solver tolerance
-0108         if growthRate > params.minGrowth
-0109             if growthRate*prodRate > minScore*1.01
-0110                 out.KO(end+1,find(KO)) = transpose(params.deletions(KO(find(KO))));
-0111                 out.growthRate(end+1,1) = growthRate;
-0112                 out.prodRate(end+1,1)   = prodRate;
-0113                 out.score(end+1,1)      = growthRate*prodRate;
-0114             end
-0115             if iteration>0
-0116                 [~,~,out] = knockoutIteration(modelKO,params,WT,out,iteration,KO,growthRate*prodRate,hsSol);
-0117             end
-0118         end
-0119     end
-0120 end
-0121 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/setExchangeBounds.html b/doc/core/setExchangeBounds.html deleted file mode 100644 index 315190cf3..000000000 --- a/doc/core/setExchangeBounds.html +++ /dev/null @@ -1,309 +0,0 @@ - - - - Description of setExchangeBounds - - - - - - - - - -
Home > core > setExchangeBounds.m
- - - -

setExchangeBounds -

- -

PURPOSE ^

-
setExchangeBounds
- -

SYNOPSIS ^

-
function [exchModel,unusedMets] = setExchangeBounds(model,mets,lb,ub,closeOthers,mediaOnly)
- -

DESCRIPTION ^

-
 setExchangeBounds
-   Define the exchange flux bounds for a given set of metabolites.
-
- Input:
-   model         a model structure
-   mets          a cell array of metabolite names (case insensitive) or 
-                 metabolite IDs, or a vector of metabolite indices
-                 (optional, default all exchanged metabolites)
-   lb            lower bound of exchange flux. Can be either a vector of
-                 bounds corresponding to each of the provided metabolites,
-                 or a single value that will be applied to all.
-                 (optional, default to model.annotation.defaultLB if it exists,
-                 otherwise -1000)
-   ub            upper bound of exchange flux. Can be either a vector of
-                 bounds corresponding to each of the provided metabolites,
-                 or a single value that will be applied to all.
-                 (optional, default to model.annotation.defaultUB if it exists,
-                 otherwise 1000)
-   closeOthers   close exchange reactions for all other exchanged 
-                 metabolites not present in the provided list. This will
-                 prevent IMPORT of the metabolites, but their EXPORT will
-                 not be modified.
-                 (optional, default true)
-   mediaOnly     only consider exchange reactions involving exchange to or
-                 from the extracellular (media) compartment. Reactions
-                 such as "sink" reactions that exchange metabolites
-                 directly with an intracellular compartment will therefore
-                 be ignored even though "getExchangeRxns" identifies such
-                 such reactions as exchange reactions.
-                 Note: The function will attempt to identify the
-                 extracellular compartment by the "compNames" field, and
-                 also requires the "metComps" field to be present,
-                 otherwise the mediaOnly flag will be ignored.
-                 (optional, default false)
-
- Output:
-   exchModel     a model structure with updated exchange flux bounds for
-                 the provided set of metabolites
-   unusedMets    metabolites provided by the user that were not used
-                 because they are not involved in any exchange reactions
-                 in the model
-
- NOTE: Exchange reactions involving more than one metabolite will be
- ignored.
-
- Usage: exchModel = setExchangeBounds(model,mets,lb,ub,closeOthers,mediaOnly);
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function [exchModel,unusedMets] = setExchangeBounds(model,mets,lb,ub,closeOthers,mediaOnly)
-0002 % setExchangeBounds
-0003 %   Define the exchange flux bounds for a given set of metabolites.
-0004 %
-0005 % Input:
-0006 %   model         a model structure
-0007 %   mets          a cell array of metabolite names (case insensitive) or
-0008 %                 metabolite IDs, or a vector of metabolite indices
-0009 %                 (optional, default all exchanged metabolites)
-0010 %   lb            lower bound of exchange flux. Can be either a vector of
-0011 %                 bounds corresponding to each of the provided metabolites,
-0012 %                 or a single value that will be applied to all.
-0013 %                 (optional, default to model.annotation.defaultLB if it exists,
-0014 %                 otherwise -1000)
-0015 %   ub            upper bound of exchange flux. Can be either a vector of
-0016 %                 bounds corresponding to each of the provided metabolites,
-0017 %                 or a single value that will be applied to all.
-0018 %                 (optional, default to model.annotation.defaultUB if it exists,
-0019 %                 otherwise 1000)
-0020 %   closeOthers   close exchange reactions for all other exchanged
-0021 %                 metabolites not present in the provided list. This will
-0022 %                 prevent IMPORT of the metabolites, but their EXPORT will
-0023 %                 not be modified.
-0024 %                 (optional, default true)
-0025 %   mediaOnly     only consider exchange reactions involving exchange to or
-0026 %                 from the extracellular (media) compartment. Reactions
-0027 %                 such as "sink" reactions that exchange metabolites
-0028 %                 directly with an intracellular compartment will therefore
-0029 %                 be ignored even though "getExchangeRxns" identifies such
-0030 %                 such reactions as exchange reactions.
-0031 %                 Note: The function will attempt to identify the
-0032 %                 extracellular compartment by the "compNames" field, and
-0033 %                 also requires the "metComps" field to be present,
-0034 %                 otherwise the mediaOnly flag will be ignored.
-0035 %                 (optional, default false)
-0036 %
-0037 % Output:
-0038 %   exchModel     a model structure with updated exchange flux bounds for
-0039 %                 the provided set of metabolites
-0040 %   unusedMets    metabolites provided by the user that were not used
-0041 %                 because they are not involved in any exchange reactions
-0042 %                 in the model
-0043 %
-0044 % NOTE: Exchange reactions involving more than one metabolite will be
-0045 % ignored.
-0046 %
-0047 % Usage: exchModel = setExchangeBounds(model,mets,lb,ub,closeOthers,mediaOnly);
-0048 
-0049 
-0050 % handle input arguments
-0051 if nargin < 2
-0052     mets = [];
-0053 elseif ~islogical(mets) || ~isnumeric(mets)
-0054     mets=convertCharArray(mets);
-0055 end 
-0056 
-0057 if nargin < 3 || isempty(lb)
-0058     if isfield(model,'annotation') && isfield(model.annotation,'defaultLB')
-0059         lb = model.annotation.defaultLB;
-0060     else
-0061         lb = -1000;
-0062     end
-0063 end
-0064 
-0065 if nargin < 4 || isempty(ub)
-0066     if isfield(model,'annotation') && isfield(model.annotation,'defaultUB')
-0067         ub = model.annotation.defaultUB;
-0068     else
-0069         ub = 1000;
-0070     end
-0071 end
-0072 
-0073 if nargin < 5 || isempty(closeOthers)
-0074     closeOthers = true;
-0075 end
-0076 
-0077 if nargin < 6
-0078     mediaOnly = false;
-0079 elseif mediaOnly
-0080     if ~all(isfield(model,{'compNames','metComps'}))
-0081         error('mediaOnly option requires the "compNames" and "metComps" model fields.');
-0082     end
-0083 end
-0084 
-0085 
-0086 % for models with an "unconstrained" field, generate a version of the model
-0087 % where all the unconstrained metabolites have stoichiometric coeffs set to
-0088 % zero, but remain in the model to avoid index changes
-0089 model_temp = model;
-0090 if isfield(model,'unconstrained')
-0091     model_temp.S(model_temp.unconstrained == 1,:) = 0;
-0092 end
-0093 
-0094 % find exchange rxns, ignoring those involving more than one metabolite
-0095 [~,exchRxnInd] = getExchangeRxns(model);
-0096 exchRxnInd(sum(model_temp.S(:,exchRxnInd) ~= 0,1) > 1) = [];
-0097 
-0098 % find all exchanged metabolites
-0099 exchMetInd = find(any(model_temp.S(:,exchRxnInd) ~= 0,2));
-0100 
-0101 if ( mediaOnly )
-0102     % ignore exchanged metabolites in non-extracellular compartments and
-0103     % any exchange reactions involving these metabolites
-0104     [~,extCompInd] = ismember('extracellular',lower(model.compNames));
-0105     if extCompInd > 0
-0106         ignoreMet = (model.metComps(exchMetInd) ~= extCompInd);
-0107     else
-0108         error('Could not find any compartments named "extracellular".');
-0109     end
-0110     ignoreRxn = any(model.S(exchMetInd(ignoreMet),exchRxnInd) ~= 0,1);
-0111     exchMetInd(ignoreMet) = [];
-0112     exchRxnInd(ignoreRxn) = [];
-0113 end
-0114 
-0115 % Check that all exchange reactions are formulated in the same direction.
-0116 % If not, this means that negative flux indicates import for some exchange
-0117 % reactions, but indicates export for others. Therefore, the LB and UB
-0118 % would need to be specified differently depending on the exchange reaction
-0119 % direction, which is error-prone.
-0120 if all(all(model.S(exchMetInd,exchRxnInd) <= 0))
-0121     importDir = 'backward';
-0122 elseif all(all(model.S(exchMetInd,exchRxnInd) >= 0))
-0123     importDir = 'forward';
-0124 else
-0125     fprintf('WARNING: Some exchange reactions differ in direction, and therefore have opposite meanings of LB and UB.\n');
-0126     if closeOthers
-0127         fprintf('         Therefore, the "closeOthers" option will be set to FALSE.\n');
-0128     end
-0129     closeOthers = false;
-0130 end
-0131 
-0132 % prepare exchanged metabolites and bounds
-0133 if ~isempty(mets)
-0134     
-0135     % prepare lb and ub variables
-0136     if numel(lb) == 1
-0137         lb = lb*ones(size(mets));
-0138     elseif numel(lb) ~= numel(mets)
-0139         error('lb must be a single value or a vector of equal length as mets');
-0140     end
-0141     if numel(ub) == 1
-0142         ub = ub*ones(size(mets));
-0143     elseif numel(ub) ~= numel(mets)
-0144         error('ub must be a single value or a vector of equal length as mets');
-0145     end
-0146     
-0147     % map provided mets to exchanged metabolites
-0148     if isnumeric(mets)
-0149         % mets are provided as indices
-0150         [isExch,metInd] = ismember(mets,exchMetInd);    
-0151     elseif sum(ismember(lower(mets),lower(model.metNames))) > sum(ismember(mets,model.mets))
-0152         % assume that mets are provided as names
-0153         [isExch,metInd] = ismember(lower(mets),lower(model.metNames(exchMetInd)));
-0154     else
-0155         % assume that mets are provided as met IDs
-0156         [isExch,metInd] = ismember(mets,model.mets(exchMetInd));
-0157     end
-0158     
-0159     % get exchanged met indices and determine unused (non-exchanged) mets
-0160     unusedMets = mets(~isExch);
-0161     exchMetInd = exchMetInd(metInd(isExch));
-0162     
-0163     % update bound vectors
-0164     lb = lb(isExch);
-0165     ub = ub(isExch);
-0166     
-0167 else
-0168     % if no mets were provided, use all exchanged mets
-0169     if numel(lb) > 1 || numel(ub) > 1
-0170         error('Only one upper and one lower bound may be provide if metabolites are not specified.');
-0171     else
-0172         lb = lb*ones(size(exchMetInd));
-0173         ub = ub*ones(size(exchMetInd));
-0174     end
-0175     unusedMets = {};
-0176 end
-0177 
-0178 % check that at least one exchanged metabolite matches
-0179 if isempty(exchMetInd)
-0180     fprintf('None of the provided metabolites were found in any exchange reactions.\n');
-0181     exchModel = model;
-0182     return
-0183 end
-0184 
-0185 % determine which metabolite is exchanged in each exchange reaction
-0186 [metInd,rxnInd] = find(model_temp.S(exchMetInd,exchRxnInd) ~= 0);
-0187 
-0188 % check for any metabolites that are exchanged in more than one reaction
-0189 [tbl,i,~] = unique(metInd,'first');
-0190 repeatedInds = find(not(ismember(1:numel(tbl),i)));
-0191 multiMetInd = exchMetInd(metInd(repeatedInds));
-0192 if ~isempty(multiMetInd)
-0193     fprintf('WARNING: The following metabolites are involved in more than one exchange reaction:\n');
-0194     fprintf('\t%s\n',model.metNames{multiMetInd(1:min(numel(multiMetInd),10))});
-0195     if numel(multiMetInd) > 10
-0196         fprintf('\t... and %u more.\n',numel(multiMetInd)-10);
-0197     end
-0198 end
-0199 
-0200 % set exchange reaction bounds
-0201 model = setParam(model,'lb',exchRxnInd(rxnInd),lb(metInd));
-0202 model = setParam(model,'ub',exchRxnInd(rxnInd),ub(metInd));
-0203 
-0204 if closeOthers
-0205     % constrain import of all other exchange reactions to zero
-0206     constrainInd = setdiff(exchRxnInd,exchRxnInd(rxnInd));
-0207     if strcmp(importDir,'backward')
-0208         model = setParam(model,'lb',constrainInd,0);
-0209     else
-0210         model = setParam(model,'ub',constrainInd,0);
-0211     end
-0212 end
-0213 
-0214 % assign output model
-0215 exchModel = model;
-0216 
-0217
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/setParam.html b/doc/core/setParam.html deleted file mode 100644 index 313197877..000000000 --- a/doc/core/setParam.html +++ /dev/null @@ -1,202 +0,0 @@ - - - - Description of setParam - - - - - - - - - -
Home > core > setParam.m
- - - -

setParam -

- -

PURPOSE ^

-
setParam
- -

SYNOPSIS ^

-
function model=setParam(model, paramType, rxnList, params, var)
- -

DESCRIPTION ^

-
 setParam
-   Sets parameters for reactions
-
- Input:
-   model       a model structure
-   paramType   the type of parameter to set:
-               'lb'    lower bound
-               'ub'    upper bound
-               'eq'    both upper and lower bound (equality constraint)
-               'obj'   objective coefficient
-               'rev'   reversibility (only changes the model.rev fields,
-                       does not affect model.lb and model.ub) 
-               'var'   variance around measured bound
-               'unc'   unconstrained, set lower and upper bound to the
-                       default values (-1000 and 1000, or any other values
-                       that are defined in model.annotation.defaultLB and
-                       .defaultUB)
-   rxnList     a cell array of reaction IDs or a vector with their
-               corresponding indexes
-   params      a vector of the corresponding values
-   var         percentage of variance around measured value, if 'var' is
-               set as paramType. Defining 'var' as 5 results in lb and ub
-               at 97.5% and 102.5% of the provide params value (if params
-               value is negative, then lb and ub are 102.5% and 97.5%).
-
- Output:
-   model       an updated model structure
-
- Usage: model = setParam(model, paramType, rxnList, params, var)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function model=setParam(model, paramType, rxnList, params, var)
-0002 % setParam
-0003 %   Sets parameters for reactions
-0004 %
-0005 % Input:
-0006 %   model       a model structure
-0007 %   paramType   the type of parameter to set:
-0008 %               'lb'    lower bound
-0009 %               'ub'    upper bound
-0010 %               'eq'    both upper and lower bound (equality constraint)
-0011 %               'obj'   objective coefficient
-0012 %               'rev'   reversibility (only changes the model.rev fields,
-0013 %                       does not affect model.lb and model.ub)
-0014 %               'var'   variance around measured bound
-0015 %               'unc'   unconstrained, set lower and upper bound to the
-0016 %                       default values (-1000 and 1000, or any other values
-0017 %                       that are defined in model.annotation.defaultLB and
-0018 %                       .defaultUB)
-0019 %   rxnList     a cell array of reaction IDs or a vector with their
-0020 %               corresponding indexes
-0021 %   params      a vector of the corresponding values
-0022 %   var         percentage of variance around measured value, if 'var' is
-0023 %               set as paramType. Defining 'var' as 5 results in lb and ub
-0024 %               at 97.5% and 102.5% of the provide params value (if params
-0025 %               value is negative, then lb and ub are 102.5% and 97.5%).
-0026 %
-0027 % Output:
-0028 %   model       an updated model structure
-0029 %
-0030 % Usage: model = setParam(model, paramType, rxnList, params, var)
-0031 
-0032 paramType=convertCharArray(paramType);
-0033 if ~any(strcmpi(paramType,{'lb','ub','eq','obj','rev','var','unc'}))
-0034     EM=['Incorrect parameter type: "' paramType{1} '"'];
-0035     dispEM(EM);
-0036 end
-0037 if isnumeric(rxnList) || islogical(rxnList)
-0038     rxnList=model.rxns(rxnList);
-0039 else
-0040     rxnList=convertCharArray(rxnList);
-0041 end
-0042 if isempty(rxnList)
-0043     return;
-0044 end
-0045 
-0046 %Allow to set several parameters to the same value
-0047 if numel(rxnList)~=numel(params) && numel(params)~=1
-0048     EM='The number of parameter values and the number of reactions must be the same';
-0049     dispEM(EM);
-0050 end
-0051 
-0052 if length(rxnList)>1
-0053     if length(paramType)==1
-0054         paramType(1:length(rxnList))=paramType;
-0055     end
-0056     if length(params)==1
-0057         params(1:length(rxnList))=params;
-0058     end
-0059 end
-0060 
-0061 %Find the indexes for the reactions in rxnList. Do not use getIndexes
-0062 %as we do not want to throw errors if matches fail
-0063 indexes=zeros(numel(rxnList),1);
-0064 
-0065 [Lia,Locb] = ismember(rxnList,model.rxns);
-0066 indexes(Lia) = Locb;
-0067 if any(~Lia)
-0068     params(~Lia)=[];
-0069     indexes(~Lia)=[];
-0070     paramType(~Lia)=[];
-0071     dispEM('Reactions not present in model, will be ignored:',false,rxnList(~Lia));
-0072 end
-0073 
-0074 %Change the parameters
-0075 if ~isempty(indexes)
-0076     if contains(paramType,'obj')
-0077         model.c=zeros(numel(model.c),1); % parameter is changed, not added
-0078     end
-0079     for j=1:length(paramType)
-0080         if strcmpi(paramType{j},'eq')
-0081             model.lb(indexes(j))=params(j);
-0082             model.ub(indexes(j))=params(j);
-0083         end
-0084         if strcmpi(paramType{j},'lb')
-0085             model.lb(indexes(j))=params(j);
-0086         end
-0087         if strcmpi(paramType{j},'ub')
-0088             model.ub(indexes(j))=params(j);
-0089         end
-0090         if strcmpi(paramType{j},'obj')
-0091             model.c(indexes(j))=params(j);
-0092         end
-0093         if strcmpi(paramType{j},'rev')
-0094             %Non-zero values are interpreted as reversible
-0095             model.rev(indexes(j))=params(j)~=0;
-0096         end
-0097         if strcmpi(paramType{j},'var')
-0098             if params(j) < 0
-0099                 model.lb(indexes(j)) = params(j) * (1+var/200);
-0100                 model.ub(indexes(j)) = params(j) * (1-var/200);
-0101             else
-0102                 model.lb(indexes(j)) = params(j) * (1-var/200);
-0103                 model.ub(indexes(j)) = params(j) * (1+var/200);
-0104             end
-0105         end
-0106         if strcmpi(paramType{j},'unc')
-0107             if isfield(model.annotation,'defaultLB')
-0108                 lb = model.annotation.defaultLB;
-0109             else
-0110                 lb = -1000;
-0111             end
-0112             if isfield(model.annotation,'defaultUB')
-0113                 ub = model.annotation.defaultUB;
-0114             else
-0115                 ub = 1000;
-0116             end
-0117             model.lb(indexes(j)) = lb;
-0118             model.ub(indexes(j)) = ub;
-0119         end
-0120     end
-0121 end
-0122 if any(ismember(paramType,{'lb','ub','unc'}))
-0123     invalidBound = model.lb(indexes) > model.ub(indexes);
-0124     if any(invalidBound)
-0125         error(['Invalid set of bounds for reaction(s): ', strjoin(model.rxns(indexes(invalidBound)),', '), '.'])
-0126     end
-0127 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/simplifyModel.html b/doc/core/simplifyModel.html deleted file mode 100644 index b47bde2de..000000000 --- a/doc/core/simplifyModel.html +++ /dev/null @@ -1,403 +0,0 @@ - - - - Description of simplifyModel - - - - - - - - - -
Home > core > simplifyModel.m
- - - -

simplifyModel -

- -

PURPOSE ^

-
simplifyModel
- -

SYNOPSIS ^

-
function [reducedModel, deletedReactions, deletedMetabolites]=simplifyModel(model,deleteUnconstrained, deleteDuplicates, deleteZeroInterval, deleteInaccessible, deleteMinMax, groupLinear, constrainReversible, reservedRxns, suppressWarnings)
- -

DESCRIPTION ^

-
 simplifyModel
-   Simplifies a model by deleting reactions/metabolites
-
-   model                 a model structure
-   deleteUnconstrained   delete metabolites marked as unconstrained (optional, default true)
-   deleteDuplicates      delete all but one of duplicate reactions (optional, default false)
-   deleteZeroInterval    delete reactions that are constrained to zero flux (optional, default false)
-   deleteInaccessible    delete dead end reactions (optional, default false)
-   deleteMinMax          delete reactions that cannot carry a flux by trying
-                         to minimize/maximize the flux through that
-                         reaction. May be time consuming (optional, default false)
-   groupLinear           group linearly dependent pathways (optional, default false)
-   constrainReversible   check if there are reversible reactions which can
-                         only carry flux in one direction, and if so
-                         constrain them to be irreversible. This tends to
-                         allow for more reactions grouped when using
-                         groupLinear (optional, default false)
-   reservedRxns          cell array with reaction IDs that are not allowed to be
-                         removed (optional)
-   suppressWarnings      true if warnings should be suppressed (optional,
-                         default false)
-
-   reducedModel          an updated model structure
-   deletedReactions      a cell array with the IDs of all deleted reactions
-   deletedMetabolites    a cell array with the IDs of all deleted
-                         metabolites
-
-   This function is for reducing the model size by removing
-   reactions and associated metabolites that cannot carry flux. It can also
-   be used for identifying different types of gaps.
-
- Usage: [reducedModel, deletedReactions, deletedMetabolites]=simplifyModel(model,...
-           deleteUnconstrained, deleteDuplicates, deleteZeroInterval,...
-           deleteInaccessible, deleteMinMax, groupLinear,...
-           constrainReversible, reservedRxns, suppressWarnings)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function [reducedModel, deletedReactions, deletedMetabolites]=simplifyModel(model,...
-0002     deleteUnconstrained, deleteDuplicates, deleteZeroInterval, deleteInaccessible, deleteMinMax, groupLinear, constrainReversible, reservedRxns, suppressWarnings)
-0003 % simplifyModel
-0004 %   Simplifies a model by deleting reactions/metabolites
-0005 %
-0006 %   model                 a model structure
-0007 %   deleteUnconstrained   delete metabolites marked as unconstrained (optional, default true)
-0008 %   deleteDuplicates      delete all but one of duplicate reactions (optional, default false)
-0009 %   deleteZeroInterval    delete reactions that are constrained to zero flux (optional, default false)
-0010 %   deleteInaccessible    delete dead end reactions (optional, default false)
-0011 %   deleteMinMax          delete reactions that cannot carry a flux by trying
-0012 %                         to minimize/maximize the flux through that
-0013 %                         reaction. May be time consuming (optional, default false)
-0014 %   groupLinear           group linearly dependent pathways (optional, default false)
-0015 %   constrainReversible   check if there are reversible reactions which can
-0016 %                         only carry flux in one direction, and if so
-0017 %                         constrain them to be irreversible. This tends to
-0018 %                         allow for more reactions grouped when using
-0019 %                         groupLinear (optional, default false)
-0020 %   reservedRxns          cell array with reaction IDs that are not allowed to be
-0021 %                         removed (optional)
-0022 %   suppressWarnings      true if warnings should be suppressed (optional,
-0023 %                         default false)
-0024 %
-0025 %   reducedModel          an updated model structure
-0026 %   deletedReactions      a cell array with the IDs of all deleted reactions
-0027 %   deletedMetabolites    a cell array with the IDs of all deleted
-0028 %                         metabolites
-0029 %
-0030 %   This function is for reducing the model size by removing
-0031 %   reactions and associated metabolites that cannot carry flux. It can also
-0032 %   be used for identifying different types of gaps.
-0033 %
-0034 % Usage: [reducedModel, deletedReactions, deletedMetabolites]=simplifyModel(model,...
-0035 %           deleteUnconstrained, deleteDuplicates, deleteZeroInterval,...
-0036 %           deleteInaccessible, deleteMinMax, groupLinear,...
-0037 %           constrainReversible, reservedRxns, suppressWarnings)
-0038 
-0039 if nargin<2
-0040     deleteUnconstrained=true;
-0041 end
-0042 if nargin<3
-0043     deleteDuplicates=false;
-0044 end
-0045 if nargin<4
-0046     deleteZeroInterval=false;
-0047 end
-0048 if nargin<5
-0049     deleteInaccessible=false;
-0050 end
-0051 if nargin<6
-0052     deleteMinMax=false;
-0053 end
-0054 if nargin<7
-0055     groupLinear=false;
-0056 end
-0057 if nargin<8
-0058     constrainReversible=false;
-0059 end
-0060 if nargin<9
-0061     reservedRxns=[];
-0062 else
-0063     reservedRxns=convertCharArray(reservedRxns);
-0064 end
-0065 if nargin<10
-0066     suppressWarnings=false;
-0067 end
-0068 
-0069 reducedModel=model;
-0070 deletedReactions={};
-0071 deletedMetabolites={};
-0072 
-0073 if deleteUnconstrained==true
-0074     if isfield(reducedModel,'unconstrained')
-0075         %Remove unbalanced metabolites
-0076         deletedMetabolites=reducedModel.mets(reducedModel.unconstrained~=0);
-0077         reducedModel=removeMets(reducedModel,reducedModel.unconstrained~=0,false,false,false,true);
-0078         reducedModel=rmfield(reducedModel,'unconstrained');
-0079     end
-0080 end
-0081 
-0082 if deleteDuplicates==true
-0083     %Delete all but the last occurrence of duplicate reactions. The
-0084     %reactions must have the same bounds, reversibility, and objective
-0085     %coefficient to be regarded as duplicate
-0086     [reducedModel, rxnsToDelete, ~]=contractModel(reducedModel);
-0087     deletedReactions=[deletedReactions; rxnsToDelete];
-0088 end
-0089 
-0090 if deleteZeroInterval==true
-0091     %Find all reactions where both LB and UB are 0
-0092     zeroIntervalReactions=and(reducedModel.lb==0,reducedModel.ub==0);
-0093     
-0094     rxnsToDelete=setdiff(reducedModel.rxns(zeroIntervalReactions),reservedRxns);
-0095     deletedReactions=[deletedReactions; rxnsToDelete];
-0096     
-0097     %Remove reactions
-0098     reducedModel=removeReactions(reducedModel,rxnsToDelete);
-0099     
-0100     %Find metabolites that no longer are used and delete them
-0101     notInUse=sum(reducedModel.S~=0,2)==0;
-0102     deletedMetabolites=[deletedMetabolites;reducedModel.mets(notInUse)];
-0103     
-0104     %Remove metabolites
-0105     reducedModel=removeMets(reducedModel,notInUse);
-0106 end
-0107 
-0108 if deleteInaccessible==true
-0109     %Print a warning if exchange metabolites haven't been deleted yet. This
-0110     %often means that the only allowed products are the metabolites that
-0111     %are taken up be the system
-0112     if isfield(reducedModel,'unconstrained') && suppressWarnings==false
-0113         EM='Removing dead-end reactions before removing exchange metabolites';
-0114         dispEM(EM,false);
-0115     end
-0116     
-0117     while true
-0118         %Find all metabolites that are only reactants or only products.
-0119         %Delete those metabolites and reactions. This is done until no more
-0120         %such reactions are found
-0121         
-0122         %Construct a stoichiometric matrix where all reactions are written
-0123         %as reversible
-0124         
-0125         %Add fake exchange reactions if model.b~=0
-0126         in=any(reducedModel.b<0,2);
-0127         out=any(reducedModel.b>0,2);
-0128         I=speye(numel(reducedModel.mets));
-0129         revS=[reducedModel.S,reducedModel.S(:,reducedModel.lb<0)*-1 I(:,in) I(:,out)*-1];
-0130         
-0131         metUsage=sum(abs(revS')>0);
-0132         onlyProducts=sum(revS'>0) == metUsage;
-0133         onlyReactants=sum(revS'<0) == metUsage;
-0134         
-0135         %Also remove metabolites that only participate in one reversible
-0136         %reaction Don't remove the ones in one reversible reaction if is
-0137         %also has a non-zero coefficient in model.b
-0138         notInUse=onlyProducts | onlyReactants | (sum(abs(reducedModel.S')>0)<=1 & (~in & ~out)');
-0139         deletedRxn=false;
-0140         if any(notInUse)
-0141             %Find their corresponding reactions
-0142             rxnsNotInUse=sum(abs(reducedModel.S(notInUse,:))>0,1)>0;
-0143             rxnsToDelete=setdiff(reducedModel.rxns(rxnsNotInUse),reservedRxns);
-0144             deletedReactions=[deletedReactions; rxnsToDelete];
-0145             
-0146             %Remove reactions
-0147             reducedModel=removeReactions(reducedModel,rxnsToDelete);
-0148             
-0149             %Remove metabolites. Recalculate since it could be that some
-0150             %cannot be deleted due to reserved rxns
-0151             notInUse=sum(reducedModel.S~=0,2)==0;
-0152             deletedMetabolites=[deletedMetabolites; reducedModel.mets(notInUse)];
-0153             reducedModel=removeMets(reducedModel,notInUse);
-0154             
-0155             %It could happen that it just finds reserved reactions and gets
-0156             %stuck
-0157             if ~isempty(rxnsToDelete)
-0158                 deletedRxn=true;
-0159             end
-0160         else
-0161             break;
-0162         end
-0163         if deletedRxn==false
-0164             break;
-0165         end
-0166     end
-0167 end
-0168 
-0169 if deleteMinMax==true
-0170     %Get reactions that can't carry fluxes. This should be done
-0171     %algebraically if possible
-0172     I=~haveFlux(reducedModel);
-0173     
-0174     %Remove reactions
-0175     rxnsToDelete=setdiff(reducedModel.rxns(I),reservedRxns);
-0176     deletedReactions=[deletedReactions; rxnsToDelete];
-0177     reducedModel=removeReactions(reducedModel,rxnsToDelete);
-0178     
-0179     %Remove metabolites
-0180     notInUse=sum(reducedModel.S~=0,2)==0;
-0181     deletedMetabolites=[deletedMetabolites; reducedModel.mets(notInUse)];
-0182     reducedModel=removeMets(reducedModel,notInUse);
-0183 end
-0184 
-0185 if constrainReversible==true
-0186     revs=find(reducedModel.rev);
-0187     [I,J]=getAllowedBounds(reducedModel,revs);
-0188     
-0189     I=abs(I);
-0190     J=abs(J);
-0191     
-0192     %Get the "small" values
-0193     K=I<10^-10;
-0194     L=J<10^-10;
-0195     
-0196     %Keep the values where only one direction is zero (small)
-0197     I(K==L)=[];
-0198     J(K==L)=[];
-0199     revs(K==L)=[];
-0200     
-0201     %Change the reversibility of the remaining reactions
-0202     reducedModel.rev(revs(J>10^-10))=0; %Ignore reverse direction
-0203     reducedModel.lb(revs(J>10^-10))=0;
-0204     
-0205     toSwitch=revs(I>10^-10);
-0206     reducedModel.rev(toSwitch)=0; %Change directionality
-0207     reducedModel.ub(toSwitch)=reducedModel.lb(toSwitch)*-1;
-0208     reducedModel.lb(toSwitch)=0;
-0209     reducedModel.S(:,toSwitch)=reducedModel.S(:,toSwitch).*-1;
-0210     reducedModel.c(toSwitch)=reducedModel.c(toSwitch)*-1;
-0211 end
-0212 if groupLinear==true
-0213     if  suppressWarnings==false
-0214         fprintf('NOTE: You have chosen to group linear reactions. This option does not keep track of gene/reaction associations when reactions are merged. Deleting all gene information\n');
-0215     end
-0216     
-0217     reducedModel.genes={};
-0218     reducedModel.rxnGeneMat=sparse(numel(reducedModel.rxns),0);
-0219     reducedModel.grRules(:)={''};
-0220     
-0221     if isfield(reducedModel,'geneShortNames')
-0222         reducedModel.geneShortNames={};
-0223     end
-0224     if isfield(reducedModel,'proteins')
-0225         reducedModel.proteins={};
-0226     end
-0227     if isfield(reducedModel,'geneMiriams')
-0228         reducedModel.geneMiriams={};
-0229     end
-0230     if isfield(reducedModel,'geneComps')
-0231         reducedModel.geneComps=[];
-0232     end
-0233     
-0234     %Convert the model to irreversible
-0235     irrevModel=convertToIrrev(reducedModel);
-0236     
-0237     %Loop through and iteratively group linear reactions
-0238     while 1
-0239         %Get the banned reaction indexes. Note that the indexes will change
-0240         %in each iteration, but the names will not as they won't be merged
-0241         %with any other reaction
-0242         bannedIndexes=getIndexes(irrevModel,reservedRxns,'rxns');
-0243         
-0244         %Select all metabolites that are only present as reactants/products
-0245         %in one reaction
-0246         singleNegative=find(sum(irrevModel.S'<0)==1);
-0247         singlePositive=find(sum(irrevModel.S'>0)==1);
-0248         
-0249         %Retrieve the common metabolites
-0250         common=intersect(singleNegative,singlePositive);
-0251         
-0252         mergedSome=false;
-0253         
-0254         %Loop through each of them and see if the reactions should be
-0255         %merged
-0256         for i=1:numel(common)
-0257             involvedRxns=find(irrevModel.S(common(i),:));
-0258             
-0259             %Check so that one or both of the reactions haven't been merged
-0260             %already
-0261             if numel(involvedRxns)==2 && isempty(intersect(bannedIndexes,involvedRxns))
-0262                 %Calculate how many times the second reaction has to be
-0263                 %multiplied before being merged with the first
-0264                 stoichRatio=abs(irrevModel.S(common(i),involvedRxns(1))/irrevModel.S(common(i),involvedRxns(2)));
-0265                 
-0266                 %Add the second to the first
-0267                 irrevModel.S(:,involvedRxns(1))=irrevModel.S(:,involvedRxns(1))+irrevModel.S(:,involvedRxns(2))*stoichRatio;
-0268                 
-0269                 %Clear the second reaction
-0270                 irrevModel.S(:,involvedRxns(2))=0;
-0271                 
-0272                 %This is to prevent numerical issues. It should be 0
-0273                 %already
-0274                 irrevModel.S(common(i),involvedRxns(1))=0;
-0275                 
-0276                 %At this point the second reaction is certain to be deleted
-0277                 %in a later step and can therefore be ignored
-0278                 
-0279                 %Recalculate the bounds for the new reaction. This can be
-0280                 %problematic since the scale of the bounds may change
-0281                 %dramatically. Let the most constraining reaction determine
-0282                 %the new bound
-0283                 lb1=irrevModel.lb(involvedRxns(1));
-0284                 lb2=irrevModel.lb(involvedRxns(2));
-0285                 ub1=irrevModel.ub(involvedRxns(1));
-0286                 ub2=irrevModel.ub(involvedRxns(2));
-0287                 
-0288                 if lb2~=-inf
-0289                     irrevModel.lb(involvedRxns(1))=max(lb1,lb2/stoichRatio);
-0290                 end
-0291                 if ub2~=inf
-0292                     irrevModel.ub(involvedRxns(1))=min(ub1,ub2/stoichRatio);
-0293                 end
-0294                 
-0295                 %Then recalculate the objective coefficient. The resulting
-0296                 %coefficient is the weighted sum of the previous
-0297                 irrevModel.c(involvedRxns(1))=irrevModel.c(involvedRxns(1))+irrevModel.c(involvedRxns(2))*stoichRatio;
-0298                 
-0299                 %Iterate again
-0300                 mergedSome=true;
-0301             end
-0302         end
-0303         
-0304         %All possible reactions merged
-0305         if mergedSome==false
-0306             break;
-0307         end
-0308         
-0309         %Now delete all reactions that involve no metabolites
-0310         I=find(sum(irrevModel.S~=0)==0);
-0311         
-0312         %Remove reactions
-0313         irrevModel=removeReactions(irrevModel,I);
-0314         
-0315         %Remove metabolites
-0316         notInUse=sum(irrevModel.S~=0,2)==0;
-0317         irrevModel=removeMets(irrevModel,notInUse);
-0318     end
-0319     
-0320     reducedModel=irrevModel;
-0321 end
-0322 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/sortModel.html b/doc/core/sortModel.html deleted file mode 100644 index b14269dfc..000000000 --- a/doc/core/sortModel.html +++ /dev/null @@ -1,249 +0,0 @@ - - - - Description of sortModel - - - - - - - - - -
Home > core > sortModel.m
- - - -

sortModel -

- -

PURPOSE ^

-
sortModel
- -

SYNOPSIS ^

-
function model=sortModel(model,sortReversible,sortMetName,sortReactionOrder)
- -

DESCRIPTION ^

-
 sortModel
-   Sorts a model based on metabolite names and compartments
-
-   model             a model structure
-   sortReversible    sorts the reversible reactions so the the metabolite
-                     that is first in lexiographical order is a reactant
-                     (optional, default true)
-   sortMetName       sort the metabolite names in the equation, also uses
-                     compartment abbreviation (optional, default false)
-   sortReactionOrder sorts the reaction order within each subsystem so that
-                     reactions consuming some metabolite comes efter
-                     reactions producing it. This overrides the
-                     sortReversible option and reactions are sorted so that
-                     the production direction matches the consumption
-                     direction (optional, default false)
-
-   model             an updated model structure
-
- Usage: model=sortModel(model,sortReversible,sortMetName,sortReactionOrder)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function model=sortModel(model,sortReversible,sortMetName,sortReactionOrder)
-0002 % sortModel
-0003 %   Sorts a model based on metabolite names and compartments
-0004 %
-0005 %   model             a model structure
-0006 %   sortReversible    sorts the reversible reactions so the the metabolite
-0007 %                     that is first in lexiographical order is a reactant
-0008 %                     (optional, default true)
-0009 %   sortMetName       sort the metabolite names in the equation, also uses
-0010 %                     compartment abbreviation (optional, default false)
-0011 %   sortReactionOrder sorts the reaction order within each subsystem so that
-0012 %                     reactions consuming some metabolite comes efter
-0013 %                     reactions producing it. This overrides the
-0014 %                     sortReversible option and reactions are sorted so that
-0015 %                     the production direction matches the consumption
-0016 %                     direction (optional, default false)
-0017 %
-0018 %   model             an updated model structure
-0019 %
-0020 % Usage: model=sortModel(model,sortReversible,sortMetName,sortReactionOrder)
-0021 
-0022 if nargin<2
-0023     sortReversible=true;
-0024 end
-0025 if nargin<3
-0026     sortMetName=false;
-0027 end
-0028 if nargin<4
-0029     sortReactionOrder=false;
-0030 end
-0031 
-0032 if sortMetName==true
-0033     %Assuming that metComps are the indexes. Should be changed at one point
-0034     [~, metIndexes]=sort(strcat(model.metNames,'[',model.comps(model.metComps),']'));
-0035     model=permuteModel(model,metIndexes,'mets');
-0036 end
-0037 
-0038 if sortReversible==true && sortReactionOrder==false
-0039     %Get all reversible reactions
-0040     revIndexes=find(model.rev);
-0041     
-0042     %Loop through them
-0043     for i=1:numel(revIndexes)
-0044         %Create a cell array with all the metabolite names
-0045         mets=find(model.S(:,revIndexes(i)));
-0046         metNames=strcat(model.metNames(mets),model.comps(model.metComps(mets)));
-0047         
-0048         if iscellstr(metNames)
-0049             [~, indexes]=sort(metNames);
-0050             
-0051             if model.S(mets(indexes(1)),revIndexes(i))>0
-0052                 model.S(:,revIndexes(i))=model.S(:,revIndexes(i))*-1;
-0053             end
-0054         end
-0055     end
-0056 end
-0057 
-0058 if sortReactionOrder==true
-0059     %Check if the model has sub-systems, otherwise throw an error
-0060     if ~isfield(model,'subSystems')
-0061         EM='The model must contain a subSystems field in order to sort reaction order';
-0062         dispEM(EM);
-0063     end
-0064     
-0065     subsystemsUnique='';
-0066     subsystemsConcatenated='';
-0067     for i=1:numel(model.subSystems)
-0068         if ~iscell(model.subSystems{i})
-0069             model.subSystems{i} = {model.subSystems{i}};
-0070         end    
-0071         subsystemsConcatenated{i,1}=strjoin(model.subSystems{i,1},';');
-0072         if ~isempty(model.subSystems{i,1})
-0073             for j=1:numel(model.subSystems{i,1})
-0074                 subsystemsUnique{numel(subsystemsUnique)+1,1}=model.subSystems{i,1}{1,j};
-0075             end
-0076         end
-0077     end
-0078     subsystemsUnique=unique(subsystemsUnique);
-0079     for i=1:numel(subsystemsUnique)
-0080         %Get all reactions for that subsystem
-0081         rxns=find(~cellfun(@isempty,regexp(subsystemsConcatenated,subsystemsUnique(i))));
-0082         
-0083         %Temporarily ignore large subsystems because of inefficient
-0084         %implementation
-0085         if numel(rxns)<2 || numel(rxns)>250
-0086             continue;
-0087         end
-0088         
-0089         nRxns=numel(rxns);
-0090         revRxns=rxns(model.rev(rxns)~=0);
-0091         
-0092         %This variable will hold the current reversibility directions of
-0093         %the reversible reactions. 1 means the same direction as in the
-0094         %original model and -1 means the opposite direction.
-0095         oldRev=ones(numel(revRxns),1);
-0096         
-0097         %The problem could probably be solved analytically but a simple
-0098         %random method is implemented here instead. Two reactions are
-0099         %chosen randomly and their positions are switched. A score is
-0100         %calculated based on the number of metabolites that are produced
-0101         %before they are consumed. If the perturbed model has a better or
-0102         %equal score than the original the reaction order is switched. If
-0103         %no increase in score has been seen after 1000*rxnsInSubsystem then
-0104         %the optimization is terminated
-0105         
-0106         rxnOrder=1:nRxns;
-0107         oldScore=-inf;
-0108         counter=0;
-0109         firstIter=true;
-0110         while 1==1
-0111             counter=counter+1;
-0112             if counter==100*nRxns
-0113                 break;
-0114             end
-0115             
-0116             newRxnOrder=rxnOrder;
-0117             rev=oldRev;
-0118             
-0119             if firstIter==false
-0120                 y=randperm(nRxns,2);
-0121                 
-0122                 %Switch the order
-0123                 newRxnOrder(y(1))=rxnOrder(y(2));
-0124                 newRxnOrder(y(2))=rxnOrder(y(1));
-0125                 
-0126                 %With a 50% chance, also switch the reversibility of one of
-0127                 %the reactions
-0128                 if rand()>0.5 && numel(rev)>1
-0129                     n=randperm(numel(rev),1);
-0130                     rev(n)=rev(n)*-1;
-0131                 end
-0132             end
-0133             firstIter=false;
-0134             
-0135             tempS=model.S;
-0136             
-0137             %Switch the directionalities
-0138             for j=1:numel(rev)
-0139                 if rev(j)==-1
-0140                     tempS(:,revRxns(j))=tempS(:,revRxns(j)).*-1;
-0141                 end
-0142             end
-0143             
-0144             %Get the metabolites that are involved and when they are
-0145             %produced/consumed
-0146             s=tempS(:,newRxnOrder);
-0147             
-0148             %Remove mets that aren't used in both directions
-0149             s=s(any(s,2),:);
-0150             
-0151             %Add so that all mets are produced and consumed in the end
-0152             s=[s ones(size(s,1),1) ones(size(s,1),1)*-1];
-0153             
-0154             %For each metabolite, find the reaction where it's first
-0155             %produced and the reaction where it's first consumed
-0156             s1=s>0;
-0157             r1=arrayfun(@(x) find(s1(x,:),1,'first'),1:size(s1,1));
-0158             s2=s<0;
-0159             r2=arrayfun(@(x) find(s2(x,:),1,'first'),1:size(s2,1));
-0160             
-0161             score=sum(r1<r2);
-0162             
-0163             if score>=oldScore
-0164                 if score>oldScore
-0165                     counter=0;
-0166                 end
-0167                 oldScore=score;
-0168                 oldRev=rev;
-0169                 rxnOrder=newRxnOrder;
-0170             end
-0171         end
-0172         
-0173         %Update the model for this subsystem
-0174         for j=1:numel(oldRev)
-0175             if oldRev(j)==-1
-0176                 model.S(:,revRxns(j))=model.S(:,revRxns(j)).*-1;
-0177             end
-0178         end
-0179         order=1:numel(model.rxns);
-0180         order(rxns)=rxns(rxnOrder);
-0181         model=permuteModel(model, order, 'rxns');
-0182     end
-0183 end
-0184 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/core/standardizeGrRules.html b/doc/core/standardizeGrRules.html deleted file mode 100644 index b58d66bd5..000000000 --- a/doc/core/standardizeGrRules.html +++ /dev/null @@ -1,236 +0,0 @@ - - - - Description of standardizeGrRules - - - - - - - - - -
Home > core > standardizeGrRules.m
- - - -

standardizeGrRules -

- -

PURPOSE ^

-
standardizeGrRules
- -

SYNOPSIS ^

-
function [grRules,rxnGeneMat,indexes2check] = standardizeGrRules(model,embedded)
- -

DESCRIPTION ^

-
 standardizeGrRules
-   Standardizes gene-rxn rules in a model according to the following
-       - No overall containing brackets
-       - Just enzyme complexes are enclosed into brackets
-       - ' and ' & ' or ' strings are strictly set to lowercases
-
-   A rxnGeneMat matrix consistent with the standardized grRules is created.
-
-   model        a model structure
-   embedded     true if this function is called inside of another 
-                RAVEN function (optional, default false)
-
-   grRules      [nRxns x 1] cell array with the standardized grRules
-   rxnGeneMat   [nRxns x nGenes]Sparse matrix consitent with the
-                standardized grRules
-   
-   If this function is going to be used in a model reconstruction or
-   modification pipeline it is recommended to run this function just
-   at the beginning of the process.
-
- Usage: [grRules,rxnGeneMat,indexes2check]=standardizeGrRules(model,embedded)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 function [grRules,rxnGeneMat,indexes2check] = standardizeGrRules(model,embedded)
-0002 % standardizeGrRules
-0003 %   Standardizes gene-rxn rules in a model according to the following
-0004 %       - No overall containing brackets
-0005 %       - Just enzyme complexes are enclosed into brackets
-0006 %       - ' and ' & ' or ' strings are strictly set to lowercases
-0007 %
-0008 %   A rxnGeneMat matrix consistent with the standardized grRules is created.
-0009 %
-0010 %   model        a model structure
-0011 %   embedded     true if this function is called inside of another
-0012 %                RAVEN function (optional, default false)
-0013 %
-0014 %   grRules      [nRxns x 1] cell array with the standardized grRules
-0015 %   rxnGeneMat   [nRxns x nGenes]Sparse matrix consitent with the
-0016 %                standardized grRules
-0017 %
-0018 %   If this function is going to be used in a model reconstruction or
-0019 %   modification pipeline it is recommended to run this function just
-0020 %   at the beginning of the process.
-0021 %
-0022 % Usage: [grRules,rxnGeneMat,indexes2check]=standardizeGrRules(model,embedded)
-0023 
-0024 %Preallocate fields
-0025 n          = length(model.rxns);
-0026 [g,~]      = size(model.genes);
-0027 rxnGeneMat = sparse(n,g);
-0028 grRules    = cell(n,1);
-0029 genes      = model.genes;
-0030 if nargin<2
-0031     embedded = false;
-0032 end
-0033 
-0034 if isfield(model,'grRules')
-0035     originalGrRules=model.grRules; 
-0036     originalGrRules=grRulesPreparation(originalGrRules);
-0037     %Search for potential logical errors in the grRules field
-0038     indexes2check = findPotentialErrors(originalGrRules,embedded,model);
-0039     
-0040     for i=1:length(originalGrRules)
-0041         originalSTR = originalGrRules{i};
-0042         grRules{i,:}  = originalSTR;
-0043         %Non-empty grRules are splitted in all their different isoenzymes
-0044         genesSets   = getSimpleGeneSets(originalSTR);
-0045         rxnGeneMat  = modifyRxnGeneMat(genesSets,genes,rxnGeneMat,i);
-0046         %standardize the non-conflicting grRules
-0047         if ~ismember(i,indexes2check)
-0048             newSTR = [];
-0049             if ~isempty(genesSets)
-0050                 %For each simple genes set in the rule
-0051                 for j=1:length(genesSets)
-0052                     simpleSet  = genesSets{j};
-0053                     %Enclose simpleSet in brackets
-0054                     if length(genesSets)>1
-0055                         if ~isempty(strfind(simpleSet,' and '))
-0056                             simpleSet = horzcat('(',simpleSet,')');
-0057                         end
-0058                     end
-0059                     %Separate genesSets in the substring (in case of
-0060                     %isoenzymes)
-0061                     if j<length(genesSets)
-0062                         newSTR = [newSTR, simpleSet, ' or '];
-0063                         %Add the last simpleSet
-0064                     else
-0065                         newSTR = [newSTR, simpleSet];
-0066                     end
-0067                 end
-0068                 %Update grRule
-0069                 grRules{i} = char(newSTR);
-0070             end
-0071         end
-0072     end
-0073 else
-0074     error('The model does not have a grRules field.')
-0075 end
-0076 
-0077 end
-0078 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-0079 %Function that gets a cell array with all the simple geneSets in a given
-0080 %grRule string
-0081 function genesSets = getSimpleGeneSets(originalSTR)
-0082 genesSets  = [];
-0083 %If gene rule is not empty split in all its different isoenzymes
-0084 if ~isempty(originalSTR)
-0085     originalSTR = strtrim(originalSTR);
-0086     %Remove all brackets
-0087     originalSTR = strrep(originalSTR,'(','');
-0088     originalSTR = strrep(originalSTR,')','');
-0089     %Split all the different genesSets
-0090     genesSets  = transpose(strsplit(originalSTR,' or '));
-0091 end
-0092 end
-0093 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-0094 %Function that gets a cell array of simple genes sets (single genes or
-0095 %enzyme complexes) associated with the i-th reaction and modifies the
-0096 %correspondent row in the rxnGeneMat accordingly.
-0097 function rxnGeneMat = modifyRxnGeneMat(genesSets,modelGenes,rxnGeneMat,i)
-0098 
-0099 if ~isempty(genesSets)
-0100     for j=1:length(genesSets)
-0101         simpleSet  = genesSets{j};
-0102         %        rxnGeneMat = modifyRxnGeneMat(simpleSet,model.genes,rxnGeneMat,i);
-0103         %Get individual genes
-0104         STR   = strrep(simpleSet,') and (',' and ');
-0105         genes = strsplit(STR,' ');
-0106         for k=1:length(genes)
-0107             if ~strcmpi(genes(k),' and ')
-0108                 %Get gene index
-0109                 genePos = find(strcmpi(modelGenes,genes(k)));
-0110                 if ~isempty(genePos)
-0111                     rxnGeneMat(i,genePos) = 1;
-0112                     %else
-0113                     %In this case the gene should be added to the
-0114                     %genes field (and to all of its dependencies)
-0115                 end
-0116             end
-0117         end
-0118     end
-0119 end
-0120 end
-0121 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-0122 %Function that gets the model field grRules and returns the indexes of the
-0123 %rules in which the pattern ") and (" is present.
-0124 function indexes2check = findPotentialErrors(grRules,embedded,model)
-0125 indxs_l       = find(~cellfun(@isempty,strfind(grRules,') and (')));
-0126 indxs_l_L     = find(~cellfun(@isempty,strfind(grRules,') and')));
-0127 indxs_l_R     = find(~cellfun(@isempty,strfind(grRules,'and (')));
-0128 indexes2check = vertcat(indxs_l,indxs_l_L,indxs_l_R);
-0129 indexes2check = unique(indexes2check);
-0130 
-0131 if ~isempty(indexes2check)
-0132     
-0133     if ~embedded
-0134         STR = 'Potentially problematic ") AND (", ") AND" or "AND ("relat';
-0135         STR = [STR,'ionships found in\n\n'];
-0136         for i=1:length(indexes2check)
-0137             index = indexes2check(i);
-0138             STR = [STR '  - grRule #' model.rxns{index} ': ' grRules{index} '\n'];
-0139         end
-0140         STR = [STR,'\n This kind of relationships should only be present '];
-0141         STR = [STR,'in  reactions catalysed by complexes of isoenzymes e'];
-0142         STR = [STR,'.g.\n\n  - (G1 or G2) and (G3 or G4)\n\n For these c'];
-0143         STR = [STR,'ases modify the grRules manually, writing all the po'];
-0144         STR = [STR,'ssible combinations e.g.\n\n  - (G1 and G3) or (G1 a'];
-0145         STR = [STR,'nd G4) or (G2 and G3) or (G2 and G4)\n\n For other c'];
-0146         STR = [STR,'ases modify the correspondent grRules avoiding:\n\n '];
-0147         STR = [STR,' 1) Overall container brackets, e.g.\n        "(G1 a'];
-0148         STR = [STR,'nd G2)" should be "G1 and G2"\n\n  2) Single unit en'];
-0149         STR = [STR,'zymes enclosed into brackets, e.g.\n        "(G1)" s'];
-0150         STR = [STR,'hould be "G1"\n\n  3) The use of uppercases for logi'];
-0151         STR = [STR,'cal operators, e.g.\n        "G1 OR G2" should be "G'];
-0152         STR = [STR,'1 or G2"\n\n  4) Unbalanced brackets, e.g.\n        '];
-0153         STR = [STR,'"((G1 and G2) or G3" should be "(G1 and G2) or G3"\n'];
-0154         warning(sprintf(STR))
-0155     end
-0156 end
-0157 end
-0158 
-0159 function grRules = grRulesPreparation(grRules)
-0160 %Remove unnecessary blanks
-0161 grRules=strrep(grRules,'  ',' ');
-0162 grRules=strrep(grRules,'( ','(');
-0163 grRules=strrep(grRules,' )',')');
-0164 % Make sure that AND and OR strings are in lowercase
-0165 grRules=strrep(grRules,' AND ',' and ');
-0166 grRules=strrep(grRules,' OR ',' or ');
-0167 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/demoicon.gif b/doc/demoicon.gif deleted file mode 100644 index c89e7acbc2a74f36f35d2ba23cdd095366563205..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 214 zcmZ?wbhEHb6krfwIKlt||NsBz;1LK4_4@xG$Oe)@|Nlq*|KIZe|D6B-*Z%*1?f?IK z|Nno#cAjDHE{X4-EuTMj+Ph8S`+Kir`@EcN1dbivDF(pUKia5*{N xtO-?WJ(Rf1$C7KR)AZ0H0j(>SR=H$6kJ)6-DZGJ)<+b45x|97Z4cdwf)&TUlSJMCh diff --git a/doc/down.png b/doc/down.png deleted file mode 100644 index d41104a26f3d09deda6ab54281affd82c981abb1..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 133 zcmeAS@N?(olHy`uVBq!ia0vp^{2gTe~DWM4fiX0)Z diff --git a/doc/doxysearch.php b/doc/doxysearch.php deleted file mode 100644 index 36112a426..000000000 --- a/doc/doxysearch.php +++ /dev/null @@ -1,329 +0,0 @@ -$word, - "match"=>$w, - "index"=>$statIdx, - "full"=>strlen($w)==strlen($word), - "docs"=>array() - ); - } - $w = readString($file); - } - $totalFreq=0; - for ($count=$start;$count$idx,"freq"=>$freq,"rank"=>0.0); - $totalFreq+=$freq; - if ($statInfo["full"]) $totalfreq+=$freq; - } - // read name an url info for the doc - for ($i=0;$i<$numDocs;$i++) - { - fseek($file,$docInfo[$i]["idx"]); - $docInfo[$i]["name"]=readString($file); - $docInfo[$i]["url"]=readString($file); - } - $statInfo["docs"]=$docInfo; - } - for ($count=$start;$count$key, - "name"=>$di["name"], - "rank"=>$rank - ); - } - $docs[$key]["words"][] = array( - "word"=>$wordInfo["word"], - "match"=>$wordInfo["match"], - "freq"=>$di["freq"] - ); - } - } - return $docs; -} - -function normalize_ranking(&$docs) -{ - $maxRank = 0.0000001; - // compute maximal rank - foreach ($docs as $doc) - { - if ($doc["rank"]>$maxRank) - { - $maxRank=$doc["rank"]; - } - } - reset($docs); - // normalize rankings - while (list ($key, $val) = each ($docs)) - { - $docs[$key]["rank"]*=100/$maxRank; - } -} - -function filter_results($docs,&$requiredWords,&$forbiddenWords) -{ - $filteredDocs=array(); - while (list ($key, $val) = each ($docs)) - { - $words = &$docs[$key]["words"]; - $copy=1; // copy entry by default - if (sizeof($requiredWords)>0) - { - foreach ($requiredWords as $reqWord) - { - $found=0; - foreach ($words as $wordInfo) - { - $found = $wordInfo["word"]==$reqWord; - if ($found) break; - } - if (!$found) - { - $copy=0; // document contains none of the required words - break; - } - } - } - if (sizeof($forbiddenWords)>0) - { - foreach ($words as $wordInfo) - { - if (in_array($wordInfo["word"],$forbiddenWords)) - { - $copy=0; // document contains a forbidden word - break; - } - } - } - if ($copy) $filteredDocs[$key]=$docs[$key]; - } - return $filteredDocs; -} - -function compare_rank($a,$b) -{ - return ($a["rank"]>$b["rank"]) ? -1 : 1; -} - -function sort_results($docs,&$sorted) -{ - $sorted = $docs; - usort($sorted,"compare_rank"); - return $sorted; -} - -function report_results(&$docs) -{ - echo "\n"; - echo " \n"; - echo " \n"; - echo " \n"; - $numDocs = sizeof($docs); - if ($numDocs==0) - { - echo " \n"; - echo " \n"; - echo " \n"; - } - else - { - echo " \n"; - echo " \n"; - echo " \n"; - $num=1; - foreach ($docs as $doc) - { - echo " \n"; - echo " "; - echo "\n"; - echo " \n"; - echo " \n"; - echo " \n"; - $num++; - } - } - echo "

Search Results

".matches_text(0)."
".matches_text($numDocs); - echo "\n"; - echo "
$num.".$doc["name"]."
Matches: "; - foreach ($doc["words"] as $wordInfo) - { - $word = $wordInfo["word"]; - $matchRight = substr($wordInfo["match"],strlen($word)); - echo "$word$matchRight(".$wordInfo["freq"].") "; - } - echo "
\n"; -} - -function matches_text($num) -{ - if ($num==0) - { - return 'Sorry, no documents matching your query.'; - } - else if ($num==1) - { - return 'Found 1 document matching your query.'; - } - else // $num>1 - { - return 'Found '.$num.' documents matching your query. Showing best matches first.'; - } -} - -function main($idxfile) -{ - if(strcmp('4.1.0', phpversion()) > 0) - { - die("Error: PHP version 4.1.0 or above required!"); - } - if (!($file=fopen($idxfile,"rb"))) - { - die("Error: Search index file could NOT be opened!"); - } - if (readHeader($file)!="DOXS") - { - die("Error: Header of index file is invalid!"); - } - $query=""; - if (array_key_exists("query", $_GET)) - { - $query=$_GET["query"]; - } - $results = array(); - $requiredWords = array(); - $forbiddenWords = array(); - $foundWords = array(); - $word=strtolower(strtok($query," ")); - while ($word) // for each word in the search query - { - if (($word{0}=='+')) { $word=substr($word,1); $requiredWords[]=$word; } - if (($word{0}=='-')) { $word=substr($word,1); $forbiddenWords[]=$word; } - if (!in_array($word,$foundWords)) - { - $foundWords[]=$word; - search($file,$word,$results); - } - $word=strtolower(strtok(" ")); - } - $docs = array(); - combine_results($results,$docs); - // filter out documents with forbidden word or that do not contain - // required words - $filteredDocs = filter_results($docs,$requiredWords,$forbiddenWords); - // normalize rankings so they are in the range [0-100] - normalize_ranking($filteredDocs); - // sort the results based on rank - $sorted = array(); - sort_results($filteredDocs,$sorted); - // report results to the user - report_results($sorted); - fclose($file); -} - -?> diff --git a/doc/external/combineMetaCycKEGGModels.html b/doc/external/combineMetaCycKEGGModels.html deleted file mode 100644 index c9cc74ad1..000000000 --- a/doc/external/combineMetaCycKEGGModels.html +++ /dev/null @@ -1,380 +0,0 @@ - - - - Description of combineMetaCycKEGGModels - - - - - - - - - -
Home > external > combineMetaCycKEGGModels.m
- - - -

combineMetaCycKEGGModels -

- -

PURPOSE ^

-
combineMetaCycKEGGModels
- -

SYNOPSIS ^

-
function model=combineMetaCycKEGGModels(metacycModel,keggModel)
- -

DESCRIPTION ^

-
 combineMetaCycKEGGModels
-    Combine MetaCyc and KEGG draft models into one model structure.
-
-    Input:
-    metacycModel    the reconstructed model from MetaCyc
-    keggModel       the reconstructed model from KEGG
-
-    Output:
-    model           a model structure generated by integrating information
-                   from draft models reconstructed using MetaCyc and KEGG
-                   databases. The 'rxnFrom/metFrom/geneFrom' fields are
-                   included to indicate the source.
-
-    Usage: model=combineMetaCycKEGGModels(metacycModel,keggModel)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function model=combineMetaCycKEGGModels(metacycModel,keggModel)
-0002 % combineMetaCycKEGGModels
-0003 %    Combine MetaCyc and KEGG draft models into one model structure.
-0004 %
-0005 %    Input:
-0006 %    metacycModel    the reconstructed model from MetaCyc
-0007 %    keggModel       the reconstructed model from KEGG
-0008 %
-0009 %    Output:
-0010 %    model           a model structure generated by integrating information
-0011 %                   from draft models reconstructed using MetaCyc and KEGG
-0012 %                   databases. The 'rxnFrom/metFrom/geneFrom' fields are
-0013 %                   included to indicate the source.
-0014 %
-0015 %    Usage: model=combineMetaCycKEGGModels(metacycModel,keggModel)
-0016 
-0017 %Just return the model
-0018 if nargin<2
-0019     disp('Missing input model');
-0020     return;
-0021 end
-0022 
-0023 %Add MetaCyc model as template
-0024 model=metacycModel;
-0025 model.id='COMBINED';
-0026 model.name='Combined model from MetaCyc and KEGG draft models';
-0027 
-0028 %Use MetaCyc model as template
-0029 model.rxnFrom=cell(numel(model.rxns),1);
-0030 model.rxnFrom(:)={'MetaCyc'};
-0031 model.metFrom=cell(numel(model.mets),1);
-0032 model.metFrom(:)={'MetaCyc'};
-0033 model.geneFrom=cell(numel(model.genes),1);
-0034 model.geneFrom(:)={'MetaCyc'};
-0035 model.grRulesKEGG=cell(numel(model.rxns),1);
-0036 model.grRulesKEGG(:)={''};
-0037 
-0038 %Remove the S and rxnGeneMat matrix
-0039 if isfield(model,'S')
-0040     model=rmfield(model,'S');
-0041 end
-0042 if isfield(model,'rxnGeneMat')
-0043     model=rmfield(model,'rxnGeneMat');
-0044 end
-0045 
-0046 %Arrange the genes related fields
-0047 
-0048 %Identify the shared genes between KEGG and MetaCyc
-0049 sharedGenes=intersect(keggModel.genes,model.genes);
-0050 [~, b]=ismember(sharedGenes,model.genes);
-0051 model.geneFrom(b)={'Both'};
-0052 
-0053 %Add unique genes from KEGG and update geneFrom
-0054 C=setdiff(keggModel.genes,model.genes);
-0055 model.genes=[model.genes;C];
-0056 geneFrom=cell(numel(C),1);
-0057 geneFrom(:)={'KEGG'};
-0058 model.geneFrom=[model.geneFrom;geneFrom];
-0059 
-0060 %Prepare for matching grRules
-0061 if isfield(keggModel,'grRules')
-0062     keggModel.grRules=strrep(keggModel.grRules,'(','');
-0063     keggModel.grRules=strrep(keggModel.grRules,')','');
-0064 end
-0065 
-0066 %Replace rxns in KEGG model with the corresponding ones in MetaCyc by
-0067 %updating values rxns field to MetaCyc version whenever possible
-0068 
-0069 %Collect the ones found in MetaCyc as mappedRxns
-0070 mappedRxns=[];
-0071 rxnsToMove=[];
-0072 grRulesToMove={}; %Storing the grRules to be moved to MetaCyc model
-0073 
-0074 %Read in dbLinks, note that linkMetaCycKEGGRxns need to be run in advance
-0075 load('metaCycRxns.mat');
-0076 num=0;
-0077 numToMove=0;
-0078 %Loop through the KEGG model and replace the rxn id from KEGG to MetaCyc
-0079 %version
-0080 for i=1:numel(keggModel.rxns)
-0081     [~, b]=ismember(rxnLinks.kegg,keggModel.rxns{i});
-0082     I=find(b);
-0083     
-0084     if numel(I)==1
-0085         %Find out the corresponding MetaCyc reactions
-0086         num=num+1;
-0087         %Record the mapped rxn index in KEGG model and remove them later
-0088         mappedRxns=[mappedRxns,i];
-0089         %keggModel.rxns{i}=rxnLinks.metacyc{I(1)};
-0090         
-0091         [c, d]=ismember(rxnLinks.metacyc{I(1)},model.rxns);
-0092         if c
-0093             model.rxnFrom{d}='Both';
-0094             %Combine the grRule info Check if KEGG grRules equals or a
-0095             %subset of MetaCyc grRules If not, save the KEGG grRules to a
-0096             %new field grRulesKEGG for manual curation
-0097             k=strfind(model.grRules{d},keggModel.grRules{i});
-0098             if isempty(k)
-0099                 if isempty(model.grRulesKEGG{d})
-0100                     model.grRulesKEGG{d}=keggModel.grRules{i};
-0101                 else
-0102                     model.grRulesKEGG{d}=strcat(model.grRulesKEGG{d},{' or '},keggModel.grRules{i});
-0103                 end
-0104             end
-0105         else
-0106             %For the KEGG rxns have MetaCyc version but not in MetaCyc
-0107             %draft model
-0108             [~, y]=ismember(rxnLinks.metacyc{I(1)},metaCycRxns.rxns);
-0109             
-0110             %Check if this reaction is repitetive and save the grRules
-0111             [Repeat, Index]=ismember(y,rxnsToMove);
-0112             if ~Repeat
-0113                 rxnsToMove=[rxnsToMove;y];  %Record rxns to be moved from KEGG to MetaCyc model
-0114                 if isempty(keggModel.grRules{i})
-0115                     %Rxns may have empty grRules (e.g. spontaneous) that
-0116                     %are identified and added back here
-0117                     grRulesToMove=[grRulesToMove;{''}];
-0118                 else
-0119                     grRulesToMove=[grRulesToMove;keggModel.grRules{i}];
-0120                 end
-0121                 numToMove=numToMove+1;
-0122             else
-0123                 %If this reaction has been recorded, append the grRules if
-0124                 %it is different
-0125                 k=strfind(grRulesToMove{Index},keggModel.grRules{i});
-0126                 if isempty(k)
-0127                     grRulesToMove{Index}=strcat(grRulesToMove{Index},{' or '},keggModel.grRules{i});
-0128                 end
-0129             end
-0130         end
-0131     else
-0132         %Here are the case of one KEGG rxn id link to several MetaCyc ids
-0133         %for j=2:numel(I) Ignore this issue for now, and resolve it later,
-0134         %because it never happened This case can be solved by adding above
-0135         %section into a loop below disp(I(j)); end
-0136     end
-0137 end
-0138 fprintf('NOTE: A total of %d reactions in the KEGG model were mapped to MetaCyc.\n',num);
-0139 fprintf('NOTE: %d reactions already in MetaCyc model, %d will be combined.\n',num-numToMove,numToMove);
-0140 
-0141 %Append mapped MetaCyc rxns in KEGG model that are absent from MetaCyc
-0142 %model
-0143 rxnFrom=cell(numel(rxnsToMove),1);
-0144 rxnFrom(:)={'KEGG'};
-0145 model.rxnFrom=[model.rxnFrom;rxnFrom];
-0146 model.rxns=[model.rxns;metaCycRxns.rxns(rxnsToMove)];
-0147 
-0148 rxnNames=metaCycRxns.rxnNames(rxnsToMove);
-0149 %Replace rxnNames with those from metaCycEnzymes
-0150 load('metaCycEnzymes.mat');
-0151 for i=1:numel(rxnsToMove)
-0152     [a, b]=ismember(metaCycRxns.rxns{rxnsToMove(i)},metaCycEnzymes.rxns);
-0153     if a
-0154         rxnNames{i}=metaCycEnzymes.rxnNames{b};
-0155     end
-0156 end
-0157 model.rxnNames=[model.rxnNames;rxnNames];
-0158 
-0159 model.eccodes=[model.eccodes;metaCycRxns.eccodes(rxnsToMove)];
-0160 model.subSystems=[model.subSystems;metaCycRxns.subSystems(rxnsToMove)];
-0161 model.rxnMiriams=[model.rxnMiriams;metaCycRxns.rxnMiriams(rxnsToMove)];
-0162 model.rxnReferences=[model.rxnReferences;metaCycRxns.rxnReferences(rxnsToMove)];
-0163 model.rev=[model.rev;metaCycRxns.rev(rxnsToMove)];
-0164 model.equations=[model.equations;metaCycRxns.equations(rxnsToMove)];
-0165 model.lb=[model.lb;metaCycRxns.lb(rxnsToMove)];
-0166 model.ub=[model.ub;metaCycRxns.ub(rxnsToMove)];
-0167 model.c=[model.c;metaCycRxns.c(rxnsToMove)];
-0168 model.grRules=[model.grRules;grRulesToMove];
-0169 %model.grRules=[model.grRules;keggModel.grRules(rxnsToMove(:,2))];
-0170 %model.grRulesKEGG=[model.grRulesKEGG;keggModel.grRules(rxnsToMove(:,2))];
-0171 rxnFields=cell(numel(rxnsToMove),1);
-0172 rxnFields(:)={''};
-0173 %model.rxnNotes=[model.rxnNotes;rxnFields];
-0174 model.grRulesKEGG=[model.grRulesKEGG;rxnFields];
-0175 
-0176 %Remove all mapped reactions from KEGG model
-0177 pureKeggModel=removeReactions(keggModel,mappedRxns,true,true);
-0178 fprintf('NOTE: A global KEGG model with %d reactions and %d metabolites was obtained.\n',numel(pureKeggModel.rxns),numel(pureKeggModel.mets));
-0179 
-0180 %Replace mets information in KEGG model with the corresponding ones in
-0181 %MetaCyc This includes updating all metabolite-related fields, except S
-0182 %matrix.
-0183 load('metaCycMets.mat');
-0184 
-0185 if ~isfield(pureKeggModel,'metCharges')
-0186     pureKeggModel.metCharges=NaN(numel(pureKeggModel.mets),1);
-0187 end
-0188 
-0189 num=0;
-0190 for i=1:numel(pureKeggModel.mets)
-0191     [a, b]=ismember(pureKeggModel.mets{i},metaCycMets.keggid);
-0192     if a
-0193         %For now only replace the met ids
-0194         num=num+1;
-0195         pureKeggModel.mets{i}=metaCycMets.mets{b};
-0196         %Record the replaced mets into a vector for later
-0197     end
-0198 end
-0199 fprintf('NOTE: A total of %d metabolites from the global KEGG model will be re-mapped to MetaCyc.\n',num);
-0200 
-0201 %Generate equations for pureKeggModel
-0202 equationStrings=constructEquations(pureKeggModel,'',false,false,false,true);
-0203 
-0204 %Add the pure KEGG reactions to MetaCyc model
-0205 rxnFrom=cell(numel(pureKeggModel.rxns),1);
-0206 rxnFrom(:)={'KEGG'};
-0207 model.rxnFrom=[model.rxnFrom;rxnFrom];
-0208 model.rxns=[model.rxns;pureKeggModel.rxns];
-0209 model.equations=[model.equations;equationStrings];
-0210 model.rxnNames=[model.rxnNames;pureKeggModel.rxnNames];
-0211 model.eccodes=[model.eccodes;pureKeggModel.eccodes];
-0212 model.subSystems=[model.subSystems;pureKeggModel.subSystems];
-0213 model.rxnMiriams=[model.rxnMiriams;pureKeggModel.rxnMiriams];
-0214 model.rev=[model.rev;pureKeggModel.rev];
-0215 model.lb=[model.lb;pureKeggModel.lb];
-0216 model.ub=[model.ub;pureKeggModel.ub];
-0217 model.c=[model.c;pureKeggModel.c];
-0218 model.grRules=[model.grRules;pureKeggModel.grRules];
-0219 rxnFields=cell(numel(pureKeggModel.rxns),1);
-0220 rxnFields(:)={''};
-0221 model.grRulesKEGG=[model.grRulesKEGG;rxnFields];
-0222 model.rxnReferences=[model.rxnReferences;rxnFields];
-0223 %model.rxnNotes=[model.rxnNotes;rxnFields];
-0224 
-0225 %It could also be that the metabolite and reaction names are empty for some
-0226 %reasons. In that case, use the ID instead
-0227 %I=cellfun(@isempty,model.metNames); model.metNames(I)=model.mets(I);
-0228 I=cellfun(@isempty,model.rxnNames);
-0229 model.rxnNames(I)=model.rxns(I);
-0230 
-0231 %Generate S matrix and mets
-0232 [S, mets, ~]=constructS(model.equations);
-0233 model.S=S;
-0234 model.mets=mets;
-0235 
-0236 %Remap metabolite information
-0237 if isfield(model,'metFrom')
-0238     model=rmfield(model,'metFrom');
-0239 end
-0240 model.metFrom=cell(numel(model.mets),1);
-0241 model.metFrom(:)={''};
-0242 
-0243 if isfield(model,'metNames')
-0244     model=rmfield(model,'metNames');
-0245 end
-0246 model.metNames=cell(numel(model.mets),1);
-0247 model.metNames(:)={''};
-0248 
-0249 if isfield(model,'metFormulas')
-0250     model=rmfield(model,'metFormulas');
-0251 end
-0252 model.metFormulas=cell(numel(model.mets),1);
-0253 model.metFormulas(:)={''};
-0254 
-0255 if ~isfield(model,'metCharges')
-0256     model=rmfield(model,'metCharges');
-0257 end
-0258 model.metCharges=NaN(numel(model.mets),1);
-0259 
-0260 if ~isfield(model,'inchis')
-0261     model=rmfield(model,'inchis');
-0262 end
-0263 model.inchis=cell(numel(model.mets),1);
-0264 model.inchis(:)={''};
-0265 
-0266 if ~isfield(model,'metMiriams')
-0267     model=rmfield(model,'metMiriams');
-0268 end
-0269 model.metMiriams=cell(numel(model.mets),1);
-0270 model.metMiriams(:)={''};
-0271 
-0272 keggMets=getMetsFromKEGG();
-0273 for i=1:numel(model.mets)
-0274     [a, b]=ismember(model.mets{i},metaCycMets.mets);
-0275     if a
-0276         %Replace the met related info
-0277         model.mets{i}=metaCycMets.mets{b};
-0278         model.metNames{i}=metaCycMets.metNames{b};
-0279         model.metFormulas{i}=metaCycMets.metFormulas{b};
-0280         model.metMiriams{i}=metaCycMets.metMiriams{b};
-0281         model.inchis{i}=metaCycMets.inchis{b};
-0282         model.metCharges(i,1)=metaCycMets.metCharges(b,1);
-0283         num=num+1;
-0284     else
-0285         [c, d]=ismember(model.mets{i},keggMets.mets);
-0286         if c
-0287             model.mets{i}=keggMets.mets{d};
-0288             model.metNames{i}=keggMets.metNames{d};
-0289             model.metFormulas{i}=keggMets.metFormulas{d};
-0290             model.metMiriams{i}=keggMets.metMiriams{d};
-0291             model.inchis{i}=keggMets.inchis{d};
-0292             num=num+1;
-0293         end
-0294     end
-0295     
-0296 end
-0297 
-0298 %It could also be that the metabolite and reaction names are empty for some
-0299 %reasons. In that case, use the ID instead
-0300 I=cellfun(@isempty,model.metNames);
-0301 model.metNames(I)=model.mets(I);
-0302 
-0303 %Add confidenceScores to model in a rough way
-0304 if isfield(model,'rxnConfidenceScores')
-0305     model=rmfield(model,'rxnConfidenceScores');
-0306 end
-0307 model.rxnConfidenceScores=NaN(numel(model.rxns),1);
-0308 model.rxnConfidenceScores(:)=2;
-0309 
-0310 %Put all metabolites in one compartment called 's' (for system). This is
-0311 %done just to be more compatible with the rest of the code
-0312 model.comps={'s'};
-0313 model.compNames={'System'};
-0314 model.metComps=ones(numel(model.mets),1);
-0315 model.b=zeros(numel(model.mets),1);
-0316 
-0317 %Create the new rxnGene matrix, get back to this later
-0318 model.rxnGeneMat=sparse(numel(model.rxns),numel(model.genes));
-0319 
-0320 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/external/getBlast.html b/doc/external/getBlast.html deleted file mode 100644 index 4c6294904..000000000 --- a/doc/external/getBlast.html +++ /dev/null @@ -1,267 +0,0 @@ - - - - Description of getBlast - - - - - - - - - -
Home > external > getBlast.m
- - - -

getBlast -

- -

PURPOSE ^

-
getBlast
- -

SYNOPSIS ^

-
function [blastStructure,blastReport]=getBlast(organismID,fastaFile,modelIDs,refFastaFiles,developMode,hideVerbose)
- -

DESCRIPTION ^

-
 getBlast
-   Performs a bidirectional BLAST between the organism of interest and a
-   set of template organisms
-
-   Input:
-   organismID      the id of the organism of interest. This should also
-                   match with the id supplied to getModelFromHomology
-   fastaFile       a FASTA file with the protein sequences for the
-                   organism of interest
-   modelIDs        a cell array of model ids. These must match the
-                   "model.id" fields in the "models" structure if the
-                   output is to be used with getModelFromHomology
-   refFastaFiles   a cell array with the paths to the corresponding FASTA
-                   files
-   developMode     true if blastReport should be generated that is used
-                   in the unit testing function for BLAST+ (optional, default
-                   false)
-   hideVerbose     true if no status messages should be printed (optional,
-                   default false)
-
-   Output:
-   blastStructure  structure containing the bidirectional homology
-                   measurements that can be used by getModelFromHomology
-   blastReport     structure containing MD5 hashes for FASTA database
-                   files and non-parsed BLAST output data. Will be blank
-                   if developMode is false.
-
-   NOTE: This function calls BLAST+ to perform a bidirectional homology
-   test between the organism of interest and a set of other organisms
-   using standard settings. The only filtering this function does is the
-   removal of hits with an E-value higher than 10e-5. The other homology
-   measurements can be implemented using getBlastFromExcel.
-
- Usage: [blastStructure,blastReport]=getBlast(organismID,fastaFile,...
-    modelIDs,refFastaFiles,developMode,hideVerbose)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function [blastStructure,blastReport]=getBlast(organismID,fastaFile,...
-0002     modelIDs,refFastaFiles,developMode,hideVerbose)
-0003 % getBlast
-0004 %   Performs a bidirectional BLAST between the organism of interest and a
-0005 %   set of template organisms
-0006 %
-0007 %   Input:
-0008 %   organismID      the id of the organism of interest. This should also
-0009 %                   match with the id supplied to getModelFromHomology
-0010 %   fastaFile       a FASTA file with the protein sequences for the
-0011 %                   organism of interest
-0012 %   modelIDs        a cell array of model ids. These must match the
-0013 %                   "model.id" fields in the "models" structure if the
-0014 %                   output is to be used with getModelFromHomology
-0015 %   refFastaFiles   a cell array with the paths to the corresponding FASTA
-0016 %                   files
-0017 %   developMode     true if blastReport should be generated that is used
-0018 %                   in the unit testing function for BLAST+ (optional, default
-0019 %                   false)
-0020 %   hideVerbose     true if no status messages should be printed (optional,
-0021 %                   default false)
-0022 %
-0023 %   Output:
-0024 %   blastStructure  structure containing the bidirectional homology
-0025 %                   measurements that can be used by getModelFromHomology
-0026 %   blastReport     structure containing MD5 hashes for FASTA database
-0027 %                   files and non-parsed BLAST output data. Will be blank
-0028 %                   if developMode is false.
-0029 %
-0030 %   NOTE: This function calls BLAST+ to perform a bidirectional homology
-0031 %   test between the organism of interest and a set of other organisms
-0032 %   using standard settings. The only filtering this function does is the
-0033 %   removal of hits with an E-value higher than 10e-5. The other homology
-0034 %   measurements can be implemented using getBlastFromExcel.
-0035 %
-0036 % Usage: [blastStructure,blastReport]=getBlast(organismID,fastaFile,...
-0037 %    modelIDs,refFastaFiles,developMode,hideVerbose)
-0038 
-0039 if nargin<5
-0040     developMode = false;
-0041 end
-0042 if nargin<6
-0043     hideVerbose = false;
-0044 end
-0045 
-0046 %Everything should be cell arrays
-0047 organismID=convertCharArray(organismID);
-0048 fastaFile=convertCharArray(fastaFile);
-0049 modelIDs=convertCharArray(modelIDs);
-0050 refFastaFiles=convertCharArray(refFastaFiles);
-0051 
-0052 %Create blank structures for results
-0053 blastStructure=[];
-0054 blastReport.dbHashes.phr={};
-0055 blastReport.dbHashes.pot={};
-0056 blastReport.dbHashes.psq={};
-0057 blastReport.dbHashes.pto={};
-0058 blastReport.blastTxtOutput={};
-0059 
-0060 %Get the directory for RAVEN Toolbox
-0061 ravenPath=findRAVENroot();
-0062 
-0063 %Generate temporary names for BLAST databases and output files
-0064 tmpDB=tempname;
-0065 outFile=tempname;
-0066 if ispc && contains(tmpDB,' ')
-0067     warning(['MATLAB assigned ''%s'' as temporary file path, but it '...
-0068              'contains a space character, which is not compatible with '...
-0069              'BLAST. Instead, a temporary folder will be initiated at '...
-0070              '''C:\\tempRAVEN\\'' which should manually be removed when '...
-0071              'finished.'],tmpDB)
-0072     tmpDB=tempname('C:\tempRAVEN');
-0073     outFile=tempname('C:\tempRAVEN');
-0074 end
-0075 
-0076 %Check for existence of files. If no full path is specified for a file,
-0077 %assume that it is in the current folder
-0078 if isrow(refFastaFiles)
-0079     files=horzcat(fastaFile,refFastaFiles);
-0080 else
-0081     files=vertcat(fastaFile,refFastaFiles);
-0082 end
-0083 
-0084 files=checkFileExistence(files,2); %Copy files to temp dir
-0085 fastaFile = files(1);
-0086 refFastaFiles = files(2:end);
-0087 
-0088 %Identify the operating system
-0089 if isunix
-0090     if ismac
-0091         binEnd='.mac';
-0092     else
-0093         binEnd='';
-0094     end
-0095 elseif ispc
-0096     binEnd='.exe';
-0097     setenv('BLASTDB_LMDB_MAP_SIZE','1000000');
-0098 else
-0099     dispEM('Unknown OS, exiting.')
-0100     return
-0101 end
-0102 
-0103 %Run BLAST multi-threaded to use all logical cores assigned to MATLAB
-0104 cores = evalc('feature(''numcores'')');
-0105 cores = strsplit(cores, 'MATLAB was assigned: ');
-0106 cores = regexp(cores{2},'^\d*','match');
-0107 cores = cores{1};
-0108 
-0109 %Create a database for the new organism and blast each of the refFastaFiles
-0110 %against it
-0111 [status, message]=system(['"' fullfile(ravenPath,'software','blast+',['makeblastdb' binEnd]) '" -in "' fastaFile{1} '" -out "' fullfile(tmpDB, 'tmpDB') '" -dbtype prot']);
-0112 if developMode
-0113     blastReport.dbHashes.phr{numel(blastReport.dbHashes.phr)+1}=getMD5Hash(fullfile(tmpDB, 'tmpDB.phr'));
-0114     blastReport.dbHashes.pot{numel(blastReport.dbHashes.pot)+1}=getMD5Hash(fullfile(tmpDB, 'tmpDB.pot'));
-0115     blastReport.dbHashes.psq{numel(blastReport.dbHashes.psq)+1}=getMD5Hash(fullfile(tmpDB, 'tmpDB.psq'));
-0116     blastReport.dbHashes.pto{numel(blastReport.dbHashes.pto)+1}=getMD5Hash(fullfile(tmpDB, 'tmpDB.pto'));
-0117 end
-0118 if status~=0
-0119     error('makeblastdb did not run successfully, error:\n%s',strip(message))
-0120 end
-0121 
-0122 for i=1:numel(refFastaFiles)
-0123     if ~hideVerbose
-0124         fprintf(['BLASTing "' modelIDs{i} '" against "' organismID{1} '"..\n']);
-0125     end
-0126     [status, message]=system(['"' fullfile(ravenPath,'software','blast+',['blastp' binEnd]) '" -query "' refFastaFiles{i} '" -out "' outFile '_' num2str(i) '" -db "' fullfile(tmpDB, 'tmpDB') '" -evalue 10e-5 -outfmt "10 qseqid sseqid evalue pident length bitscore ppos" -num_threads "' cores '"']);
-0127     if developMode
-0128         blastReport.blastTxtOutput{numel(blastReport.blastTxtOutput)+1}=importdata([outFile '_' num2str(i)]);
-0129     end
-0130     if status~=0
-0131         error('blastp did not run successfully, error:\n%s',strip(message))
-0132     end
-0133 end
-0134 delete([tmpDB filesep 'tmpDB*']);
-0135 
-0136 %Then create a database for each of the reference organisms and blast the
-0137 %new organism against them
-0138 for i=1:numel(refFastaFiles)
-0139     if ~hideVerbose
-0140         fprintf(['BLASTing "' organismID{1} '" against "' modelIDs{i} '"..\n']);
-0141     end
-0142     [status, message]=system(['"' fullfile(ravenPath,'software','blast+',['makeblastdb' binEnd]) '" -in "' refFastaFiles{i} '" -out "' fullfile(tmpDB, 'tmpDB') '" -dbtype prot']);
-0143     if status~=0
-0144         error('makeblastdb did not run successfully, error:\n%s',strip(message))
-0145     end
-0146     [status, message]=system(['"' fullfile(ravenPath,'software','blast+',['blastp' binEnd]) '" -query "' fastaFile{1} '" -out "' outFile '_r' num2str(i) '" -db "' fullfile(tmpDB, 'tmpDB') '" -evalue 10e-5 -outfmt "10 qseqid sseqid evalue pident length bitscore ppos" -num_threads "' cores '"']);
-0147     if developMode
-0148         blastReport.dbHashes.phr{numel(blastReport.dbHashes.phr)+1}=getMD5Hash(fullfile(tmpDB, 'tmpDB.phr'));
-0149         blastReport.dbHashes.pot{numel(blastReport.dbHashes.pot)+1}=getMD5Hash(fullfile(tmpDB, 'tmpDB.pot'));
-0150         blastReport.dbHashes.psq{numel(blastReport.dbHashes.psq)+1}=getMD5Hash(fullfile(tmpDB, 'tmpDB.psq'));
-0151         blastReport.dbHashes.pto{numel(blastReport.dbHashes.pto)+1}=getMD5Hash(fullfile(tmpDB, 'tmpDB.pto'));
-0152         blastReport.blastTxtOutput{numel(blastReport.blastTxtOutput)+1}=importdata([outFile '_r' num2str(i)]);
-0153     end    
-0154     if status~=0
-0155         error('blastp did not run successfully, error:\n%s',strip(message))
-0156     end
-0157     delete([tmpDB filesep 'tmpDB*']);
-0158 end
-0159 
-0160 %Done with the BLAST, do the parsing of the text files
-0161 for i=1:numel(refFastaFiles)*2
-0162     tempStruct=[];
-0163     if i<=numel(refFastaFiles)
-0164         tempStruct.fromId=modelIDs{i};
-0165         tempStruct.toId=organismID{1};
-0166         A=readtable([outFile '_' num2str(i)],'Delimiter',',','Format','%s%s%f%f%f%f%f');
-0167     else
-0168         tempStruct.fromId=organismID{1};
-0169         tempStruct.toId=modelIDs{i-numel(refFastaFiles)};
-0170         A=readtable([outFile '_r' num2str(i-numel(refFastaFiles))],'Delimiter',',','Format','%s%s%f%f%f%f%f');
-0171     end
-0172     tempStruct.fromGenes=A{:,1};
-0173     tempStruct.toGenes=A{:,2};
-0174     tempStruct.evalue=table2array(A(:,3));
-0175     tempStruct.identity=table2array(A(:,4));
-0176     tempStruct.aligLen=table2array(A(:,5));
-0177     tempStruct.bitscore=table2array(A(:,6));
-0178     tempStruct.ppos=table2array(A(:,7));
-0179     blastStructure=[blastStructure tempStruct];
-0180 end
-0181 
-0182 %Remove the old tempfiles
-0183 delete([outFile '*']);
-0184 %Remove the temp fasta files
-0185 delete(files{:})
-0186 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/external/getBlastFromExcel.html b/doc/external/getBlastFromExcel.html deleted file mode 100644 index 68300fa40..000000000 --- a/doc/external/getBlastFromExcel.html +++ /dev/null @@ -1,185 +0,0 @@ - - - - Description of getBlastFromExcel - - - - - - - - - -
Home > external > getBlastFromExcel.m
- - - -

getBlastFromExcel -

- -

PURPOSE ^

-
getBlastFromExcel
- -

SYNOPSIS ^

-
function blastStructure=getBlastFromExcel(models,blastFile,organismId)
- -

DESCRIPTION ^

-
 getBlastFromExcel
-   Retrieves gene homology information from Excel files. Used as
-   input to getModelFromHomology.
-
-   Input:
-   models          a cell array of model structures
-   blastFile       Excel file with homology information
-   organismId      the id of the organism of interest (as described in the
-                   Excel file)
-
-   Output:
-   blastStructure  structure containing the information in the Excel
-                   sheets.
-
-   The Excel file should contain a number of spreadsheets which in turn
-   contain the bidirectional homology measurements between the genes in the
-   organisms. The first and second column headers in each sheet is the
-   "to" and "from" model ids (as defined in models or for the new organism).
-   The entries should correspond to the gene names in those models. The third,
-   fourth, fifth, sixth and seventh columns represent the E-value, alignment
-   length, identity, bitscore and percentage of positive-scoring matches for
-   each measurement (captions should be "E-value", "Alignment length",
-   "Identity", "Bitscore" and "PPOS").
-
- Usage: blastStructure=getBlastFromExcel(models,blastFile,organismId)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function blastStructure=getBlastFromExcel(models,blastFile,organismId)
-0002 % getBlastFromExcel
-0003 %   Retrieves gene homology information from Excel files. Used as
-0004 %   input to getModelFromHomology.
-0005 %
-0006 %   Input:
-0007 %   models          a cell array of model structures
-0008 %   blastFile       Excel file with homology information
-0009 %   organismId      the id of the organism of interest (as described in the
-0010 %                   Excel file)
-0011 %
-0012 %   Output:
-0013 %   blastStructure  structure containing the information in the Excel
-0014 %                   sheets.
-0015 %
-0016 %   The Excel file should contain a number of spreadsheets which in turn
-0017 %   contain the bidirectional homology measurements between the genes in the
-0018 %   organisms. The first and second column headers in each sheet is the
-0019 %   "to" and "from" model ids (as defined in models or for the new organism).
-0020 %   The entries should correspond to the gene names in those models. The third,
-0021 %   fourth, fifth, sixth and seventh columns represent the E-value, alignment
-0022 %   length, identity, bitscore and percentage of positive-scoring matches for
-0023 %   each measurement (captions should be "E-value", "Alignment length",
-0024 %   "Identity", "Bitscore" and "PPOS").
-0025 %
-0026 % Usage: blastStructure=getBlastFromExcel(models,blastFile,organismId)
-0027 
-0028 if ~isfile(blastFile)
-0029     error('BLAST result file %s cannot be found',string(blastFile));
-0030 end
-0031 organismId=char(organismId);
-0032 
-0033 blastStructure=[];
-0034 
-0035 %Get a list of model IDs
-0036 organisms=cell(numel(models)+1,1);
-0037 organisms{1}=organismId;
-0038 for i=1:numel(models)
-0039     organisms{i+1}=models{i}.id;
-0040 end
-0041 
-0042 %Get all the spreadsheets in the file
-0043 [type, sheets]=xlsfinfo(blastFile);
-0044 
-0045 %Check if the file is a Microsoft Excel Spreadsheet
-0046 if ~any(regexp(type,'Excel Spreadsheet'))
-0047     EM='The file is not a Microsoft Excel Spreadsheet';
-0048     dispEM(EM);
-0049 end
-0050 
-0051 for i=1:numel(sheets)
-0052     %Check if the sheet has the right header and deal with organisms that
-0053     %are in "models"
-0054     [values,dataSheet]=xlsread(blastFile,i);
-0055     labels=dataSheet(1,:);
-0056     if strcmpi(labels{3},'E-value') && strcmpi(labels{4},'Alignment length') ...
-0057             && strcmpi(labels{5},'Identity') && strcmpi(labels{6},'Bitscore') ...
-0058             && strcmpi(labels{7},'PPOS')
-0059         %At least one of the organisms must have a model
-0060         fromID=find(strcmpi(labels{1},organisms));
-0061         toID=find(strcmpi(labels{2},organisms));
-0062         %Check that the organism ids exist and that one of them is the
-0063         %organism of interest
-0064         if any(fromID) && any(toID) && (toID==1 || fromID==1)
-0065             %Check that no gene ids are empty. This could for example be
-0066             %the case if the gene names are wrongly formatted as numbers
-0067             %instead of strings
-0068             emptyNames=cellfun(@isempty,dataSheet(2:end,1)) | cellfun(@isempty,dataSheet(2:end,2));
-0069             if any(emptyNames)
-0070                 if all(emptyNames)
-0071                     EM=['Only empty gene names in sheet from ' organisms{fromID} ' to ' organisms{toID}];
-0072                     dispEM(EM);
-0073                 else
-0074                     EM=['Empty gene names in sheet from ' organisms{fromID} ' to ' organisms{toID} '. Ignoring genes with empty names'];
-0075                     dispEM(EM,false);
-0076                 end
-0077             end
-0078             blastStructure(numel(blastStructure)+1).toId=organisms{toID};
-0079             blastStructure(numel(blastStructure)).fromId=organisms{fromID};
-0080             blastStructure(numel(blastStructure)).fromGenes=dataSheet(2:end,1);
-0081             blastStructure(numel(blastStructure)).toGenes=dataSheet(2:end,2);
-0082             blastStructure(numel(blastStructure)).evalue=values(:,1);
-0083             blastStructure(numel(blastStructure)).aligLen=values(:,2);
-0084             blastStructure(numel(blastStructure)).identity=values(:,3);
-0085             blastStructure(numel(blastStructure)).bitscore=values(:,4);
-0086             blastStructure(numel(blastStructure)).ppos=values(:,5);
-0087             
-0088             %Remove matches where any of the values is NaN. This would have
-0089             %been done anyways in getModelFromHomology, but it's neater to
-0090             %do it here
-0091             I=isnan(blastStructure(end).evalue) | isnan(blastStructure(end).aligLen) | isnan(blastStructure(end).identity);
-0092             blastStructure(end).fromGenes(I)=[];
-0093             blastStructure(end).toGenes(I)=[];
-0094             blastStructure(end).evalue(I)=[];
-0095             blastStructure(end).aligLen(I)=[];
-0096             blastStructure(end).identity(I)=[];
-0097             blastStructure(end).bitscore(I)=[];
-0098             blastStructure(end).ppos(I)=[];
-0099         else
-0100             if isempty(toID) || isempty(fromID)
-0101                 EM=['The data in sheet ' sheets{i} ' has no corresponding model. Ignoring sheet'];
-0102                 dispEM(EM,false);
-0103             else
-0104                 EM=['The data in sheet ' sheets{i} ' does not involve the organism of interest. Ignoring sheet'];
-0105                 dispEM(EM,false);
-0106             end
-0107         end
-0108     else
-0109         EM=['The data in sheet ' sheets{i} ' is not correctly formatted. Ignoring sheet'];
-0110         dispEM(EM,false);
-0111     end
-0112 end
-0113 
-0114 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/external/getDiamond.html b/doc/external/getDiamond.html deleted file mode 100644 index 16db1a0d2..000000000 --- a/doc/external/getDiamond.html +++ /dev/null @@ -1,250 +0,0 @@ - - - - Description of getDiamond - - - - - - - - - -
Home > external > getDiamond.m
- - - -

getDiamond -

- -

PURPOSE ^

-
getDiamond
- -

SYNOPSIS ^

-
function [blastStructure,diamondReport]=getDiamond(organismID,fastaFile,modelIDs,refFastaFiles,developMode,hideVerbose)
- -

DESCRIPTION ^

-
 getDiamond
-   Uses DIAMOND to perform a bidirectional BLAST between the organism
-   of interest and a set of template organisms
-
-   Input:
-   organismID      the id of the organism of interest. This should also
-                   match with the id supplied to getModelFromHomology
-   fastaFile       a FASTA file with the protein sequences for the
-                   organism of interest
-   modelIDs        a cell array of model ids. These must match the
-                   "model.id" fields in the "models" structure if the
-                   output is to be used with getModelFromHomology
-   refFastaFiles   a cell array with the paths to the corresponding FASTA
-                   files
-   developMode     true if blastReport should be generated that is used
-                   in the unit testing function for DIAMOND (optional, default
-                   false)
-   hideVerbose     true if no status messages should be printed (optional,
-                   default false)
-
-   Output:
-   blastStructure  structure containing the bidirectional homology
-                   measurements which are used by getModelFromHomology
-   diamondReport   structure containing MD5 hashes for FASTA database
-                   files and non-parsed BLAST output data. Will be blank
-                   if developMode is false.
-
-   NOTE: This function calls DIAMOND to perform a bidirectional homology
-   search between the organism of interest and a set of other organisms
-   using the '--more-sensitive' setting from DIAMOND. For the most
-   sensitive results, the use of getBlast() is adviced, however,
-   getDiamond() is a fast alternative (>15x faster). The blastStructure
-   generated is in the same format as those obtained from getBlast().
-
- Usage: [blastStructure,diamondReport]=getDiamond(organismID,fastaFile,...
-    modelIDs,refFastaFiles,developMode,hideVerbose)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function [blastStructure,diamondReport]=getDiamond(organismID,fastaFile,...
-0002     modelIDs,refFastaFiles,developMode,hideVerbose)
-0003 % getDiamond
-0004 %   Uses DIAMOND to perform a bidirectional BLAST between the organism
-0005 %   of interest and a set of template organisms
-0006 %
-0007 %   Input:
-0008 %   organismID      the id of the organism of interest. This should also
-0009 %                   match with the id supplied to getModelFromHomology
-0010 %   fastaFile       a FASTA file with the protein sequences for the
-0011 %                   organism of interest
-0012 %   modelIDs        a cell array of model ids. These must match the
-0013 %                   "model.id" fields in the "models" structure if the
-0014 %                   output is to be used with getModelFromHomology
-0015 %   refFastaFiles   a cell array with the paths to the corresponding FASTA
-0016 %                   files
-0017 %   developMode     true if blastReport should be generated that is used
-0018 %                   in the unit testing function for DIAMOND (optional, default
-0019 %                   false)
-0020 %   hideVerbose     true if no status messages should be printed (optional,
-0021 %                   default false)
-0022 %
-0023 %   Output:
-0024 %   blastStructure  structure containing the bidirectional homology
-0025 %                   measurements which are used by getModelFromHomology
-0026 %   diamondReport   structure containing MD5 hashes for FASTA database
-0027 %                   files and non-parsed BLAST output data. Will be blank
-0028 %                   if developMode is false.
-0029 %
-0030 %   NOTE: This function calls DIAMOND to perform a bidirectional homology
-0031 %   search between the organism of interest and a set of other organisms
-0032 %   using the '--more-sensitive' setting from DIAMOND. For the most
-0033 %   sensitive results, the use of getBlast() is adviced, however,
-0034 %   getDiamond() is a fast alternative (>15x faster). The blastStructure
-0035 %   generated is in the same format as those obtained from getBlast().
-0036 %
-0037 % Usage: [blastStructure,diamondReport]=getDiamond(organismID,fastaFile,...
-0038 %    modelIDs,refFastaFiles,developMode,hideVerbose)
-0039 
-0040 if nargin<5
-0041     developMode = false;
-0042 end
-0043 if nargin<6
-0044     hideVerbose = false;
-0045 end
-0046 
-0047 %Everything should be cell arrays
-0048 organismID=convertCharArray(organismID);
-0049 fastaFile=convertCharArray(fastaFile);
-0050 modelIDs=convertCharArray(modelIDs);
-0051 refFastaFiles=convertCharArray(refFastaFiles);
-0052 
-0053 %Create blank structures for results
-0054 blastStructure=[];
-0055 diamondReport.dbHashes={};
-0056 diamondReport.diamondTxtOutput={};
-0057 
-0058 %Get the directory for RAVEN Toolbox.
-0059 ravenPath=findRAVENroot();
-0060 
-0061 %Generate temporary names for DIAMOND databases and output files
-0062 tmpDB=tempname;
-0063 outFile=tempname;
-0064 
-0065 %Check for existence of files. If no full path is specified for a file,
-0066 %assume that it is in the current folder
-0067 if isrow(refFastaFiles)
-0068     files=horzcat(fastaFile,refFastaFiles);
-0069 else
-0070     files=vertcat(fastaFile,refFastaFiles);
-0071 end
-0072 
-0073 files=checkFileExistence(files,2); %Copy files to temp dir
-0074 fastaFile = files(1);
-0075 refFastaFiles = files(2:end);
-0076 
-0077 %Identify the operating system
-0078 if isunix
-0079     if ismac
-0080         binEnd='.mac';
-0081     else
-0082         binEnd='';
-0083     end
-0084 elseif ispc
-0085     binEnd='.exe';
-0086 else
-0087     dispEM('Unknown OS, exiting.')
-0088     return
-0089 end
-0090 
-0091 %Run DIAMOND multi-threaded to use all logical cores assigned to MATLAB.
-0092 cores = evalc('feature(''numcores'')');
-0093 cores = strsplit(cores, 'MATLAB was assigned: ');
-0094 cores = regexp(cores{2},'^\d*','match');
-0095 cores = cores{1};
-0096 
-0097 %Create a database for the new organism and blast each of the refFastaFiles
-0098 %against it
-0099 [status, message]=system(['"' fullfile(ravenPath,'software','diamond',['diamond' binEnd]) '" makedb --in "' fastaFile{1} '" --db "' fullfile(tmpDB) '"']);
-0100 if developMode
-0101     diamondReport.dbHashes{numel(diamondReport.dbHashes)+1} = char(regexp(message,'[a-f0-9]{32}','match'));
-0102 end
-0103 if status~=0
-0104     error('DIAMOND makedb did not run successfully, error:\n%s',strip(message))
-0105 end
-0106 
-0107 for i=1:numel(refFastaFiles)
-0108     if ~hideVerbose
-0109         fprintf(['Running DIAMOND blastp with "' modelIDs{i} '" against "' organismID{1} '"..\n']);
-0110     end
-0111     [status, message]=system(['"' fullfile(ravenPath,'software','diamond',['diamond' binEnd]) '" blastp --query "' refFastaFiles{i} '" --out "' outFile '_' num2str(i) '" --db "' fullfile(tmpDB) '" --more-sensitive --outfmt 6 qseqid sseqid evalue pident length bitscore ppos --threads ' cores ]);
-0112     if developMode
-0113         diamondReport.diamondTxtOutput{numel(diamondReport.diamondTxtOutput)+1}=importdata([outFile '_' num2str(i)]);
-0114     end
-0115     if status~=0
-0116         error('DIAMOND blastp did not run successfully, error:\n%s',strip(message))
-0117     end
-0118 end
-0119 delete([tmpDB filesep 'tmpDB*']);
-0120 
-0121 %Then create a database for each of the reference organisms and blast the
-0122 %new organism against them
-0123 for i=1:numel(refFastaFiles)
-0124     if ~hideVerbose
-0125         fprintf(['Running DIAMOND blastp with "' organismID{1} '" against "' modelIDs{i} '"..\n']);
-0126     end
-0127     [status, message1]=system(['"' fullfile(ravenPath,'software','diamond',['diamond' binEnd]) '" makedb --in "' refFastaFiles{i} '" --db "' fullfile(tmpDB) '"']);
-0128     if status~=0
-0129         error('DIAMOND makedb did not run successfully, error:\n%s',strip(message1))
-0130     end
-0131     [status, message]=system(['"' fullfile(ravenPath,'software','diamond',['diamond' binEnd]) '" blastp --query "' fastaFile{1} '" --out "' outFile '_r' num2str(i) '" --db "' fullfile(tmpDB) '" --more-sensitive --outfmt 6 qseqid sseqid evalue pident length bitscore ppos --threads ' cores]);
-0132     if developMode
-0133         diamondReport.dbHashes{numel(diamondReport.dbHashes)+1} = char(regexp(message1,'[a-f0-9]{32}','match'));
-0134         diamondReport.diamondTxtOutput{numel(diamondReport.diamondTxtOutput)+1}=importdata([outFile '_r' num2str(i)]);
-0135     end
-0136     if status~=0
-0137         error('DIAMOND blastp did not run successfully, error:\n%s',strip(message))
-0138     end
-0139     delete([tmpDB filesep 'tmpDB*']);
-0140 end
-0141 
-0142 %Done with the DIAMOND blastp, do the parsing of the text files
-0143 for i=1:numel(refFastaFiles)*2
-0144     tempStruct=[];
-0145     if i<=numel(refFastaFiles)
-0146         tempStruct.fromId=modelIDs{i};
-0147         tempStruct.toId=organismID{1};
-0148         A=readtable([outFile '_' num2str(i)],'Delimiter','\t','Format','%s%s%f%f%f%f%f');
-0149     else
-0150         tempStruct.fromId=organismID{1};
-0151         tempStruct.toId=modelIDs{i-numel(refFastaFiles)};
-0152         A=readtable([outFile '_r' num2str(i-numel(refFastaFiles))],'Delimiter','\t','Format','%s%s%f%f%f%f%f');
-0153     end
-0154     tempStruct.fromGenes=A{:,1};
-0155     tempStruct.toGenes=A{:,2};
-0156     tempStruct.evalue=table2array(A(:,3));
-0157     tempStruct.identity=table2array(A(:,4));
-0158     tempStruct.aligLen=table2array(A(:,5));
-0159     tempStruct.bitscore=table2array(A(:,6));
-0160     tempStruct.ppos=table2array(A(:,7));
-0161     blastStructure=[blastStructure tempStruct];
-0162 end
-0163 
-0164 %Remove the old tempfiles
-0165 delete([outFile '*']);
-0166 %Remove the temp fasta files
-0167 delete(files{:})
-0168 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/external/getWoLFScores.html b/doc/external/getWoLFScores.html deleted file mode 100644 index e4c8178cf..000000000 --- a/doc/external/getWoLFScores.html +++ /dev/null @@ -1,113 +0,0 @@ - - - - Description of getWoLFScores - - - - - - - - - -
Home > external > getWoLFScores.m
- - - -

getWoLFScores -

- -

PURPOSE ^

-
getWoLFScores
- -

SYNOPSIS ^

-
function GSS = getWoLFScores(inputFile, kingdom)
- -

DESCRIPTION ^

-
 getWoLFScores
-   Call WoLF PSort to predict the sub-cellular localization of proteins.
-   The output can be used as input to predictLocalization. This function
-   is currently only available for Linux and requires Perl to be
-   installed. If one wants to use another predictor, see parseScores. The
-   function normalizes the scores so that the best score for each gene is
-   1.0.
-
-   Input:
-   inputFile    a FASTA file with protein sequences
-   kingdom     the kingdom of the organism, 'animal', 'fungi' or 'plant'
-
-   Output:
-   GSS         a gene scoring structure to be used in predictLocalization
-
- Usage: GSS = getWoLFScores(inputFile, kingdom)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function GSS = getWoLFScores(inputFile, kingdom)
-0002 % getWoLFScores
-0003 %   Call WoLF PSort to predict the sub-cellular localization of proteins.
-0004 %   The output can be used as input to predictLocalization. This function
-0005 %   is currently only available for Linux and requires Perl to be
-0006 %   installed. If one wants to use another predictor, see parseScores. The
-0007 %   function normalizes the scores so that the best score for each gene is
-0008 %   1.0.
-0009 %
-0010 %   Input:
-0011 %   inputFile    a FASTA file with protein sequences
-0012 %   kingdom     the kingdom of the organism, 'animal', 'fungi' or 'plant'
-0013 %
-0014 %   Output:
-0015 %   GSS         a gene scoring structure to be used in predictLocalization
-0016 %
-0017 % Usage: GSS = getWoLFScores(inputFile, kingdom)
-0018 
-0019 if ~isfile(inputFile)
-0020     error('FASTA file %s cannot be found',string(inputFile));
-0021 end
-0022 
-0023 kingdom=char(kingdom);
-0024 if ~any(strcmp(kingdom,{'animal','fungi','plant'}))
-0025     EM='Allowed kingdoms are "animal", "fungi", and "plant"';
-0026     dispEM(EM);
-0027 end
-0028 
-0029 if ispc || ismac
-0030     EM='This function currently runs only on Linux. Use parseScores if you want to use another predictor';
-0031     dispEM(EM);
-0032 end
-0033 
-0034 %Get the directory for RAVEN Toolbox
-0035 ravenPath=findRAVENroot();
-0036 
-0037 %Temporary output name
-0038 outFile=tempname;
-0039 fid=fopen(outFile,'w');
-0040 
-0041 %Do the prediction
-0042 [~, output]=unix(['perl "' ravenPath '/software/WoLFPSORT/bin/runWolfPsortSummary" ' kingdom ' < ' inputFile]);
-0043 
-0044 %Save output and call the general parser
-0045 fprintf(fid,output);
-0046 fclose(fid);
-0047 GSS=parseScores(outFile,'wolf');
-0048 
-0049 %Clean up
-0050 delete(outFile);
-0051 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/external/index.html b/doc/external/index.html deleted file mode 100644 index 8521638f3..000000000 --- a/doc/external/index.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - Index for Directory external - - - - - - - - - - -
< Master indexIndex for external >
- -

Index for external

- -

Matlab files in this directory:

- -
 combineMetaCycKEGGModelscombineMetaCycKEGGModels
 getBlastgetBlast
 getBlastFromExcelgetBlastFromExcel
 getDiamondgetDiamond
 getWoLFScoresgetWoLFScores
 makeFakeBlastStructuremakeFakeBlastStructure
 parseScoresparseScores
 updateDocumentationupdateDocumentation
- - -

Subsequent directories:

- - -
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/external/kegg/constructMultiFasta.html b/doc/external/kegg/constructMultiFasta.html deleted file mode 100644 index def6a4931..000000000 --- a/doc/external/kegg/constructMultiFasta.html +++ /dev/null @@ -1,222 +0,0 @@ - - - - Description of constructMultiFasta - - - - - - - - - -
Home > external > kegg > constructMultiFasta.m
- - - -

constructMultiFasta -

- -

PURPOSE ^

-
constructMultiFasta
- -

SYNOPSIS ^

-
function constructMultiFasta(model,sourceFile,outputDir)
- -

DESCRIPTION ^

-
 constructMultiFasta
-   Saves one file in FASTA format for each reaction in the model that has genes
-
-   Input:
-   model         a model structure
-   sourceFile    a file with sequences in FASTA format
-   outputDir     the directory to save the resulting FASTA files in
-
-   The source file is assumed to have the format '>gene identifier
-   additional info'. Only the gene identifier is used for matching. This is
-   to be compatible with the rest of the code that retrieves information
-   from KEGG.
-
- Usage: constructMultiFasta(model,sourceFile,outputDir)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function constructMultiFasta(model,sourceFile,outputDir)
-0002 % constructMultiFasta
-0003 %   Saves one file in FASTA format for each reaction in the model that has genes
-0004 %
-0005 %   Input:
-0006 %   model         a model structure
-0007 %   sourceFile    a file with sequences in FASTA format
-0008 %   outputDir     the directory to save the resulting FASTA files in
-0009 %
-0010 %   The source file is assumed to have the format '>gene identifier
-0011 %   additional info'. Only the gene identifier is used for matching. This is
-0012 %   to be compatible with the rest of the code that retrieves information
-0013 %   from KEGG.
-0014 %
-0015 % Usage: constructMultiFasta(model,sourceFile,outputDir)
-0016 
-0017 sourceFile=char(sourceFile);
-0018 outputDir=char(outputDir);
-0019 if ~isfile(sourceFile)
-0020     error('FASTA file %s cannot be found',string(sourceFile));
-0021 end
-0022 
-0023 fprintf('Scanning the source multi-FASTA file... ');
-0024 %Open the source file
-0025 fid = fopen(sourceFile, 'r');
-0026 
-0027 %Since the list of genes will be accessed many times I use a Java hashtable
-0028 hTable = java.util.Hashtable;
-0029 
-0030 for i=1:numel(model.genes)
-0031     hTable.put(model.genes{i}, i);
-0032 end
-0033 
-0034 %First go through the source file and save the position (in bytes) of the
-0035 %start of each gene
-0036 elementPositions=zeros(5000000,1,'int64'); %Make room for 5000000 elements
-0037 totalElements=0;
-0038 whereAmI=0; %Keeps track of where in the file we are
-0039 while 1
-0040     %Read 10 mb at a time
-0041     str=fread(fid,10000000,'int8');
-0042     
-0043     %Find any '>' which indicates a new label in FASTA format
-0044     newPosts=find(str==62); %62 is '>'
-0045     
-0046     elementPositions(totalElements+1:totalElements+numel(newPosts))=whereAmI+newPosts;
-0047     
-0048     totalElements=totalElements+numel(newPosts);
-0049     
-0050     whereAmI=whereAmI+10000000;
-0051     
-0052     if feof(fid)
-0053         break;
-0054     end
-0055 end
-0056 elementPositions=elementPositions(1:totalElements);
-0057 fprintf('COMPLETE\n');
-0058 
-0059 fprintf(['NOTICE: If Matlab is freezing and does not provide any output in 30 minutes, consider increasing Java Heap Memory\n', ...
-0060     'in MATLAB settings and start over with the new session\n']);
-0061 fprintf('Mapping genes to the multi-FASTA source file...   0%% complete');
-0062 %Now loop through the file to see which genes are present in the gene list
-0063 %and save their position IN elementPositions! This is to enable a easy way
-0064 %to get the distance to the following element
-0065 genePositions=zeros(numel(model.genes),1);
-0066 for i=1:numel(elementPositions)
-0067     fseek(fid,elementPositions(i),-1);
-0068     str=fread(fid,[1 30],'*char'); %Assumes that no ID is longer than 20 characters
-0069     delim=find(str==32 | str==10,1,'first'); %Space or line feed
-0070     
-0071     geneIdentifier=str(1:delim-1);
-0072     
-0073     %This should never happen, but just to prevent errors. Could be that
-0074     %'>' is a part of some gene information. An alternative would be to
-0075     %check that the indexes follows a line feed
-0076     if isempty(geneIdentifier)
-0077         continue;
-0078     end
-0079     
-0080     %If not found it means that the id was too long
-0081     if isempty(delim)
-0082         EM='Too long gene identifier, increase read length';
-0083         dispEM(EM);
-0084     end
-0085     
-0086     %See if the gene was found
-0087     id=hTable.get(geneIdentifier);
-0088     
-0089     if any(id)
-0090         if genePositions(id)==0
-0091             genePositions(id)=i;
-0092         end
-0093     end
-0094     %Print the progress
-0095     if rem(i-1,350000) == 0
-0096         progress=num2str(floor(100*i/numel(elementPositions)));
-0097         progress=pad(progress,3,'left');
-0098         fprintf('\b\b\b\b\b\b\b\b\b\b\b\b\b%s%% complete',progress);
-0099     end
-0100 end
-0101 fprintf('\b\b\b\b\b\b\b\b\b\b\b\b\bCOMPLETE\n');   
-0102 
-0103 fprintf('Generating the KEGG Orthology specific multi-FASTA files...   0%% complete');
-0104 %Loop through the reactions and print the corresponding sequences
-0105 for i=1:numel(model.rxns)
-0106 
-0107     %Do not overwrite existing files
-0108     if ~exist(fullfile(outputDir,[model.rxns{i} '.fa']), 'file')
-0109         
-0110         %Get the positions in elementPositions for the involved genes
-0111         genesUsed=model.rxnGeneMat(i,:);
-0112         
-0113         %Open a file for this reaction. This saves empty files for KOs
-0114         %without genes
-0115         rxnfid=fopen(fullfile(outputDir,[model.rxns{i} '.fa']),'w');
-0116         
-0117         if any(genesUsed)
-0118             positions=genePositions(genesUsed~=0);
-0119             
-0120             %It could be that some genes were not found. Delete those
-0121             %elements
-0122             positions(positions==0)=[];
-0123             
-0124             %Print each sequence
-0125             for j=1:numel(positions)
-0126                 fseek(fid,elementPositions(positions(j)),-1);
-0127                 %Should check that it ends with a gene!!!! Check for eof
-0128                 if positions(j)<numel(elementPositions)
-0129                     str=fread(fid,[1 double(elementPositions(positions(j)+1))-double(elementPositions(positions(j)))-1],'*char');
-0130                     
-0131                     %If the string does not end with a line feed character
-0132                     if str(end)~=10
-0133                         str=[str fread(fid,[1 double(elementPositions(positions(j)+2))-double(elementPositions(positions(j)+1))],'*char')];
-0134                         
-0135                         %This is if we still have not found a new gene.
-0136                         %Maximal unluck. This whole check should be done
-0137                         %when elementPositions are calculated!
-0138                         if str(end)~=10
-0139                             %Skip this gene
-0140                             continue;
-0141                         end
-0142                     end
-0143                 else
-0144                     str=fread(fid,[1 inf],'*char');
-0145                 end
-0146                 fwrite(rxnfid,['>' str]);
-0147             end
-0148         end
-0149         fclose(rxnfid);
-0150     end
-0151     %Print the progress
-0152     if rem(i-1,50) == 0
-0153         progress=num2str(floor(100*i/numel(model.rxns)));
-0154         progress=pad(progress,3,'left');
-0155         fprintf('\b\b\b\b\b\b\b\b\b\b\b\b\b%s%% complete',progress);
-0156     end
-0157 end
-0158 fprintf('\b\b\b\b\b\b\b\b\b\b\b\b\bCOMPLETE\n');
-0159 
-0160 %Close the source file
-0161 fclose(fid);
-0162 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/external/kegg/getGenesFromKEGG.html b/doc/external/kegg/getGenesFromKEGG.html deleted file mode 100644 index cba93c72e..000000000 --- a/doc/external/kegg/getGenesFromKEGG.html +++ /dev/null @@ -1,516 +0,0 @@ - - - - Description of getGenesFromKEGG - - - - - - - - - -
Home > external > kegg > getGenesFromKEGG.m
- - - -

getGenesFromKEGG -

- -

PURPOSE ^

-
getGenesFromKEGG
- -

SYNOPSIS ^

-
function model=getGenesFromKEGG(keggPath,koList)
- -

DESCRIPTION ^

-
 getGenesFromKEGG
-   Retrieves information on all genes stored in KEGG database
-
-   Input:
-   keggPath    if keggGenes.mat is not in the RAVEN\external\kegg
-               directory, this function will attempt to read data from a
-               local FTP dump of the KEGG database. keggPath is the path
-               to the root of this database
-   koList      the number of genes in KEGG is very large. koList can be a
-               cell array with KO identifiers, in which case only genes
-               belonging to one of those KEGG orthologies are retrieved
-               (optional, default all KOs with associated reactions)
-
-   Output:
-   model       a model structure generated from the database. The
-               following fields are filled
-       id              'KEGG'
-       name     'Automatically generated from KEGG database'
-       rxns            KO ids
-       rxnNames        Name for each entry
-       genes           IDs for all the genes. Genes are saved as organism
-                       abbreviation:id (same as in KEGG). 'HSA:124' for
-                       example is alcohol dehydrogenase in Homo sapiens
-       rxnGeneMat      A binary matrix that indicates whether a specific
-                       gene is present in a KO id
-
-   NOTE: If the file keggGenes.mat is in the RAVEN\external\kegg directory
-   it will be loaded instead of parsing of the KEGG files. If it does not
-   exist it will be saved after parsing of the KEGG files. In general, you
-   should remove the keggGenes.mat file if you want to rebuild the model
-   structure from a newer version of KEGG.
-
- Usage: model=getGenesFromKEGG(keggPath,koList)
-
- NOTE: This is how one entry looks in the file
-
- ENTRY       K11440                      KO
- NAME        gbsB
- DEFINITION  choline dehydrogenase [EC:1.1.1.1]
- PATHWAY     ko00260  Glycine, serine and threonine metabolism
-             ko01100  Metabolic pathways
- MODULE      M00555  Betaine biosynthesis, choline => betaine
- BRITE       KEGG Orthology (KO) [BR:ko00001]
-             (list truncated)
- DBLINKS     RN: R08557 R08558
-             COG: COG1454
- GENES       BSU: BSU31050(gbsB)
-             BSR: I33_3189
-             (list truncated)
- REFERENCE   PMID:8752328
-   AUTHORS   Boch J, Kempf B, Schmid R, Bremer E
-   TITLE     Synthesis of the osmoprotectant glycine... (truncated)
-   JOURNAL   J Bacteriol 178:5121-9 (1996)
-             DOI:10.1128/JB.178.17.5121-5129.1996
-   SEQUENCE  [bsu:BSU31050]
- ///
-
- The file is not tab-delimited. Instead each label is 12 characters
- (except for '///').
-
- Check if the genes have been parsed before and saved. If so, load the
- model.
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 function model=getGenesFromKEGG(keggPath,koList)
-0002 % getGenesFromKEGG
-0003 %   Retrieves information on all genes stored in KEGG database
-0004 %
-0005 %   Input:
-0006 %   keggPath    if keggGenes.mat is not in the RAVEN\external\kegg
-0007 %               directory, this function will attempt to read data from a
-0008 %               local FTP dump of the KEGG database. keggPath is the path
-0009 %               to the root of this database
-0010 %   koList      the number of genes in KEGG is very large. koList can be a
-0011 %               cell array with KO identifiers, in which case only genes
-0012 %               belonging to one of those KEGG orthologies are retrieved
-0013 %               (optional, default all KOs with associated reactions)
-0014 %
-0015 %   Output:
-0016 %   model       a model structure generated from the database. The
-0017 %               following fields are filled
-0018 %       id              'KEGG'
-0019 %       name     'Automatically generated from KEGG database'
-0020 %       rxns            KO ids
-0021 %       rxnNames        Name for each entry
-0022 %       genes           IDs for all the genes. Genes are saved as organism
-0023 %                       abbreviation:id (same as in KEGG). 'HSA:124' for
-0024 %                       example is alcohol dehydrogenase in Homo sapiens
-0025 %       rxnGeneMat      A binary matrix that indicates whether a specific
-0026 %                       gene is present in a KO id
-0027 %
-0028 %   NOTE: If the file keggGenes.mat is in the RAVEN\external\kegg directory
-0029 %   it will be loaded instead of parsing of the KEGG files. If it does not
-0030 %   exist it will be saved after parsing of the KEGG files. In general, you
-0031 %   should remove the keggGenes.mat file if you want to rebuild the model
-0032 %   structure from a newer version of KEGG.
-0033 %
-0034 % Usage: model=getGenesFromKEGG(keggPath,koList)
-0035 %
-0036 % NOTE: This is how one entry looks in the file
-0037 %
-0038 % ENTRY       K11440                      KO
-0039 % NAME        gbsB
-0040 % DEFINITION  choline dehydrogenase [EC:1.1.1.1]
-0041 % PATHWAY     ko00260  Glycine, serine and threonine metabolism
-0042 %             ko01100  Metabolic pathways
-0043 % MODULE      M00555  Betaine biosynthesis, choline => betaine
-0044 % BRITE       KEGG Orthology (KO) [BR:ko00001]
-0045 %             (list truncated)
-0046 % DBLINKS     RN: R08557 R08558
-0047 %             COG: COG1454
-0048 % GENES       BSU: BSU31050(gbsB)
-0049 %             BSR: I33_3189
-0050 %             (list truncated)
-0051 % REFERENCE   PMID:8752328
-0052 %   AUTHORS   Boch J, Kempf B, Schmid R, Bremer E
-0053 %   TITLE     Synthesis of the osmoprotectant glycine... (truncated)
-0054 %   JOURNAL   J Bacteriol 178:5121-9 (1996)
-0055 %             DOI:10.1128/JB.178.17.5121-5129.1996
-0056 %   SEQUENCE  [bsu:BSU31050]
-0057 % ///
-0058 %
-0059 % The file is not tab-delimited. Instead each label is 12 characters
-0060 % (except for '///').
-0061 %
-0062 % Check if the genes have been parsed before and saved. If so, load the
-0063 % model.
-0064 %
-0065 
-0066 if nargin<1
-0067     keggPath='RAVEN/external/kegg';
-0068 else
-0069     keggPath=char(keggPath);
-0070 end
-0071 
-0072 ravenPath=findRAVENroot();
-0073 genesFile=fullfile(ravenPath,'external','kegg','keggGenes.mat');
-0074 if ~exist(genesFile, 'file')
-0075     try
-0076         downloadKEGGgenes();
-0077     catch
-0078         %Download failed; fall through to local regeneration below
-0079     end
-0080 end
-0081 if exist(genesFile, 'file')
-0082     fprintf(['Importing KEGG genes from ' strrep(genesFile,'\','/') '... ']);
-0083     load(genesFile);
-0084 else
-0085     fprintf(['NOTE: Cannot locate ' strrep(genesFile,'\','/') ', it will therefore be generated from the local KEGG database\n']);
-0086     if ~isfile(fullfile(keggPath,'ko')) || ~isfile(fullfile(keggPath,'reaction'))
-0087         EM=fprintf(['The files ''ko'' and ''reaction'' cannot be located at ' strrep(keggPath,'\','/') '/ and should be downloaded from the KEGG FTP\n']);
-0088         dispEM(EM);
-0089     else
-0090         fprintf('Generating keggGenes.mat file...\n');
-0091         %Get all KOs that are associated to reactions
-0092         allKOs=getAllKOs(keggPath);
-0093         
-0094         %Since the list of genes will be accessed many times the hash table
-0095         %is established
-0096         geneMap=containers.Map('KeyType','char','ValueType','int32');
-0097         
-0098         %Add new functionality in the order specified in models
-0099         model.id='KEGG';
-0100         model.name='Automatically generated from KEGG database';
-0101         
-0102         %Preallocate memory
-0103         model.rxns=cell(numel(allKOs),1);
-0104         model.rxnNames=cell(numel(allKOs),1);
-0105         
-0106         %Reserve space for 500000 genes
-0107         model.genes=cell(500000,1);
-0108         
-0109         %Load information on KO ID, name, and associated genes
-0110         fid = fopen(fullfile(keggPath,'ko'), 'r');
-0111         
-0112         %Keeps track of how many KOs that have been added
-0113         koCounter=0;
-0114         nGenes=0;
-0115         addingGenes=false;
-0116         
-0117         %These contain the mapping between KOs and genes and are used to
-0118         %generate the model.rxnGeneMat in the end
-0119         koIndex=zeros(5000000,1);
-0120         geneIndex=koIndex;
-0121         nMappings=0;
-0122         
-0123         skipRead=false;
-0124         
-0125         %Loop through the file
-0126         while 1
-0127             %Get the next line
-0128             if skipRead==false
-0129                 tline = fgetl(fid);
-0130             else
-0131                 skipRead=false;
-0132             end
-0133             
-0134             %Abort at end of file
-0135             if ~ischar(tline)
-0136                 break;
-0137             end
-0138             
-0139             %Skip '///'
-0140             if numel(tline)<12
-0141                 addingGenes=false;
-0142                 continue;
-0143             end
-0144             
-0145             %Check if it's a new reaction
-0146             if strcmp(tline(1:12),'ENTRY       ')
-0147                 %Check if it should be added
-0148                 koID=tline(13:18);
-0149                 
-0150                 if ismember(koID,allKOs)
-0151                     addMe=true;
-0152                     koCounter=koCounter+1;
-0153                 else
-0154                     addMe=false;
-0155                     continue;
-0156                 end
-0157                 
-0158                 %Add reaction ID (always 6 characters)
-0159                 model.rxns{koCounter}=koID;
-0160                 
-0161                 model.rxnNames{koCounter}='';
-0162                 %Will be overwritten if it exists
-0163             end
-0164             
-0165             %To get here we must be in a KO that should be added
-0166             if addMe==true
-0167                 %Add name
-0168                 if strcmp(tline(1:12),'DEFINITION  ')
-0169                     model.rxnNames{koCounter}=tline(13:end);
-0170                 end
-0171                 
-0172                 %Check if it's time to start adding genes
-0173                 if strcmp(tline(1:12),'GENES       ')
-0174                     addingGenes=true;
-0175                 end
-0176                 
-0177                 %Add genes
-0178                 if addingGenes==true
-0179                     %We are now adding genes for the current KO. All gene
-0180                     %rows start with 12 spaces. If this is not true it
-0181                     %means that there is additional annotation such as
-0182                     %AUTHORS. This is not common but it exists
-0183                     if strcmp(tline(1:12),'            ') || strcmp(tline(1:12),'GENES       ')
-0184                         geneLine=tline(13:end);
-0185                         
-0186                         %Check if the line is from a new organism of from
-0187                         %the same as before
-0188                         if strcmp(geneLine(4),':')
-0189                             %If organism id contains 3 letters;
-0190                             currentOrganism=geneLine(1:3);
-0191                             %Parse the string
-0192                             genes=regexp(geneLine(6:end),' ','split');
-0193                             genes=strcat(currentOrganism,':',genes(:));
-0194                         elseif strcmp(geneLine(5),':')
-0195                             %If organism id contains 4 letters;
-0196                             currentOrganism=geneLine(1:4);
-0197                             %Parse the string
-0198                             genes=regexp(geneLine(7:end),' ','split');
-0199                             genes=strcat(currentOrganism,':',genes(:));
-0200                         end
-0201                         
-0202                         %Add the genes to the gene list
-0203                         for i=1:numel(genes)
-0204                             geneString=genes{i};
-0205                             if geneMap.isKey(geneString)
-0206                                 index=geneMap(geneString);
-0207                             else
-0208                                 nGenes=nGenes+1;
-0209                                 model.genes{nGenes}=geneString;
-0210                                 index=nGenes;
-0211                                 geneMap(geneString)=index;
-0212                             end
-0213                             
-0214                             %Add the connection to the KO
-0215                             nMappings=nMappings+1;
-0216                             koIndex(nMappings)=koCounter;
-0217                             geneIndex(nMappings)=index;
-0218                         end
-0219                     else
-0220                         %Now we want to throw away everything until the
-0221                         %next entry
-0222                         while 1
-0223                             tline = fgetl(fid);
-0224                             if strcmp(tline,'///')
-0225                                 %When the new entry is found, skip reading
-0226                                 %one line to fit with the rest of the code
-0227                                 skipRead=true;
-0228                                 break;
-0229                             end
-0230                         end
-0231                     end
-0232                 end
-0233             end
-0234         end
-0235         %Close the file
-0236         fclose(fid);
-0237         
-0238         %If too much space was allocated, shrink the model
-0239         model.rxns=model.rxns(1:koCounter);
-0240         model.rxnNames=model.rxnNames(1:koCounter);
-0241         model.genes=model.genes(1:nGenes);
-0242         
-0243         %Retrieve and add the gene associations
-0244         model.rxnGeneMat=sparse(koIndex(1:nMappings),geneIndex(1:nMappings),ones(nMappings,1));
-0245         
-0246         %To make sure the size is correct if the last KOs don't have genes
-0247         if size(model.rxnGeneMat,1)~=koCounter
-0248             model.rxnGeneMat(koCounter,1)=0;
-0249         end
-0250         
-0251         %Trim the genes so that they only contain information that can be
-0252         %matched to the KEGG file of protein sequences (remove all
-0253         %information after first parenthesis)
-0254         %NOTE: For some reason the organism abbreviation should be in lower
-0255         %case in this database. Fix this here
-0256         for i=1:numel(model.genes)
-0257             parIndex=strfind(model.genes{i},'(');
-0258             if any(parIndex)
-0259                 model.genes{i}=model.genes{i}(1:parIndex-1);
-0260             end
-0261             colIndex=strfind(model.genes{i},':');
-0262             model.genes{i}=[lower(model.genes{i}(1:colIndex-1)) model.genes{i}(colIndex:end)];
-0263         end
-0264         
-0265         %Save the model structure
-0266         save(genesFile,'model');
-0267     end
-0268 end
-0269 
-0270 %Only get the KOs in koList
-0271 if nargin>1
-0272     I=~ismember(model.rxns,koList);
-0273     model=removeReactions(model,I,true,true);
-0274 end
-0275 fprintf('COMPLETE\n');
-0276 end
-0277 
-0278 function allKOs=getAllKOs(keggPath)
-0279 %Retrieves all KOs that are associated to reactions. This is because the
-0280 %number of genes in KEGG is very large so without this parsing it would
-0281 %take many hours
-0282 
-0283 allKOs={};
-0284 
-0285 %First check if the reactions have already been parsed
-0286 ravenPath=findRAVENroot;
-0287 rxnsFile=fullfile(ravenPath,'external','kegg','keggRxns.mat');
-0288 if exist(rxnsFile, 'file')
-0289     fprintf(['NOTE: Importing KEGG ORTHOLOGY list from ' strrep(rxnsFile,'\','/') '.\n']);
-0290     load(rxnsFile,'model');
-0291     
-0292     %Loop through the reactions and add the corresponding genes
-0293     for i=1:numel(model.rxns)
-0294         if isstruct(model.rxnMiriams{i})
-0295             %Get all KOs
-0296             allKOs=[allKOs;model.rxnMiriams{i}.value(strcmpi(model.rxnMiriams{i}.name,'kegg.orthology'))];
-0297         end
-0298     end
-0299 else
-0300     %Parse the reaction file instead First load information on reaction ID,
-0301     %reaction name, KO, pathway and ec-number
-0302     fid = fopen(fullfile(keggPath,'reaction'), 'r');
-0303     orthology=false;
-0304     while 1
-0305         %Get the next line
-0306         tline = fgetl(fid);
-0307         
-0308         %Abort at end of file
-0309         if ~ischar(tline)
-0310             break;
-0311         end
-0312         
-0313         %Skip '///'
-0314         if numel(tline)<12
-0315             continue;
-0316         end
-0317         
-0318         %Check if it's a new reaction
-0319         if strcmp(tline(1:12),'ENTRY       ')
-0320             orthology=false;
-0321         end
-0322         
-0323         if strcmp(tline(1:9),'REFERENCE')
-0324             orthology=false;
-0325         end
-0326         
-0327         %Add KO-ids
-0328         if numel(tline)>16
-0329             if strcmp(tline(1:16),'ORTHOLOGY   KO: ') || strcmp(tline(1:16),'            KO: ') || strcmp(tline(1:12),'ORTHOLOGY   ') || orthology==true
-0330                 if strcmp(tline(13:16),'KO:')
-0331                     %This is in the old version
-0332                     allKOs=[allKOs;tline(17:22)];
-0333                 elseif strcmp(tline(1:12),'ORTHOLOGY   ')
-0334                     %This means that it found one KO in the new format and
-0335                     %that subsequent lines might be other KOs
-0336                     orthology=true;
-0337                     allKOs=[allKOs;tline(13:18)];
-0338                 end
-0339             end
-0340         end
-0341     end
-0342     
-0343     %Close the file
-0344     fclose(fid);
-0345 end
-0346 allKOs=unique(allKOs);
-0347 end
-0348 
-0349 function downloadKEGGgenes()
-0350 % downloadKEGGgenes
-0351 %   Downloads keggGenes.mat from the RAVEN GitHub release into
-0352 %   external/kegg/. This file is distributed as a release asset rather
-0353 %   than shipped in the repository because it exceeds GitHub's 100 MB
-0354 %   file-size limit.
-0355 %
-0356 %   The following asset is expected on the release tag defined below:
-0357 %       keggGenes.zip   containing keggGenes.mat
-0358 %
-0359 %   To force a refresh (for example, after a new KEGG snapshot has been
-0360 %   published with a new RAVEN release), delete
-0361 %   external/kegg/keggGenes.mat and call getGenesFromKEGG again.
-0362 %
-0363 %   Usage: downloadKEGGgenes()
-0364 
-0365 % Release tag that hosts the data archive. Bump this for any RAVEN
-0366 % release that ships an updated keggGenes.mat.
-0367 releaseTag = 'v2.11.1';
-0368 
-0369 archiveName = 'keggGenes.zip';
-0370 targetDir   = fullfile(findRAVENroot(),'external','kegg');
-0371 targetFile  = fullfile(targetDir,'keggGenes.mat');
-0372 url         = ['https://github.com/SysBioChalmers/RAVEN/releases/download/',...
-0373                releaseTag,'/',archiveName];
-0374 zipPath     = fullfile(targetDir,archiveName);
-0375 
-0376 fprintf(['Downloading ' archiveName ' from RAVEN ' releaseTag ' release... ']);
-0377 try
-0378     websave(zipPath,url);
-0379 catch ME
-0380     if strcmp(ME.identifier,'MATLAB:webservices:HTTP404StatusCodeError')
-0381         error(['Failed to download ' archiveName ': the server returned ' ...
-0382                'a 404 error. If this persists, please report it at ' ...
-0383                'https://github.com/SysBioChalmers/RAVEN/issues']);
-0384     else
-0385         rethrow(ME);
-0386     end
-0387 end
-0388 fprintf('COMPLETE\n');
-0389 
-0390 fprintf(['Extracting ' archiveName ' to ' strrep(targetDir,'\','/') '... ']);
-0391 try
-0392     unzip(zipPath,targetDir);
-0393 catch ME
-0394     if isfile(zipPath); delete(zipPath); end
-0395     error(['Failed to extract ' archiveName '. The downloaded archive ' ...
-0396            'may be corrupted.\nOriginal error: %s'],ME.message);
-0397 end
-0398 fprintf('COMPLETE\n');
-0399 
-0400 if isfile(zipPath); delete(zipPath); end
-0401 
-0402 if ~isfile(targetFile)
-0403     error(['keggGenes.mat was not found in ' archiveName ...
-0404            '. Please verify the release asset contents.']);
-0405 end
-0406 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/external/kegg/getKEGGModelForOrganism.html b/doc/external/kegg/getKEGGModelForOrganism.html deleted file mode 100644 index 843e4b454..000000000 --- a/doc/external/kegg/getKEGGModelForOrganism.html +++ /dev/null @@ -1,1342 +0,0 @@ - - - - Description of getKEGGModelForOrganism - - - - - - - - - -
Home > external > kegg > getKEGGModelForOrganism.m
- - - -

getKEGGModelForOrganism -

- -

PURPOSE ^

-
getKEGGModelForOrganism
- -

SYNOPSIS ^

-
function model=getKEGGModelForOrganism(organismID,fastaFile,dataDir,outDir,keepSpontaneous,keepUndefinedStoich,keepIncomplete,keepGeneral,cutOff,minScoreRatioKO,minScoreRatioG,maxPhylDist,nSequences,seqIdentity,globalModel)
- -

DESCRIPTION ^

-
 getKEGGModelForOrganism
-   Reconstructs a genome-scale metabolic model based on protein homology
-   to the orthologies in KEGG. If the target species is not available in
-   KEGG, the user must select a closely related species. It is also
-   possible to circumvent protein homology search (see fastaFile parameter
-   for more details)
-
-   Input:
-   organismID          three or four letter abbreviation of the organism
-                       (as used in KEGG). If not available, use a closely
-                       related species. This is used for determing the
-                       phylogenetic distance. Use 'eukaryotes' or
-                       'prokaryotes' to get a model for the whole domain.
-                       Only applicable if fastaFile is empty, i.e. no
-                       homology search should be performed
-   fastaFile           a FASTA file that contains the protein sequences of
-                       the organism for which to reconstruct a model (optional,
-                       if no FASTA file is supplied then a model is
-                       reconstructed based only on the organism
-                       abbreviation. This option ignores all settings
-                       except for keepSpontaneous, keepUndefinedStoich,
-                       keepIncomplete and keepGeneral)
-   dataDir             directory for which to retrieve the input data.
-                       Should contain a combination of these sub-folders:
-                       -dataDir\keggdb
-                           The KEGG database files used in 1a (see below)
-                       -dataDir\fasta
-                           The multi-FASTA files generated in 1b (see
-                           below)
-                       -dataDir\aligned
-                           The aligned FASTA files as generated in 2a (see
-                           below)
-                       -dataDir\hmms
-                           The hidden Markov models as generated in 2b or
-                           downloaded from BioMet Toolbox (see below)
-                       The final directory in dataDir should be styled as
-                       prok90_kegg116 or euk90_kegg116, indicating whether
-                       the HMMs were trained on pro- or eukaryotic
-                       sequences; using which sequence similarity treshold
-                       (first set of digits); using which KEGG version
-                       (second set of digits). (this parameter should
-                       ALWAYS be provided)
-   outDir              directory to save the results from the quering of
-                       the hidden Markov models. The output is specific
-                       for the input sequences and the settings used. It
-                       is stored in this manner so that the function can
-                       continue if interrupted or if it should run in
-                       parallel. Be careful not to leave output files from
-                       different organisms or runs with different settings
-                       in the same folder. They will not be overwritten
-                       (optional, default is a temporary dir where all *.out
-                       files are deleted before and after doing the
-                       reconstruction)
-   keepSpontaneous     include reactions labeled as "spontaneous". (optional,
-                       default true)
-   keepUndefinedStoich    include reactions in the form n A <=> n+1 A. These
-                       will be dealt with as two separate metabolites
-                       (optional, default true)
-   keepIncomplete      include reactions which have been labelled as
-                       "incomplete", "erroneous" or "unclear" (optional,
-                       default true)
-   keepGeneral         include reactions which have been labelled as
-                       "general reaction". These are reactions on the form
-                       "an aldehyde <=> an alcohol", and are therefore
-                       unsuited for modelling purposes. Note that not all
-                       reactions have this type of annotation, and the
-                       script will therefore not be able to remove all
-                       such reactions (optional, default false)
-   cutOff              significance score from HMMer needed to assign
-                       genes to a KO (optional, default 10^-50)
-   minScoreRatioG      a gene is only assigned to KOs for which the score
-                       is >=log(score)/log(best score) for that gene. This
-                       is to prevent that a gene which clearly belongs to
-                       one KO is assigned also to KOs with much lower
-                       scores (optional, default 0.8 (lower is less strict))
-   minScoreRatioKO     ignore genes in a KO if their score is
-                       <log(score)/log(best score in KO). This is to
-                       "prune" KOs which have many genes and where some are
-                       clearly a better fit (optional, default 0.3 (lower is
-                       less strict))
-   maxPhylDist         -1: only use sequences from the same domain
-                       (Prokaryota, Eukaryota)
-                       other (positive) value: only use sequences for
-                       organisms where the phylogenetic distance is at the
-                       most this large (as calculated in getPhylDist)
-                       (optional, default Inf, which means that all sequences
-                       will be used)
-   nSequences          for each KO, use up to this many sequences from the
-                       most closely related species. This is mainly to
-                       speed up the alignment process for KOs with very
-                       many genes. This subsampling is performed before
-                       running CD-HIT (optional, default inf)
-   seqIdentity         sequence identity threshold in CD-HIT, referred as
-                       "global sequence identity" in CD-HIT User's Guide.
-                       If -1 is provided, CD-HIT is skipped (optional, default 0.9)
-   globalModel         structure containing both model and KOModel
-                       structures as generated by getModelFromKEGG. These
-                       will otherwise be loaded by via getModelFromKEGG.
-                       Providing globalKEGGmodel can speed up model
-                       generation if getKEGGModelForOrganism is run
-                       multiple times for different strains. Example:
-                       [globalModel.model,globalModel.KOModel] = getModelFromKEGG;
-                       (optional, default empty, global model is loaded by
-                       getModelFromKEGG)
-
-   Output:
-   model               the reconstructed model
-
-   PLEASE READ THIS: The input to this function can be confusing, because
-   it is intended to be run in parallel on a cluster or in multiple
-   sessions. It therefore saves a lot of intermediate results to storage.
-   This also serves the purpose of not having to do redundant
-   calculations. This, however, comes with the disadvantage of somewhat
-   trickier handling. This is what this function does:
-
-   1a. Loads files from a local KEGG FTP dump and constructs a general
-       RAVEN model representing the metabolic network. The functions
-       getRxnsFromKEGG, getGenesFromKEGG, getMetsFromKEGG summarise the
-       data into 'keggRxns.mat', 'keggGenes.mat' and 'keggMets.mat' files,
-       which are later merged into 'keggModel.mat' by getModelFromKEGG
-       function. The function getPhylDist generates 'keggPhylDist.mat'
-       file. KEGG FTP access requires a <a href="matlab:
-       web('http://www.bioinformatics.jp/en/keggftp.html')">license</a>.
-   1b. Generates protein FASTA files from the KEGG FTP dump (see 1a). One
-       multi-FASTA file for each KO in KEGG is generated.
-
-   The Step 1 has to be re-done every time KEGG updates their database (or
-   rather when the updates are large enough to warrant re-running this
-   part). Many users would probably never use this feature.
-
-   2a. Filters KO-specific protein sets. This is done by using the
-       settings "maxPhylDist" and "nSequences" to control which sequences
-       should be used for constructing Hidden Markov models (HMMs), and
-       later for matching your sequences to.
-       The most common alternatives here would be to use sequences from
-       only eukaryotes, only prokaryotes or all sequences in KEGG, but you
-       could also play around with the parameters to use e.g. only fungal
-       sequences.
-   2b. KO-specific protein FASTA files are re-organised into
-       non-redundant protein sets with CD-HIT. The user can only set
-       seqIdentity parameter, which corresponds to '-c' parameter in
-       CD-HIT, described as "sequence identity threshold". CD-HIT suggsted
-       sequence identity specific word_length (-n) parameters are used.
-   2c. Does a multi sequence alignment for multi-FASTA files obtained in
-       Step 2b for future use. MAFFT software with automatic selection of
-       alignment algorithm is used in this step ('--auto').
-   2d. Trains hidden Markov models using HMMer for each of the aligned
-       KO-specific FASTA files obtained in Step 2c. This is performed with
-       'hmmbuild' using the default settings.
-
-   Step 2 may be reasonable to be re-done if the user wants to tweak the
-   settings in proteins filtering, clustering, multi sequence alignment or
-   HMMs training steps. However, it requires to have KO-specific protein
-   FASTA files obtained in Step 1a. As such files are not provided in
-   RAVEN and BioMet ToolBox, the user can only generate these files from
-   KEGG FTP dump files, so KEGG FTP license is needed.
-
-   3a. Queries the HMMs with sequences for the organism you are making a
-       model for. This step uses both the output from step 1a and from 2d.
-       This is done with 'hmmsearch' function under default settings. The
-       significance threshold value set in 'cutOff' parameter is used
-       later when parsing '*.out' files to filter out KO hits with higher
-       value than 'cutOff' value. The results with passable E values are
-       summarised into KO-gene occurence matrix with E values in
-       intersections as 'koGeneMat'. The parameters 'minScoreRatioG' and
-       'minScoreRatioKO' are then applied to 'prune' KO-gene associations
-       (see the function descriptions above for more details). The
-       intersection values for these 'prunable' associations are converted
-       to zeroes.
-   3b. Constructs a model based on the pre-processed KO-gene association
-       matrix (koGeneMat). As the full KEGG model already has reaction-KO
-       relationships, KOs are converted into the query genes. The final
-       draft model contains only these reactions, which are associated
-       with KOs from koGeneMat. The reactions without the genes may also
-       be included, if the user set keepSpontaneous as 'true'.
-
-   The Step 3 is specific to the organism for which the model is
-   reconstructed.
-
-   In principle the function looks at which output that is already available
-   and runs only the parts that are required for step 3. This means
-   that (see the definition of the parameters for details):
-   -1a is only performed if there are no KEGG model files in the
-   RAVEN\external\kegg directory
-   -1b is only performed if not all required HMMs OR aligned FASTA files
-   OR multi-FASTA files exist in the defined dataDir. This means that this
-   step is skipped if the HMMs are downloaded from BioMet Toolbox instead
-   (see above). If not all files exist it will try to find
-   the KEGG database files in dataDir.
-   -2a is only performed if not all required HMMs OR aligned FASTA files
-   files exist in the defined dataDir. This means that this step is skipped
-   if the HMMs are downloaded from BioMet Toolbox instead (see above).
-   -2b is only performed if not all required HMMs exist in the defined
-   dataDir. This means that this step is skipped if the FASTA files or
-   HMMs are downloaded from BioMet Toolbox instead (see above).
-   -3a is performed for the required HMMs for which no corresponding .out
-   file exists in outDir. This is just a way to enable the function to be
-   run in parallel or to resume if interrupted.
-   -3b is always performed.
-
-   These steps are specific to the organism for which you are
-   reconstructing the model.
-
-   Regarding the whole pipeline, the function checks the output that is
-   already available and runs only the parts that are required for step 3.
-   This means that (see the definition of the parameters for details):
-   -1a is only performed if there are no KEGG model files in the
-   RAVEN\external\kegg directory.
-   -1b is only performed if any of required KOs do not have HMMs, aligned
-   FASTA files, clustered FASTA files and raw FASTA files in the defined
-   dataDir. This means that this step is skipped if the HMMs are
-   downloaded from BioMet Toolbox instead (see above). If not all files
-   exist it will try to find the KEGG database files in dataDir.
-   -2ab are only performed if any of required KOs do not have HMMs,
-   aligned FASTA files and clustered FASTA files in the defined dataDir.
-   This means that this step is skipped if the HMMs are downloaded from
-   BioMet Toolbox instead (see above).
-   -2c is only performed if any of required KOs do not have HMMs and
-   aligned FASTA files in the defined dataDir. This means that this step
-   is skipped if the HMMs are downloaded from BioMet Toolbox instead (see
-   above).
-   -2d is only performed if any of required KOs do not have HMMs exist in
-   the defined dataDir. This means that this step is skipped if the FASTA
-   files or HMMs are downloaded from BioMet Toolbox instead (see above).
-   -3a is performed for the required HMMs for which no corresponding .out
-   file exists in outDir. This is just a way to enable the function to be
-   run in parallel or to resume if interrupted.
-   -3b is always performed.
-
-   NOTE: it is also possible to obtain draft model from KEGG without
-   providing protein FASTA file for the target organism. In such case the
-   organism three-four letter abbreviation set as 'organismID' must exist
-   in the local KEGG database. In such case, the program just fetches all
-   the reactions, which are associated with given 'organismID'.
-
- Usage: model=getKEGGModelForOrganism(organismID,fastaFile,dataDir,...
-    outDir,keepSpontaneous,keepUndefinedStoich,keepIncomplete,...
-    keepGeneral,cutOff,minScoreRatioKO,minScoreRatioG,maxPhylDist,...
-    nSequences,seqIdentity)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 function model=getKEGGModelForOrganism(organismID,fastaFile,dataDir,...
-0002     outDir,keepSpontaneous,keepUndefinedStoich,keepIncomplete,...
-0003     keepGeneral,cutOff,minScoreRatioKO,minScoreRatioG,maxPhylDist,...
-0004     nSequences,seqIdentity,globalModel)
-0005 % getKEGGModelForOrganism
-0006 %   Reconstructs a genome-scale metabolic model based on protein homology
-0007 %   to the orthologies in KEGG. If the target species is not available in
-0008 %   KEGG, the user must select a closely related species. It is also
-0009 %   possible to circumvent protein homology search (see fastaFile parameter
-0010 %   for more details)
-0011 %
-0012 %   Input:
-0013 %   organismID          three or four letter abbreviation of the organism
-0014 %                       (as used in KEGG). If not available, use a closely
-0015 %                       related species. This is used for determing the
-0016 %                       phylogenetic distance. Use 'eukaryotes' or
-0017 %                       'prokaryotes' to get a model for the whole domain.
-0018 %                       Only applicable if fastaFile is empty, i.e. no
-0019 %                       homology search should be performed
-0020 %   fastaFile           a FASTA file that contains the protein sequences of
-0021 %                       the organism for which to reconstruct a model (optional,
-0022 %                       if no FASTA file is supplied then a model is
-0023 %                       reconstructed based only on the organism
-0024 %                       abbreviation. This option ignores all settings
-0025 %                       except for keepSpontaneous, keepUndefinedStoich,
-0026 %                       keepIncomplete and keepGeneral)
-0027 %   dataDir             directory for which to retrieve the input data.
-0028 %                       Should contain a combination of these sub-folders:
-0029 %                       -dataDir\keggdb
-0030 %                           The KEGG database files used in 1a (see below)
-0031 %                       -dataDir\fasta
-0032 %                           The multi-FASTA files generated in 1b (see
-0033 %                           below)
-0034 %                       -dataDir\aligned
-0035 %                           The aligned FASTA files as generated in 2a (see
-0036 %                           below)
-0037 %                       -dataDir\hmms
-0038 %                           The hidden Markov models as generated in 2b or
-0039 %                           downloaded from BioMet Toolbox (see below)
-0040 %                       The final directory in dataDir should be styled as
-0041 %                       prok90_kegg116 or euk90_kegg116, indicating whether
-0042 %                       the HMMs were trained on pro- or eukaryotic
-0043 %                       sequences; using which sequence similarity treshold
-0044 %                       (first set of digits); using which KEGG version
-0045 %                       (second set of digits). (this parameter should
-0046 %                       ALWAYS be provided)
-0047 %   outDir              directory to save the results from the quering of
-0048 %                       the hidden Markov models. The output is specific
-0049 %                       for the input sequences and the settings used. It
-0050 %                       is stored in this manner so that the function can
-0051 %                       continue if interrupted or if it should run in
-0052 %                       parallel. Be careful not to leave output files from
-0053 %                       different organisms or runs with different settings
-0054 %                       in the same folder. They will not be overwritten
-0055 %                       (optional, default is a temporary dir where all *.out
-0056 %                       files are deleted before and after doing the
-0057 %                       reconstruction)
-0058 %   keepSpontaneous     include reactions labeled as "spontaneous". (optional,
-0059 %                       default true)
-0060 %   keepUndefinedStoich    include reactions in the form n A <=> n+1 A. These
-0061 %                       will be dealt with as two separate metabolites
-0062 %                       (optional, default true)
-0063 %   keepIncomplete      include reactions which have been labelled as
-0064 %                       "incomplete", "erroneous" or "unclear" (optional,
-0065 %                       default true)
-0066 %   keepGeneral         include reactions which have been labelled as
-0067 %                       "general reaction". These are reactions on the form
-0068 %                       "an aldehyde <=> an alcohol", and are therefore
-0069 %                       unsuited for modelling purposes. Note that not all
-0070 %                       reactions have this type of annotation, and the
-0071 %                       script will therefore not be able to remove all
-0072 %                       such reactions (optional, default false)
-0073 %   cutOff              significance score from HMMer needed to assign
-0074 %                       genes to a KO (optional, default 10^-50)
-0075 %   minScoreRatioG      a gene is only assigned to KOs for which the score
-0076 %                       is >=log(score)/log(best score) for that gene. This
-0077 %                       is to prevent that a gene which clearly belongs to
-0078 %                       one KO is assigned also to KOs with much lower
-0079 %                       scores (optional, default 0.8 (lower is less strict))
-0080 %   minScoreRatioKO     ignore genes in a KO if their score is
-0081 %                       <log(score)/log(best score in KO). This is to
-0082 %                       "prune" KOs which have many genes and where some are
-0083 %                       clearly a better fit (optional, default 0.3 (lower is
-0084 %                       less strict))
-0085 %   maxPhylDist         -1: only use sequences from the same domain
-0086 %                       (Prokaryota, Eukaryota)
-0087 %                       other (positive) value: only use sequences for
-0088 %                       organisms where the phylogenetic distance is at the
-0089 %                       most this large (as calculated in getPhylDist)
-0090 %                       (optional, default Inf, which means that all sequences
-0091 %                       will be used)
-0092 %   nSequences          for each KO, use up to this many sequences from the
-0093 %                       most closely related species. This is mainly to
-0094 %                       speed up the alignment process for KOs with very
-0095 %                       many genes. This subsampling is performed before
-0096 %                       running CD-HIT (optional, default inf)
-0097 %   seqIdentity         sequence identity threshold in CD-HIT, referred as
-0098 %                       "global sequence identity" in CD-HIT User's Guide.
-0099 %                       If -1 is provided, CD-HIT is skipped (optional, default 0.9)
-0100 %   globalModel         structure containing both model and KOModel
-0101 %                       structures as generated by getModelFromKEGG. These
-0102 %                       will otherwise be loaded by via getModelFromKEGG.
-0103 %                       Providing globalKEGGmodel can speed up model
-0104 %                       generation if getKEGGModelForOrganism is run
-0105 %                       multiple times for different strains. Example:
-0106 %                       [globalModel.model,globalModel.KOModel] = getModelFromKEGG;
-0107 %                       (optional, default empty, global model is loaded by
-0108 %                       getModelFromKEGG)
-0109 %
-0110 %   Output:
-0111 %   model               the reconstructed model
-0112 %
-0113 %   PLEASE READ THIS: The input to this function can be confusing, because
-0114 %   it is intended to be run in parallel on a cluster or in multiple
-0115 %   sessions. It therefore saves a lot of intermediate results to storage.
-0116 %   This also serves the purpose of not having to do redundant
-0117 %   calculations. This, however, comes with the disadvantage of somewhat
-0118 %   trickier handling. This is what this function does:
-0119 %
-0120 %   1a. Loads files from a local KEGG FTP dump and constructs a general
-0121 %       RAVEN model representing the metabolic network. The functions
-0122 %       getRxnsFromKEGG, getGenesFromKEGG, getMetsFromKEGG summarise the
-0123 %       data into 'keggRxns.mat', 'keggGenes.mat' and 'keggMets.mat' files,
-0124 %       which are later merged into 'keggModel.mat' by getModelFromKEGG
-0125 %       function. The function getPhylDist generates 'keggPhylDist.mat'
-0126 %       file. KEGG FTP access requires a <a href="matlab:
-0127 %       web('http://www.bioinformatics.jp/en/keggftp.html')">license</a>.
-0128 %   1b. Generates protein FASTA files from the KEGG FTP dump (see 1a). One
-0129 %       multi-FASTA file for each KO in KEGG is generated.
-0130 %
-0131 %   The Step 1 has to be re-done every time KEGG updates their database (or
-0132 %   rather when the updates are large enough to warrant re-running this
-0133 %   part). Many users would probably never use this feature.
-0134 %
-0135 %   2a. Filters KO-specific protein sets. This is done by using the
-0136 %       settings "maxPhylDist" and "nSequences" to control which sequences
-0137 %       should be used for constructing Hidden Markov models (HMMs), and
-0138 %       later for matching your sequences to.
-0139 %       The most common alternatives here would be to use sequences from
-0140 %       only eukaryotes, only prokaryotes or all sequences in KEGG, but you
-0141 %       could also play around with the parameters to use e.g. only fungal
-0142 %       sequences.
-0143 %   2b. KO-specific protein FASTA files are re-organised into
-0144 %       non-redundant protein sets with CD-HIT. The user can only set
-0145 %       seqIdentity parameter, which corresponds to '-c' parameter in
-0146 %       CD-HIT, described as "sequence identity threshold". CD-HIT suggsted
-0147 %       sequence identity specific word_length (-n) parameters are used.
-0148 %   2c. Does a multi sequence alignment for multi-FASTA files obtained in
-0149 %       Step 2b for future use. MAFFT software with automatic selection of
-0150 %       alignment algorithm is used in this step ('--auto').
-0151 %   2d. Trains hidden Markov models using HMMer for each of the aligned
-0152 %       KO-specific FASTA files obtained in Step 2c. This is performed with
-0153 %       'hmmbuild' using the default settings.
-0154 %
-0155 %   Step 2 may be reasonable to be re-done if the user wants to tweak the
-0156 %   settings in proteins filtering, clustering, multi sequence alignment or
-0157 %   HMMs training steps. However, it requires to have KO-specific protein
-0158 %   FASTA files obtained in Step 1a. As such files are not provided in
-0159 %   RAVEN and BioMet ToolBox, the user can only generate these files from
-0160 %   KEGG FTP dump files, so KEGG FTP license is needed.
-0161 %
-0162 %   3a. Queries the HMMs with sequences for the organism you are making a
-0163 %       model for. This step uses both the output from step 1a and from 2d.
-0164 %       This is done with 'hmmsearch' function under default settings. The
-0165 %       significance threshold value set in 'cutOff' parameter is used
-0166 %       later when parsing '*.out' files to filter out KO hits with higher
-0167 %       value than 'cutOff' value. The results with passable E values are
-0168 %       summarised into KO-gene occurence matrix with E values in
-0169 %       intersections as 'koGeneMat'. The parameters 'minScoreRatioG' and
-0170 %       'minScoreRatioKO' are then applied to 'prune' KO-gene associations
-0171 %       (see the function descriptions above for more details). The
-0172 %       intersection values for these 'prunable' associations are converted
-0173 %       to zeroes.
-0174 %   3b. Constructs a model based on the pre-processed KO-gene association
-0175 %       matrix (koGeneMat). As the full KEGG model already has reaction-KO
-0176 %       relationships, KOs are converted into the query genes. The final
-0177 %       draft model contains only these reactions, which are associated
-0178 %       with KOs from koGeneMat. The reactions without the genes may also
-0179 %       be included, if the user set keepSpontaneous as 'true'.
-0180 %
-0181 %   The Step 3 is specific to the organism for which the model is
-0182 %   reconstructed.
-0183 %
-0184 %   In principle the function looks at which output that is already available
-0185 %   and runs only the parts that are required for step 3. This means
-0186 %   that (see the definition of the parameters for details):
-0187 %   -1a is only performed if there are no KEGG model files in the
-0188 %   RAVEN\external\kegg directory
-0189 %   -1b is only performed if not all required HMMs OR aligned FASTA files
-0190 %   OR multi-FASTA files exist in the defined dataDir. This means that this
-0191 %   step is skipped if the HMMs are downloaded from BioMet Toolbox instead
-0192 %   (see above). If not all files exist it will try to find
-0193 %   the KEGG database files in dataDir.
-0194 %   -2a is only performed if not all required HMMs OR aligned FASTA files
-0195 %   files exist in the defined dataDir. This means that this step is skipped
-0196 %   if the HMMs are downloaded from BioMet Toolbox instead (see above).
-0197 %   -2b is only performed if not all required HMMs exist in the defined
-0198 %   dataDir. This means that this step is skipped if the FASTA files or
-0199 %   HMMs are downloaded from BioMet Toolbox instead (see above).
-0200 %   -3a is performed for the required HMMs for which no corresponding .out
-0201 %   file exists in outDir. This is just a way to enable the function to be
-0202 %   run in parallel or to resume if interrupted.
-0203 %   -3b is always performed.
-0204 %
-0205 %   These steps are specific to the organism for which you are
-0206 %   reconstructing the model.
-0207 %
-0208 %   Regarding the whole pipeline, the function checks the output that is
-0209 %   already available and runs only the parts that are required for step 3.
-0210 %   This means that (see the definition of the parameters for details):
-0211 %   -1a is only performed if there are no KEGG model files in the
-0212 %   RAVEN\external\kegg directory.
-0213 %   -1b is only performed if any of required KOs do not have HMMs, aligned
-0214 %   FASTA files, clustered FASTA files and raw FASTA files in the defined
-0215 %   dataDir. This means that this step is skipped if the HMMs are
-0216 %   downloaded from BioMet Toolbox instead (see above). If not all files
-0217 %   exist it will try to find the KEGG database files in dataDir.
-0218 %   -2ab are only performed if any of required KOs do not have HMMs,
-0219 %   aligned FASTA files and clustered FASTA files in the defined dataDir.
-0220 %   This means that this step is skipped if the HMMs are downloaded from
-0221 %   BioMet Toolbox instead (see above).
-0222 %   -2c is only performed if any of required KOs do not have HMMs and
-0223 %   aligned FASTA files in the defined dataDir. This means that this step
-0224 %   is skipped if the HMMs are downloaded from BioMet Toolbox instead (see
-0225 %   above).
-0226 %   -2d is only performed if any of required KOs do not have HMMs exist in
-0227 %   the defined dataDir. This means that this step is skipped if the FASTA
-0228 %   files or HMMs are downloaded from BioMet Toolbox instead (see above).
-0229 %   -3a is performed for the required HMMs for which no corresponding .out
-0230 %   file exists in outDir. This is just a way to enable the function to be
-0231 %   run in parallel or to resume if interrupted.
-0232 %   -3b is always performed.
-0233 %
-0234 %   NOTE: it is also possible to obtain draft model from KEGG without
-0235 %   providing protein FASTA file for the target organism. In such case the
-0236 %   organism three-four letter abbreviation set as 'organismID' must exist
-0237 %   in the local KEGG database. In such case, the program just fetches all
-0238 %   the reactions, which are associated with given 'organismID'.
-0239 %
-0240 % Usage: model=getKEGGModelForOrganism(organismID,fastaFile,dataDir,...
-0241 %    outDir,keepSpontaneous,keepUndefinedStoich,keepIncomplete,...
-0242 %    keepGeneral,cutOff,minScoreRatioKO,minScoreRatioG,maxPhylDist,...
-0243 %    nSequences,seqIdentity)
-0244 
-0245 if nargin<2 || isempty(fastaFile)
-0246     fastaFile=[];
-0247 else
-0248     fastaFile=char(fastaFile);
-0249 end
-0250 if nargin<3
-0251     dataDir=[];
-0252 else
-0253     dataDir=char(dataDir);
-0254 end
-0255 if nargin<4 || isempty(outDir)
-0256     outDir=tempdir;
-0257     %Delete all *.out files if any exist
-0258     delete(fullfile(outDir,'*.out'));
-0259 else
-0260     outDir=char(outDir);
-0261 end
-0262 if nargin<5 || isempty(keepSpontaneous)
-0263     keepSpontaneous=true;
-0264 end
-0265 if nargin<6 || isempty(keepUndefinedStoich)
-0266     keepUndefinedStoich=true;
-0267 end
-0268 if nargin<7 || isempty(keepIncomplete)
-0269     keepIncomplete=true;
-0270 end
-0271 if nargin<8 || isempty(keepGeneral)
-0272     keepGeneral=false;
-0273 end
-0274 if nargin<9 || isempty(cutOff)
-0275     cutOff=10^-50;
-0276 end
-0277 if nargin<10 || isempty(minScoreRatioKO)
-0278     minScoreRatioKO=0.3;
-0279 end
-0280 if nargin<11 || isempty(minScoreRatioG)
-0281     minScoreRatioG=0.8;
-0282 end
-0283 if nargin<12 || isempty(maxPhylDist)
-0284     maxPhylDist=inf;
-0285     %Include all sequences for each reaction
-0286 end
-0287 if nargin<13 || isempty(nSequences)
-0288     nSequences=inf;
-0289     %Include all sequences for each reaction
-0290 end
-0291 if nargin<14 || isempty(seqIdentity)
-0292     seqIdentity=0.9;
-0293 end
-0294 
-0295 if isempty(fastaFile)
-0296     fprintf(['\n*** The model reconstruction from KEGG based on the annotation available for KEGG Species <strong>' organismID '</strong> ***\n\n']);
-0297 else
-0298     fprintf('\n*** The model reconstruction from KEGG based on the protein homology search against KEGG Orthology specific HMMs ***\n\n');
-0299     %Check if query fasta exists
-0300     fastaFile=checkFileExistence(fastaFile,2); %Copy file to temp dir
-0301 end
-0302 
-0303 %Run the external binaries multi-threaded to use all logical cores assigned
-0304 %to MATLAB
-0305 cores = evalc('feature(''numcores'')');
-0306 cores = strsplit(cores, 'MATLAB was assigned: ');
-0307 cores = regexp(cores{2},'^\d*','match');
-0308 cores = cores{1};
-0309 
-0310 %Get the directory for RAVEN Toolbox.
-0311 ravenPath=findRAVENroot();
-0312 
-0313 %Checking if dataDir is consistent. It must point to pre-trained HMMs set,
-0314 %compatible with the the current RAVEN version. The user may have the
-0315 %required zip file already in working directory or have it extracted. If
-0316 %the zip file and directory is not here, it is downloaded from the cloud
-0317 if ~isempty(dataDir)
-0318     hmmOptions={'euk90_kegg116','prok90_kegg116'};
-0319     if ~endsWith(dataDir,hmmOptions) %Check if dataDir ends with any of the hmmOptions.
-0320         %If not, then check whether the required folders exist anyway.
-0321         if ~isfile(fullfile(dataDir,'keggdb','genes.pep')) && ...
-0322                 ~isfolder(fullfile(dataDir,'fasta')) && ...
-0323                 ~isfolder(fullfile(dataDir,'aligned')) && ...
-0324                 ~isfolder(fullfile(dataDir,'hmms'))
-0325             error(['Pre-trained HMMs set is not recognised. If you want download RAVEN provided sets, it should match any of the following: ' strjoin(hmmOptions,' or ')])
-0326         end
-0327     else
-0328         if isfolder(dataDir) && isfile(fullfile(dataDir,'hmms','K00844.hmm'))
-0329             fprintf(['NOTE: Found <strong>' dataDir '</strong> directory with pre-trained HMMs, it will therefore be used during reconstruction\n']);
-0330         elseif ~isfolder(dataDir) && isfile([dataDir,'.zip'])
-0331             fprintf('Extracting the HMMs archive file... ');
-0332             unzip([dataDir,'.zip']);
-0333             fprintf('COMPLETE\n');
-0334         else
-0335             hmmIndex=strcmp(dataDir,hmmOptions);
-0336             if ~any(hmmIndex)
-0337                 error(['Pre-trained HMMs are only provided with proteins clustered at 90% sequence identity (i.e. prok90_kegg116 and euk90_kegg116). ' ...
-0338                     'Use either of these datasets, or otherwise download the relevant sequence data from KEGG to train HMMs with your desired sequence identity'])
-0339             else
-0340                 fprintf('Downloading the HMMs archive file... ');
-0341                 try
-0342                     websave([dataDir,'.zip'],['https://github.com/SysBioChalmers/RAVEN/releases/download/v2.11.0/',hmmOptions{hmmIndex},'.zip']);
-0343                 catch ME
-0344                     if strcmp(ME.identifier,'MATLAB:webservices:HTTP404StatusCodeError')
-0345                         error('Failed to download the HMMs archive file, the server returned a 404 error, try again later. If the problem persists please report it on the RAVEN GitHub Issues page: https://github.com/SysBioChalmers/RAVEN/issues')
-0346                     end
-0347                 end
-0348             end
-0349 
-0350             fprintf('COMPLETE\n');
-0351             fprintf('Extracting the HMMs archive file... ');
-0352             unzip([dataDir,'.zip']);
-0353             fprintf('COMPLETE\n');
-0354         end
-0355         %Check if HMMs are extracted
-0356         if ~isfile(fullfile(dataDir,'hmms','K00844.hmm'))
-0357             error(['The HMM files seem improperly extracted and not found in ',dataDir,'/hmms. Please remove ',dataDir,' folder and rerun getKEGGModelForOrganism']);
-0358         end
-0359     end
-0360 end
-0361 
-0362 %Check if the fasta-file contains '/' or'\'. If not then it's probably just
-0363 %a file name. Expand to full path.
-0364 if any(fastaFile)
-0365     if ~any(strfind(fastaFile,'\')) && ~any(strfind(fastaFile,'/'))
-0366         fastaFile=which(fastaFile);
-0367     end
-0368     %Create the required sub-folders in dataDir if they dont exist
-0369     if ~isfolder(fullfile(dataDir,'keggdb'))
-0370         mkdir(dataDir,'keggdb');
-0371     end
-0372     if ~isfolder(fullfile(dataDir,'fasta'))
-0373         mkdir(dataDir,'fasta');
-0374     end
-0375     if ~isfolder(fullfile(dataDir,'aligned'))
-0376         mkdir(dataDir,'aligned');
-0377     end
-0378     if ~isfolder(fullfile(dataDir,'hmms'))
-0379         mkdir(dataDir,'hmms');
-0380     end
-0381     if ~isfolder(outDir)
-0382         mkdir(outDir);
-0383     end
-0384 end
-0385 
-0386 %First generate the full global KEGG model. Can be provided as input.
-0387 %Otherwise, getModelFromKEGG is run. The dataDir must not be supplied as
-0388 %there is also an internal RAVEN version available
-0389 if nargin==15
-0390     model=globalModel.model;
-0391     KOModel=globalModel.KOModel;
-0392 elseif any(dataDir)
-0393     [model, KOModel]=getModelFromKEGG(fullfile(dataDir,'keggdb'),keepSpontaneous,keepUndefinedStoich,keepIncomplete,keepGeneral);
-0394 else
-0395     [model, KOModel]=getModelFromKEGG([],keepSpontaneous,keepUndefinedStoich,keepIncomplete,keepGeneral);
-0396 end
-0397 model.id=organismID;
-0398 model.c=zeros(numel(model.rxns),1);
-0399 
-0400 %If no FASTA file is supplied, then just remove all genes which are not for
-0401 %the given organism ID
-0402 if isempty(fastaFile)
-0403     %Check if organismID can be found in KEGG species list or is
-0404     %set to "eukaryotes" or "prokaryotes"
-0405     phylDistsFull=getPhylDist(fullfile(dataDir,'keggdb'),true);
-0406     if ~ismember(organismID,[phylDistsFull.ids 'eukaryotes' 'prokaryotes'])
-0407         error('Provided organismID is incorrect. Only species abbreviations from KEGG Species List or "eukaryotes"/"prokaryotes" are allowed.');
-0408     end
-0409 
-0410     fprintf(['Pruning the model from <strong>non-' organismID '</strong> genes... ']);
-0411     if ismember(organismID,{'eukaryotes','prokaryotes'})
-0412         phylDists=getPhylDist(fullfile(dataDir,'keggdb'),maxPhylDist==-1);
-0413         if strcmp(organismID,'eukaryotes')
-0414             proxyid='hsa';
-0415             %Use H. sapiens here
-0416         else
-0417             proxyid='eco';
-0418             %Use E. coli here
-0419         end
-0420         [~, phylDistId]=ismember(proxyid,phylDists.ids);
-0421         idsToKeep=phylDists.ids(~isinf(phylDists.distMat(phylDistId,:)));
-0422         taxIDs=cellfun(@(x) x{1},cellfun(@(x) strsplit(x,':'),model.genes,'UniformOutput',false),'UniformOutput',false);
-0423         I=ismember(upper(taxIDs),upper(idsToKeep));
-0424     else
-0425         %KEGG organism IDs may have three or four letters
-0426         organismID=strcat(organismID,':');
-0427         %Add colon for accurate matching
-0428         if length(organismID)==4
-0429             I=cellfun(@(x) strcmpi(x(1:4),organismID),model.genes);
-0430         elseif length(organismID)==5
-0431             I=cellfun(@(x) strcmpi(x(1:5),organismID),model.genes);
-0432         end
-0433     end
-0434     %Remove those genes
-0435     model.genes=model.genes(I);
-0436     model.rxnGeneMat=model.rxnGeneMat(:,I);
-0437     fprintf('COMPLETE\n');
-0438 end
-0439 
-0440 %First remove all reactions without genes
-0441 if keepSpontaneous==true
-0442     fprintf('Removing non-spontaneous reactions without GPR rules... ');
-0443     load(fullfile(ravenPath,'external','kegg','keggRxns.mat'),'isSpontaneous');
-0444     I=~any(model.rxnGeneMat,2)&~ismember(model.rxns,isSpontaneous);
-0445     spontRxnsWithGenes=model.rxns(any(model.rxnGeneMat,2)&~ismember(model.rxns,isSpontaneous));
-0446 else
-0447     fprintf('Removing reactions without GPR rules... ');
-0448     I=~any(model.rxnGeneMat,2);
-0449 end
-0450 model=removeReactions(model,I,true);
-0451 fprintf('COMPLETE\n');
-0452 
-0453 %Clean gene names
-0454 fprintf('Fixing gene names in the model... ');
-0455 %Get rid of the prefix organism id
-0456 model.genes=regexprep(model.genes,'^\w+?:','');
-0457 fprintf('COMPLETE\n');
-0458 
-0459 %If no FASTA file is supplied, then we are done here
-0460 if isempty(fastaFile)
-0461     %Create grRules
-0462     fprintf('Constructing GPR associations and annotations for the model... ');
-0463     model.grRules=cell(numel(model.rxns),1);
-0464     model.grRules(:)={''};
-0465     %Add the gene associations as 'or'
-0466     for i=1:numel(model.rxns)
-0467         %Find the involved genes
-0468         I=find(model.rxnGeneMat(i,:));
-0469         if any(I)
-0470             model.grRules{i}=['(' model.genes{I(1)}];
-0471             for j=2:numel(I)
-0472                 model.grRules{i}=[model.grRules{i} ' or ' model.genes{I(j)}];
-0473             end
-0474             model.grRules{i}=[model.grRules{i} ')'];
-0475         end
-0476     end
-0477     %Fix grRules and reconstruct rxnGeneMat
-0478     [grRules,rxnGeneMat] = standardizeGrRules(model); %Give detailed output
-0479     model.grRules = grRules;
-0480     model.rxnGeneMat = rxnGeneMat;
-0481     %Add geneMiriams, assuming that it follows the syntax
-0482     %kegg.genes/organismID:geneName
-0483     model.geneMiriams='';
-0484     for i=1:numel(model.genes)
-0485         model.geneMiriams{i,1}.name{1,1}='kegg.genes';
-0486         model.geneMiriams{i,1}.value{1,1}=strcat(lower(organismID),model.genes{i,1});
-0487     end
-0488     %Add the description to the reactions
-0489     for i=1:numel(model.rxns)
-0490         if ~isempty(model.rxnNotes{i})
-0491             model.rxnNotes(i)=strcat('Included by getKEGGModelForOrganism (without HMMs).',model.rxnNotes(i));
-0492             model.rxnNotes(i)=strrep(model.rxnNotes(i),'.','. ');
-0493         else
-0494             model.rxnNotes(i)={'Included by getKEGGModelForOrganism (without HMMs)'};
-0495         end
-0496     end
-0497     fprintf('COMPLETE\n\n');
-0498     fprintf('*** Model reconstruction complete ***\n');
-0499     return;
-0500 end
-0501 
-0502 %Create a phylogenetic distance structure
-0503 phylDistStruct=getPhylDist(fullfile(dataDir,'keggdb'),maxPhylDist==-1);
-0504 [~, phylDistId]=ismember(model.id,phylDistStruct.ids);
-0505 
-0506 %Calculate the real maximal distance now. An abitary large number of 1000
-0507 %is used for the "all in kingdom" or "all sequences" options. This is a bit
-0508 %inconvenient way to do it, but it is to make it fit with some older code
-0509 if isinf(maxPhylDist) || maxPhylDist==-1
-0510     maxPhylDist=1000;
-0511 end
-0512 
-0513 %Get the KO ids for which files have been generated. Maybe not the neatest
-0514 %way..
-0515 fastaFiles=listFiles(fullfile(dataDir,'fasta','*.fa'));
-0516 alignedFiles=listFiles(fullfile(dataDir,'aligned','*.fa'));
-0517 alignedWorking=listFiles(fullfile(dataDir,'aligned','*.faw'));
-0518 hmmFiles=listFiles(fullfile(dataDir,'hmms','*.hmm'));
-0519 outFiles=listFiles(fullfile(outDir,'*.out'));
-0520 
-0521 %Check if multi-FASTA files should be generated. This should only be
-0522 %performed if there are IDs in the KOModel structure that haven't been
-0523 %parsed yet
-0524 missingFASTA=setdiff(KOModel.rxns,[fastaFiles;alignedFiles;hmmFiles;outFiles]);
-0525 
-0526 if ~isempty(missingFASTA)
-0527     if ~isfile(fullfile(dataDir,'keggdb','genes.pep'))
-0528         EM=['The file ''genes.pep'' cannot be located at ' strrep(dataDir,'\','/') '/ and should be downloaded from the KEGG FTP.\n'];
-0529         dispEM(EM);
-0530     end
-0531     %Only construct models for KOs which don't have files already
-0532     fastaModel=removeReactions(KOModel,setdiff(KOModel.rxns,missingFASTA),true,true);
-0533     %Permute the order of the KOs in the model so that constructMultiFasta
-0534     %can be run on several processors at once
-0535     fastaModel=permuteModel(fastaModel,randperm(RandStream.create('mrg32k3a','Seed',cputime()),numel(fastaModel.rxns)),'rxns');
-0536     constructMultiFasta(fastaModel,fullfile(dataDir,'keggdb','genes.pep'),fullfile(dataDir,'fasta'));
-0537 else
-0538     fprintf('Generating the KEGG Orthology specific multi-FASTA files... COMPLETE\n');
-0539 end
-0540 
-0541 if isunix
-0542     if ismac
-0543         binEnd='.mac';
-0544     else
-0545         binEnd='';
-0546     end
-0547 elseif ispc
-0548     binEnd='';
-0549 else
-0550     EM='Unknown OS, exiting.';
-0551     disp(EM);
-0552     return
-0553 end
-0554 
-0555 tmpFile=tempname;
-0556 %On Windows, paths need to be translated to Unix before parsing it to WSL
-0557 if ispc
-0558     wslPath.tmpFile=getWSLpath(tmpFile);
-0559     %mafft has problems writing to terminal (/dev/stderr) when running
-0560     %on WSL via MATLAB, instead write and read progress file
-0561     mafftOutput = tempname;
-0562     wslPath.mafftOutput=getWSLpath(mafftOutput);
-0563     wslPath.mafft=getWSLpath(fullfile(ravenPath,'software','mafft','mafft-linux64','mafft.bat'));
-0564     wslPath.hmmbuild=getWSLpath(fullfile(ravenPath,'software','hmmer','hmmbuild'));
-0565     wslPath.hmmsearch=getWSLpath(fullfile(ravenPath,'software','hmmer','hmmsearch'));
-0566     wslPath.cdhit=getWSLpath(fullfile(ravenPath,'software','cd-hit','cd-hit'));
-0567 end
-0568 
-0569 %Check if alignment of FASTA files should be performed
-0570 missingAligned=setdiff(KOModel.rxns,[alignedFiles;hmmFiles;alignedWorking;outFiles]);
-0571 if ~isempty(missingAligned)
-0572     if seqIdentity==-1
-0573         fprintf('Performing the multiple alignment for KEGG Orthology specific protein sets...   0%% complete');
-0574     else
-0575         fprintf('Performing clustering and multiple alignment for KEGG Orthology specific protein sets...   0%% complete');
-0576     end
-0577     missingAligned=missingAligned(randperm(RandStream.create('mrg32k3a','Seed',cputime()),numel(missingAligned)));
-0578 
-0579     for i=1:numel(missingAligned)
-0580         %This is checked here because it could be that it is created by a
-0581         %parallel process. The faw-files are saved as temporary files to
-0582         %kept track of which files are being worked on
-0583         if ~isfile(fullfile(dataDir,'aligned',[missingAligned{i} '.faw'])) &&...
-0584                 ~isfile(fullfile(dataDir,'aligned',[missingAligned{i} '.fa']))
-0585             %Check that the multi-FASTA file exists. It should do so since
-0586             %we are saving empty files as well. Print a warning and
-0587             %continue if not
-0588             if ~isfile(fullfile(dataDir,'fasta',[missingAligned{i} '.fa']))
-0589                 EM=['WARNING: The multi-FASTA file for ' missingAligned{i} ' does not exist'];
-0590                 dispEM(EM,false);
-0591                 continue;
-0592             end
-0593 
-0594             %If the multi-FASTA file is empty then save an empty aligned
-0595             %file and continue
-0596             s=dir(fullfile(dataDir,'fasta',[missingAligned{i} '.fa']));
-0597             if s.bytes<=0
-0598                 fid=fopen(fullfile(dataDir,'aligned',[missingAligned{i} '.fa']),'w');
-0599                 fclose(fid);
-0600                 continue;
-0601             end
-0602 
-0603             %Create an empty file to prevent other threads to start to work
-0604             %on the same alignment
-0605             fid=fopen(fullfile(dataDir,'aligned',[missingAligned{i} '.faw']),'w');
-0606             fclose(fid);
-0607 
-0608             %First load the FASTA file, then select up to nSequences
-0609             %sequences of the most closely related species, apply any
-0610             %constraints from maxPhylDist, and save it as a temporary file,
-0611             %and create the model from that
-0612 
-0613             fastaStruct=fastaread(fullfile(dataDir,'fasta',[missingAligned{i} '.fa']));
-0614             phylDist=inf(numel(fastaStruct),1);
-0615             for j=1:numel(fastaStruct)
-0616                 %Get the organism abbreviation
-0617                 index=strfind(fastaStruct(j).Header,':');
-0618                 if any(index)
-0619                     abbrev=fastaStruct(j).Header(1:index(1)-1);
-0620                     [~, index]=ismember(abbrev,phylDistStruct.ids);
-0621                     if any(index)
-0622                         phylDist(j)=phylDistStruct.distMat(index(1),phylDistId);
-0623                     end
-0624                 end
-0625             end
-0626 
-0627             %Inf means that it should not be included
-0628             phylDist(phylDist>maxPhylDist)=[];
-0629 
-0630             %Sort based on phylDist
-0631             [~, order]=sort(phylDist);
-0632 
-0633             %Save the first nSequences hits to a temporary FASTA file
-0634             if nSequences<=numel(fastaStruct)
-0635                 fastaStruct=fastaStruct(order(1:nSequences));
-0636             else
-0637                 fastaStruct=fastaStruct(order);
-0638             end
-0639 
-0640             %Do the clustering and alignment if there are more than one
-0641             %sequences, otherwise just save the sequence (or an empty file)
-0642             if numel(fastaStruct)>1
-0643                 if seqIdentity~=-1
-0644                     cdhitInpCustom=tempname;
-0645                     fastawrite(cdhitInpCustom,fastaStruct);
-0646                     if seqIdentity<=1 && seqIdentity>0.7
-0647                         nparam='5';
-0648                     elseif seqIdentity>0.6
-0649                         nparam='4';
-0650                     elseif seqIdentity>0.5
-0651                         nparam='3';
-0652                     elseif seqIdentity>0.4
-0653                         nparam='2';
-0654                     else
-0655                         EM='The provided seqIdentity must be between 0 and 1\n';
-0656                         dispEM(EM);
-0657                     end
-0658                     if ispc
-0659                         wslPath.cdhitInpCustom=getWSLpath(cdhitInpCustom);
-0660                         [status, output]=system(['wsl "' wslPath.cdhit '" -T "' num2str(cores) '" -i "' wslPath.cdhitInpCustom '" -o "' wslPath.tmpFile '" -c "' num2str(seqIdentity) '" -n ' nparam ' -M 2000']);
-0661                     elseif ismac || isunix
-0662                         [status, output]=system(['"' fullfile(ravenPath,'software','cd-hit',['cd-hit' binEnd]) '" -T "' num2str(cores) '" -i "' cdhitInpCustom '" -o "' tmpFile '" -c "' num2str(seqIdentity) '" -n ' nparam ' -M 2000']);
-0663                     end
-0664                     if status~=0
-0665                         EM=['Error when performing clustering of ' missingAligned{i} ':\n' output];
-0666                         dispEM(EM);
-0667                     end
-0668                     %Remove the old tempfile
-0669                     if exist(cdhitInpCustom, 'file')
-0670                         delete([cdhitInpCustom '*']);
-0671                     end
-0672                 else
-0673                     %This means that CD-HIT should be skipped since
-0674                     %seqIdentity is equal to -1
-0675                     fastawrite(tmpFile,fastaStruct);
-0676                 end
-0677                 %Do the alignment for this file
-0678                 if ismac
-0679                     [status, output]=system(['"' fullfile(ravenPath,'software','mafft','mafft-mac','mafft.bat') '" --auto --anysymbol --thread "' num2str(cores) '" "' tmpFile '" > "' fullfile(dataDir,'aligned',[missingAligned{i} '.faw']) '"']);
-0680                 elseif isunix
-0681                     [status, output]=system(['"' fullfile(ravenPath,'software','mafft','mafft-linux64','mafft.bat') '" --auto --anysymbol --thread "' num2str(cores) '" "' tmpFile '" > "' fullfile(dataDir,'aligned',[missingAligned{i} '.faw']) '"']);
-0682                 elseif ispc
-0683                     wslPath.fawFile=getWSLpath(fullfile(dataDir,'aligned',[missingAligned{i} '.faw']));
-0684                     [status, ~]=system(['wsl "' wslPath.mafft '" --auto --anysymbol --progress "' wslPath.mafftOutput '" --thread "' num2str(cores) '" --out "' wslPath.fawFile '" "' wslPath.tmpFile '"']);
-0685                     output=fileread(mafftOutput);
-0686                     delete(mafftOutput);
-0687                 end
-0688                 if status~=0
-0689                     %It could be that alignment failed because only one
-0690                     %sequence was left after clustering. If that is the
-0691                     %case, then the clustered file is just copied as 'faw'
-0692                     %file
-0693                     if any(regexp(output,'Only 1 sequence found'))
-0694                         movefile(tmpFile,fullfile(dataDir,'aligned',[missingAligned{i} '.faw']),'f');
-0695                     else
-0696                         EM=['Error when performing alignment of ' missingAligned{i} ':\n' output];
-0697                         dispEM(EM);
-0698                     end
-0699                 end
-0700                 %Remove the old tempfile
-0701                 if exist(tmpFile, 'file')
-0702                     delete([tmpFile '*']);
-0703                 end
-0704             else
-0705                 %If there is only one sequence then it's not possible to do
-0706                 %a multiple alignment. Just print the sequence instead. An
-0707                 %empty file was written previously so that doesn't have to
-0708                 %be dealt with
-0709                 if numel(fastaStruct)==1
-0710                     warnState = warning; %Save the current warning state
-0711                     warning('off','Bioinfo:fastawrite:AppendToFile');
-0712                     fastawrite(fullfile(dataDir,'aligned',[missingAligned{i} '.faw']),fastaStruct);
-0713                     warning(warnState) %Reset warning state to previous settings
-0714                 end
-0715             end
-0716             %Move the temporary file to the real one
-0717             movefile(fullfile(dataDir,'aligned',[missingAligned{i} '.faw']),fullfile(dataDir,'aligned',[missingAligned{i} '.fa']),'f');
-0718 
-0719             %Print the progress every 25 files
-0720             if rem(i-1,25) == 0
-0721                 progress=num2str(floor(100*numel(listFiles(fullfile(dataDir,'aligned','*.fa')))/numel(KOModel.rxns)));
-0722                 progress=pad(progress,3,'left');
-0723                 fprintf('\b\b\b\b\b\b\b\b\b\b\b\b\b%s%% complete',progress);
-0724             end
-0725         end
-0726     end
-0727     fprintf('\b\b\b\b\b\b\b\b\b\b\b\b\bCOMPLETE\n');
-0728 else
-0729     if seqIdentity==-1
-0730         fprintf('Performing the multiple alignment for KEGG Orthology specific protein sets... COMPLETE\n');
-0731     else
-0732         fprintf('Performing clustering and multiple alignment for KEGG Orthology specific protein sets... COMPLETE\n');
-0733     end
-0734 end
-0735 
-0736 %Check if training of Hidden Markov models should be performed
-0737 missingHMMs=setdiff(KOModel.rxns,[hmmFiles;outFiles]);
-0738 if ~isempty(missingHMMs)
-0739     fprintf('Training the KEGG Orthology specific HMMs...   0%% complete');
-0740     missingHMMs=missingHMMs(randperm(RandStream.create('mrg32k3a','Seed',cputime()),numel(missingHMMs)));
-0741     %Train models for all missing KOs
-0742     for i=1:numel(missingHMMs)
-0743         %This is checked here because it could be that it is created by a
-0744         %parallel process
-0745         if ~isfile(fullfile(dataDir,'hmms',[missingHMMs{i} '.hmm'])) && ~isfile(fullfile(dataDir,'hmms',[missingHMMs{i} '.hmw']))
-0746             %Check that the aligned FASTA file exists. It could be that it
-0747             %is still being worked on by some other instance of the program
-0748             %(the .faw file should then exist). This should not happen on a
-0749             %single computer. It doesn't throw an error, because it should
-0750             %finalize the ones it can
-0751             if ~isfile(fullfile(dataDir,'aligned',[missingHMMs{i} '.fa']))
-0752                 EM=['The aligned FASTA file for ' missingHMMs{i} ' does not exist'];
-0753                 dispEM(EM,false);
-0754                 continue;
-0755             end
-0756 
-0757             %If the multi-FASTA file is empty then save an empty aligned
-0758             %file and continue
-0759             s=dir(fullfile(dataDir,'aligned',[missingHMMs{i} '.fa']));
-0760             if s.bytes<=0
-0761                 fid=fopen(fullfile(dataDir,'hmms',[missingHMMs{i} '.hmm']),'w');
-0762                 fclose(fid);
-0763                 continue;
-0764             end
-0765             %Create a temporary file to indicate that it is working on the
-0766             %KO. This is because hmmbuild cannot overwrite existing files
-0767             fid=fopen(fullfile(dataDir,'hmms',[missingHMMs{i} '.hmw']),'w');
-0768             fclose(fid);
-0769 
-0770             %Create HMM
-0771             if ismac || isunix
-0772                 [status, output]=system(['"' fullfile(ravenPath,'software','hmmer',['hmmbuild' binEnd]) '" --cpu "' num2str(cores) '" "' fullfile(dataDir,'hmms',[missingHMMs{i} '.hmm']) '" "' fullfile(dataDir,'aligned',[missingHMMs{i} '.fa']) '"']);
-0773             else
-0774                 wslPath.hmmFile   = getWSLpath(fullfile(dataDir,'hmms',[missingHMMs{i} '.hmm']));
-0775                 wslPath.alignFile = getWSLpath(fullfile(dataDir,'aligned',[missingHMMs{i} '.fa']));
-0776                 [status, output]  = system(['wsl "' wslPath.hmmbuild '" --cpu "' num2str(cores) '" "' wslPath.hmmFile '" "' wslPath.alignFile '"']);
-0777             end
-0778             if status~=0
-0779                 EM=['Error when training HMM for ' missingHMMs{i} ':\n' output];
-0780                 dispEM(EM);
-0781             end
-0782 
-0783             %Delete the temporary file
-0784             delete(fullfile(dataDir,'hmms',[missingHMMs{i} '.hmw']));
-0785 
-0786             %Print the progress every 25 files
-0787             if rem(i-1,25) == 0
-0788                 progress=num2str(floor(100*numel(listFiles(fullfile(dataDir,'hmms','*.hmm')))/numel(KOModel.rxns)));
-0789                 progress=pad(progress,3,'left');
-0790                 fprintf('\b\b\b\b\b\b\b\b\b\b\b\b\b%s%% complete',progress);
-0791             end
-0792         end
-0793     end
-0794     fprintf('\b\b\b\b\b\b\b\b\b\b\b\b\bCOMPLETE\n');
-0795 else
-0796     fprintf('Training the KEGG Orthology specific HMMs... COMPLETE\n');
-0797 end
-0798 
-0799 %Check which new .out files that should be generated. Check if training of
-0800 %Hidden Markov models should be performed
-0801 missingOUT=setdiff(KOModel.rxns,outFiles);
-0802 if ~isempty(missingOUT)
-0803     fprintf('Querying the user-specified FASTA file against the KEGG Orthology specific HMMs...   0%% complete');
-0804     missingOUT=missingOUT(randperm(RandStream.create('mrg32k3a','Seed',cputime()),numel(missingOUT)));
-0805     for i=1:numel(missingOUT)
-0806         %This is checked here because it could be that it is created by a
-0807         %parallel process
-0808         if ~isfile(fullfile(outDir,[missingOUT{i} '.out']))
-0809             %Check that the HMM file exists. It should do so since %we are
-0810             %saving empty files as well. Print a warning and continue if
-0811             %not
-0812             if ~isfile(fullfile(dataDir,'hmms',[missingOUT{i} '.hmm']))
-0813                 EM=['The HMM file for ' missingOUT{i} ' does not exist'];
-0814                 dispEM(EM,false);
-0815                 continue;
-0816             end
-0817 
-0818             %Save an empty file to prevent several threads working on the
-0819             %same file
-0820             fid=fopen(fullfile(outDir,[missingOUT{i} '.out']),'w');
-0821             fclose(fid);
-0822 
-0823             %If the HMM file is empty then save an out file and continue
-0824             s=dir(fullfile(dataDir,'hmms',[missingOUT{i} '.hmm']));
-0825             if s.bytes<=0
-0826                 continue;
-0827             end
-0828 
-0829             %Check each gene in the input file against this model
-0830             if ismac || isunix
-0831                 [status, output]=system(['"' fullfile(ravenPath,'software','hmmer',['hmmsearch' binEnd]) '" --cpu "' num2str(cores) '" "' fullfile(dataDir,'hmms',[missingOUT{i} '.hmm']) '" "' fastaFile '"']);
-0832             else
-0833                 wslPath.hmmFile   = getWSLpath(fullfile(dataDir,'hmms',[missingOUT{i} '.hmm']));
-0834                 wslPath.fastaFile = getWSLpath(fastaFile);
-0835                 [status, output]=system(['wsl "' wslPath.hmmsearch '" --cpu "' num2str(cores) '" "' wslPath.hmmFile '" "' wslPath.fastaFile '"']);
-0836             end
-0837             if status~=0
-0838                 EM=['Error when querying HMM for ' missingOUT{i} ':\n' output];
-0839                 dispEM(EM);
-0840             end
-0841 
-0842             %Save the output to a file
-0843             fid=fopen(fullfile(outDir,[missingOUT{i} '.out']),'w');
-0844             fwrite(fid,output);
-0845             fclose(fid);
-0846 
-0847             %Print the progress every 25 files
-0848             if rem(i-1,25) == 0
-0849                 progress=num2str(floor(100*numel(listFiles(fullfile(outDir,'*.out')))/numel(KOModel.rxns)));
-0850                 progress=pad(progress,3,'left');
-0851                 fprintf('\b\b\b\b\b\b\b\b\b\b\b\b\b%s%% complete',progress);
-0852             end
-0853         end
-0854     end
-0855     fprintf('\b\b\b\b\b\b\b\b\b\b\b\b\bCOMPLETE\n');
-0856 else
-0857     fprintf('Querying the user-specified FASTA file against the KEGG Orthology specific HMMs... COMPLETE\n');
-0858 end
-0859 
-0860 
-0861 %***Begin retrieving the output and putting together the resulting model
-0862 
-0863 fprintf('Parsing the HMM search results... ');
-0864 %Retrieve matched genes from the HMMs
-0865 koGeneMat=zeros(numel(KOModel.rxns),3000); %Make room for 3000 genes
-0866 genes=cell(3000,1);
-0867 %Store the best score for a gene in a hash list (since it will be searching
-0868 %many times)
-0869 hTable = java.util.Hashtable;
-0870 
-0871 geneCounter=0;
-0872 for i=1:numel(KOModel.rxns)
-0873     if exist(fullfile(outDir,[KOModel.rxns{i} '.out']), 'file')
-0874         fid=fopen(fullfile(outDir,[KOModel.rxns{i} '.out']),'r');
-0875         beginMatches=false;
-0876         while 1
-0877             %Get the next line
-0878             tline = fgetl(fid);
-0879 
-0880             %Abort at end of file
-0881             if ~ischar(tline)
-0882                 break;
-0883             end
-0884 
-0885             if and(beginMatches,strcmp(tline,'  ------ inclusion threshold ------'))
-0886                 break;
-0887             end
-0888 
-0889             if beginMatches==false
-0890                 %This is how the listing of matches begins
-0891                 if any(strfind(tline,'E-value '))
-0892                     %Read one more line that is only padding
-0893                     tline = fgetl(fid);
-0894                     beginMatches=true;
-0895                 end
-0896             else
-0897                 %If matches should be read
-0898                 if ~strcmp(tline,'   [No hits detected that satisfy reporting thresholds]') && ~isempty(tline)
-0899                     elements=regexp(tline,' ','split');
-0900                     elements=elements(cellfun(@any,elements));
-0901 
-0902                     %Check if the match is below the treshhold
-0903                     score=str2double(elements{1});
-0904                     gene=elements{9};
-0905                     if score<=cutOff
-0906                         %If the score is exactly 0, change it to a very
-0907                         %small value to avoid NaN
-0908                         if score==0
-0909                             score=10^-250;
-0910                         end
-0911                         %Check if the gene is added already and, is so, get
-0912                         %the best score for it
-0913                         I=hTable.get(gene);
-0914                         if any(I)
-0915                             koGeneMat(i,I)=score;
-0916                         else
-0917                             geneCounter=geneCounter+1;
-0918                             %The gene was not present yet so add it
-0919                             hTable.put(gene,geneCounter);
-0920                             genes{geneCounter}=gene;
-0921                             koGeneMat(i,geneCounter)=score;
-0922                         end
-0923                     end
-0924                 else
-0925                     break;
-0926                 end
-0927             end
-0928         end
-0929         fclose(fid);
-0930     end
-0931 end
-0932 fprintf('COMPLETE\n');
-0933 
-0934 fprintf('Removing gene, KEGG Orthology associations below minScoreRatioKO, minScoreRatioG... ');
-0935 koGeneMat=koGeneMat(:,1:geneCounter);
-0936 
-0937 %Remove the genes for each KO that are below minScoreRatioKO.
-0938 for i=1:size(koGeneMat,1)
-0939     J=find(koGeneMat(i,:));
-0940     if any(J)
-0941         koGeneMat(i,J(log(koGeneMat(i,J))/log(min(koGeneMat(i,J)))<minScoreRatioKO))=0;
-0942     end
-0943 end
-0944 
-0945 %Remove the KOs for each gene that are below minScoreRatioG
-0946 for i=1:size(koGeneMat,2)
-0947     J=find(koGeneMat(:,i));
-0948     if any(J)
-0949         koGeneMat(J(log(koGeneMat(J,i))/log(min(koGeneMat(J,i)))<minScoreRatioG),i)=0;
-0950     end
-0951 end
-0952 fprintf('COMPLETE\n');
-0953 
-0954 fprintf('Adding gene annotations to the model... ');
-0955 %Create the new model
-0956 model.genes=genes(1:geneCounter);
-0957 model.grRules=cell(numel(model.rxns),1);
-0958 model.grRules(:)={''};
-0959 model.rxnGeneMat=sparse(numel(model.rxns),numel(model.genes));
-0960 
-0961 %Loop through the reactions and add the corresponding genes
-0962 for i=1:numel(model.rxns)
-0963     if isstruct(model.rxnMiriams{i})
-0964         %Get all KOs
-0965         I=find(strcmpi(model.rxnMiriams{i}.name,'kegg.orthology'));
-0966         KOs=model.rxnMiriams{i}.value(I);
-0967         %Find the KOs and the corresponding genes
-0968         J=ismember(KOModel.rxns,KOs);
-0969         [~, K]=find(koGeneMat(J,:));
-0970 
-0971         if any(K)
-0972             model.rxnGeneMat(i,K)=1;
-0973             %Also delete KOs for which no genes were found. If no genes at
-0974             %all were matched to the reaction it will be deleted later
-0975             L=sum(koGeneMat(J,:),2)==0;
-0976             model.rxnMiriams{i}.value(I(L))=[];
-0977             model.rxnMiriams{i}.name(I(L))=[];
-0978         end
-0979     end
-0980 end
-0981 fprintf('COMPLETE\n');
-0982 
-0983 %Find and delete all reactions without genes. This also removes genes that
-0984 %are not used (which could happen because minScoreRatioG and
-0985 %minScoreRatioKO). If keepSpontaneous==true, the spontaneous reactions
-0986 %without genes are kept in the model. Spontaneous reactions with original
-0987 %gene associations are treated in the same way, like the rest of the
-0988 %reactions - if gene associations were removed during HMM search, such
-0989 %reactions are deleted from the model
-0990 if keepSpontaneous==true
-0991     %Not the most comprise way to delete reactions without genes, but this
-0992     %makes the code easier to understand. Firstly the non-spontaneous
-0993     %reactions without genes are removed. After that, the second deletion
-0994     %step removes spontaneous reactions, which had gene associations before
-0995     %HMM search, but no longer have after it
-0996     fprintf('Removing non-spontaneous reactions which after HMM search no longer have GPR rules... ');
-0997     I=~any(model.rxnGeneMat,2)&~ismember(model.rxns,isSpontaneous);
-0998     model=removeReactions(model,I,true,true);
-0999     I=~any(model.rxnGeneMat,2)&ismember(model.rxns,spontRxnsWithGenes);
-1000     model=removeReactions(model,I,true,true);
-1001 else
-1002     %Just simply check for any new reactions without genes and remove
-1003     %it
-1004     fprintf('Removing reactions which after HMM search no longer have GPR rules... ');
-1005     I=~any(model.rxnGeneMat,2);
-1006     model=removeReactions(model,I,true,true);
-1007 end
-1008 fprintf('COMPLETE\n');
-1009 
-1010 fprintf('Constructing GPR rules and finalizing the model... ');
-1011 %Add the gene associations as 'or'
-1012 for i=1:numel(model.rxns)
-1013     %Find the involved genes
-1014     I=find(model.rxnGeneMat(i,:));
-1015     if any(I)
-1016         model.grRules{i}=['(' model.genes{I(1)}];
-1017         for j=2:numel(I)
-1018             model.grRules{i}=[model.grRules{i} ' or ' model.genes{I(j)}];
-1019         end
-1020         model.grRules{i}=[model.grRules{i} ')'];
-1021     end
-1022 end
-1023 
-1024 %Fix grRules and reconstruct rxnGeneMat
-1025 [grRules,rxnGeneMat] = standardizeGrRules(model,false); %Give detailed output
-1026 model.grRules = grRules;
-1027 model.rxnGeneMat = rxnGeneMat;
-1028 
-1029 %Add the description to the reactions
-1030 for i=1:numel(model.rxns)
-1031     if ~isempty(model.rxnNotes{i})
-1032         model.rxnNotes(i)=strcat('Included by getKEGGModelForOrganism (using HMMs).',model.rxnNotes(i));
-1033         model.rxnNotes(i)=strrep(model.rxnNotes(i),'.','. ');
-1034     else
-1035         model.rxnNotes(i)={'Included by getKEGGModelForOrganism (using HMMs)'};
-1036     end
-1037 end
-1038 %Remove the temp fasta file
-1039 delete(fastaFile)
-1040 fprintf('COMPLETE\n\n*** Model reconstruction complete ***\n');
-1041 end
-1042 
-1043 function files=listFiles(directory)
-1044 %Supporter function to list the files in a directory and return them as a
-1045 %cell array
-1046 temp=dir(directory);
-1047 files=cell(numel(temp),1);
-1048 for i=1:numel(temp)
-1049     files{i}=temp(i,1).name;
-1050 end
-1051 files=strrep(files,'.fa','');
-1052 files=strrep(files,'.hmm','');
-1053 files=strrep(files,'.out','');
-1054 files=strrep(files,'.faw','');
-1055 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/external/kegg/getMetsFromKEGG.html b/doc/external/kegg/getMetsFromKEGG.html deleted file mode 100644 index 9299cd96b..000000000 --- a/doc/external/kegg/getMetsFromKEGG.html +++ /dev/null @@ -1,391 +0,0 @@ - - - - Description of getMetsFromKEGG - - - - - - - - - -
Home > external > kegg > getMetsFromKEGG.m
- - - -

getMetsFromKEGG -

- -

PURPOSE ^

-
getMetsFromKEGG
- -

SYNOPSIS ^

-
function model=getMetsFromKEGG(keggPath)
- -

DESCRIPTION ^

-
 getMetsFromKEGG
-   Retrieves information on all metabolites stored in KEGG database
-
-   Input:
-   keggPath    if keggMets.mat is not in the RAVEN\external\kegg
-               directory, this function will attempt to read data from a
-               local FTP dump of the KEGG database. keggPath is the path
-               to the root of this database
-
-   Output:
-   model       a model structure generated from the database. The
-               following fields are filled
-       id              'KEGG'
-       name     'Automatically generated from KEGG database'
-       mets            KEGG compound ids
-       metNames        Compound name. Only the first name will be saved if
-                       there are several synonyms
-       metMiriams      If there is a CHEBI id available, then that will be
-                       saved here
-       inchis          InChI string for the metabolite
-       metFormulas     The chemical composition of the metabolite. This
-                       will only be loaded if there is no InChI string
-
-   NOTE: If the file keggMets.mat is in the RAVEN\external\kegg directory
-   it will be loaded instead of parsing of the KEGG files. If it does not
-   exist it will be saved after parsing of the KEGG files. In general, you
-   should remove the keggMets.mat file if you want to rebuild the model
-   structure from a newer version of KEGG.
-               
- Usage: model=getMetsFromKEGG(keggPath)
-
- NOTE: This is how one entry looks in the file
-
- ENTRY       C00001                      Compound
- NAME        H2O;
-             Water
- FORMULA     H2O
- EXACT_MASS  18.0106
- MOL_WEIGHT  18.0153
- REMARK      Same as: D00001
- REACTION    R00001 R00002 R00004 R00005 R00009 R00010 R00011 R00017
-             R00022 R00024 R00025 R00026 R00028 R00036 R00041 R00044
-             (list truncated)
- ENZYME      1.1.1.1         1.1.1.22        1.1.1.23        1.1.1.115
-             1.1.1.132       1.1.1.136       1.1.1.170       1.1.1.186
-             (list truncated)
- BRITE       Therapeutic category of drugs in Japan [BR:br08301]
-             (list truncated)
- DBLINKS     CAS: 7732-18-5
-             PubChem: 3303
-             ChEBI: 15377
-             (list truncated)
-
- Then a lot of info about the positions of the atoms and so on. It is not
- certain that each metabolite follows this structure exactly.
-
- The file is not tab-delimited. Instead each label is 12 characters
- (except for '///').
-
- Check if the reactions have been parsed before and saved. If so, load the
- model.
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function model=getMetsFromKEGG(keggPath)
-0002 % getMetsFromKEGG
-0003 %   Retrieves information on all metabolites stored in KEGG database
-0004 %
-0005 %   Input:
-0006 %   keggPath    if keggMets.mat is not in the RAVEN\external\kegg
-0007 %               directory, this function will attempt to read data from a
-0008 %               local FTP dump of the KEGG database. keggPath is the path
-0009 %               to the root of this database
-0010 %
-0011 %   Output:
-0012 %   model       a model structure generated from the database. The
-0013 %               following fields are filled
-0014 %       id              'KEGG'
-0015 %       name     'Automatically generated from KEGG database'
-0016 %       mets            KEGG compound ids
-0017 %       metNames        Compound name. Only the first name will be saved if
-0018 %                       there are several synonyms
-0019 %       metMiriams      If there is a CHEBI id available, then that will be
-0020 %                       saved here
-0021 %       inchis          InChI string for the metabolite
-0022 %       metFormulas     The chemical composition of the metabolite. This
-0023 %                       will only be loaded if there is no InChI string
-0024 %
-0025 %   NOTE: If the file keggMets.mat is in the RAVEN\external\kegg directory
-0026 %   it will be loaded instead of parsing of the KEGG files. If it does not
-0027 %   exist it will be saved after parsing of the KEGG files. In general, you
-0028 %   should remove the keggMets.mat file if you want to rebuild the model
-0029 %   structure from a newer version of KEGG.
-0030 %
-0031 % Usage: model=getMetsFromKEGG(keggPath)
-0032 %
-0033 % NOTE: This is how one entry looks in the file
-0034 %
-0035 % ENTRY       C00001                      Compound
-0036 % NAME        H2O;
-0037 %             Water
-0038 % FORMULA     H2O
-0039 % EXACT_MASS  18.0106
-0040 % MOL_WEIGHT  18.0153
-0041 % REMARK      Same as: D00001
-0042 % REACTION    R00001 R00002 R00004 R00005 R00009 R00010 R00011 R00017
-0043 %             R00022 R00024 R00025 R00026 R00028 R00036 R00041 R00044
-0044 %             (list truncated)
-0045 % ENZYME      1.1.1.1         1.1.1.22        1.1.1.23        1.1.1.115
-0046 %             1.1.1.132       1.1.1.136       1.1.1.170       1.1.1.186
-0047 %             (list truncated)
-0048 % BRITE       Therapeutic category of drugs in Japan [BR:br08301]
-0049 %             (list truncated)
-0050 % DBLINKS     CAS: 7732-18-5
-0051 %             PubChem: 3303
-0052 %             ChEBI: 15377
-0053 %             (list truncated)
-0054 %
-0055 % Then a lot of info about the positions of the atoms and so on. It is not
-0056 % certain that each metabolite follows this structure exactly.
-0057 %
-0058 % The file is not tab-delimited. Instead each label is 12 characters
-0059 % (except for '///').
-0060 %
-0061 % Check if the reactions have been parsed before and saved. If so, load the
-0062 % model.
-0063 %
-0064 
-0065 if nargin<1
-0066     keggPath='RAVEN/external/kegg';
-0067 else
-0068     keggPath=char(keggPath);
-0069 end
-0070 
-0071 ravenPath=findRAVENroot();
-0072 metsFile=fullfile(ravenPath,'external','kegg','keggMets.mat');
-0073 if exist(metsFile, 'file')
-0074     fprintf(['Importing KEGG metabolites from ' strrep(metsFile,'\','/') '... ']);
-0075     load(metsFile);
-0076 else
-0077     fprintf(['NOTE: Cannot locate ' strrep(metsFile,'\','/') ', it will therefore be generated from the local KEGG database\n']);
-0078     if ~isfile(fullfile(keggPath,'compound')) || ~isfile(fullfile(keggPath,'compound.inchi'))
-0079         EM=fprintf(['The files ''compound'' and ''compound.inchi'' cannot be located at ' strrep(keggPath,'\','/') '/ and should be downloaded from the KEGG FTP.\n']);
-0080         dispEM(EM);
-0081     else
-0082         fprintf('Generating keggMets.mat file... ');
-0083         %Add new functionality in the order specified in models
-0084         model.id='KEGG';
-0085         model.name='Automatically generated from KEGG database';
-0086         
-0087         %Preallocate memory for 50000 metabolites
-0088         model.mets=cell(50000,1);
-0089         model.metNames=cell(50000,1);
-0090         model.metFormulas=cell(50000,1);
-0091         model.metMiriams=cell(50000,1);
-0092         
-0093         %First load information on metabolite ID, metabolite name,
-0094         %composition, and ChEBI
-0095         
-0096         fid = fopen(fullfile(keggPath,'compound'), 'r');
-0097         
-0098         %Keeps track of how many metabolites that have been added
-0099         metCounter=0;
-0100         
-0101         %Loop through the file
-0102         while 1
-0103             %Get the next line
-0104             tline = fgetl(fid);
-0105             
-0106             %Abort at end of file
-0107             if ~ischar(tline)
-0108                 break;
-0109             end
-0110             
-0111             %Skip '///'
-0112             if numel(tline)<12
-0113                 continue;
-0114             end
-0115             
-0116             %Check if it's a new reaction
-0117             if strcmp(tline(1:12),'ENTRY       ')
-0118                 metCounter=metCounter+1;
-0119                 
-0120                 %Add empty strings where there should be such
-0121                 model.metNames{metCounter}='';
-0122                 model.metFormulas{metCounter}='';
-0123                 
-0124                 %Add compound ID (always 6 characters)
-0125                 model.mets{metCounter}=tline(13:18);
-0126                 
-0127                 %Add the KEGG id as metMiriams
-0128                 if length(model.mets{metCounter})==6
-0129                     miriamStruct=model.metMiriams{metCounter};
-0130                     if strcmp('G',model.mets{metCounter}(1))
-0131                         miriamStruct.name{1,1}='kegg.glycan';
-0132                     else
-0133                         miriamStruct.name{1,1}='kegg.compound';
-0134                     end
-0135                     miriamStruct.value{1,1}=tline(13:18);
-0136                     model.metMiriams{metCounter}=miriamStruct;
-0137                 end
-0138             end
-0139             
-0140             %Add name
-0141             if strcmp(tline(1:12),'NAME        ')
-0142                 %If there are synonyms, then the last character is ';'
-0143                 if strcmp(tline(end),';')
-0144                     model.metNames{metCounter}=tline(13:end-1);
-0145                     %Semicolon can also occur in the middle, separating
-0146                     %several synonims in the same line
-0147                     model.metNames{metCounter} = regexprep(model.metNames{metCounter},';.+','');
-0148                 elseif regexp(tline,';')
-0149                     model.metNames{metCounter}=tline(13:end);
-0150                     model.metNames{metCounter} = regexprep(model.metNames{metCounter},';.+','');
-0151                 else
-0152                     model.metNames{metCounter}=tline(13:end);
-0153                 end
-0154             end
-0155             
-0156             %Add composition
-0157             if strcmp(tline(1:12),'FORMULA     ')
-0158                 model.metFormulas{metCounter}=tline(13:end);
-0159             end
-0160             
-0161             %Add PubChem id
-0162             if numel(tline)>21
-0163                 if strcmp(tline(13:21),'PubChem: ')
-0164                     if isstruct(model.metMiriams{metCounter})
-0165                         addToIndex=numel(model.metMiriams{metCounter}.name)+1;
-0166                     else
-0167                         addToIndex=1;
-0168                     end
-0169                     miriamStruct=model.metMiriams{metCounter};
-0170                     miriamStruct.name{addToIndex,1}='pubchem.substance';
-0171                     miriamStruct.value{addToIndex,1}=tline(22:end);
-0172                     model.metMiriams{metCounter}=miriamStruct;
-0173                 end
-0174             end
-0175             
-0176             %Add CHEBI id
-0177             if numel(tline)>19
-0178                 if strcmp(tline(13:19),'ChEBI: ')
-0179                     if isstruct(model.metMiriams{metCounter})
-0180                         addToIndex=numel(model.metMiriams{metCounter}.name)+1;
-0181                     else
-0182                         addToIndex=1;
-0183                     end
-0184                     chebiIDs=strsplit(tline(20:end),' ');
-0185                     miriamStruct=model.metMiriams{metCounter};
-0186                     for i=1:numel(chebiIDs)
-0187                         miriamStruct.name{addToIndex,1}='chebi';
-0188                         miriamStruct.value{addToIndex,1}=strcat('CHEBI:',chebiIDs{i});
-0189                         addToIndex=addToIndex+1;
-0190                     end
-0191                     model.metMiriams{metCounter}=miriamStruct;
-0192                 end
-0193             end
-0194         end
-0195         
-0196         %Close the file
-0197         fclose(fid);
-0198         
-0199         %If too much space was allocated, shrink the model
-0200         model.mets=model.mets(1:metCounter);
-0201         model.metNames=model.metNames(1:metCounter);
-0202         model.metFormulas=model.metFormulas(1:metCounter);
-0203         model.metMiriams=model.metMiriams(1:metCounter);
-0204         
-0205         %Then load the InChI strings from another file. Not all metabolites
-0206         %will be present in the list
-0207         
-0208         inchIDs=cell(numel(model.mets),1);
-0209         inchis=cell(numel(model.mets),1);
-0210         
-0211         %The format is metID*tab*string
-0212         
-0213         fid = fopen(fullfile(keggPath,'compound.inchi'), 'r');
-0214         
-0215         %Loop through the file
-0216         counter=1;
-0217         while 1
-0218             %Get the next line
-0219             tline = fgetl(fid);
-0220             
-0221             %Abort at end of file
-0222             if ~ischar(tline)
-0223                 break;
-0224             end
-0225             
-0226             %Get the ID and the InChI
-0227             inchIDs{counter}=tline(1:6);
-0228             inchis{counter}=tline(14:end);
-0229             counter=counter+1;
-0230         end
-0231         
-0232         %Close the file
-0233         fclose(fid);
-0234         
-0235         inchIDs=inchIDs(1:counter-1);
-0236         inchis=inchis(1:counter-1);
-0237         
-0238         %Find the metabolites that had InChI strings and add them to the
-0239         %model
-0240         [a, b]=ismember(inchIDs,model.mets);
-0241         
-0242         %If there were mets with InChIs but that were not in the list
-0243         if ~all(a)
-0244             EM='Not all metabolites with InChI strings were found in the original list';
-0245             disp(EM);
-0246         end
-0247         
-0248         model.inchis=cell(numel(model.mets),1);
-0249         model.inchis(:)={''};
-0250         model.inchis(b)=inchis;
-0251         
-0252         %Remove composition if InChI was found
-0253         model.metFormulas(b)={''};
-0254         
-0255         %Ensuring that all model.metMiriams.value consist only of strings,
-0256         %no double
-0257         for i=1:(numel(model.mets))
-0258             for j=1:(numel(model.metMiriams{i}))
-0259                 if isa(model.metMiriams{i}.value{j},'double')
-0260                     model.metMiriams{i}.value{j}=num2str(model.metMiriams{i}.value{j});
-0261                 end
-0262             end
-0263         end
-0264         
-0265         %Removing fronting and trailing whitespace from metNames
-0266         model.metNames = deblank(model.metNames);
-0267         
-0268         %Fixing redundant metNames. The first occurence of particular
-0269         %metabolite name is not changed, but starting from the second
-0270         %occurence, original metabolite name is concatenated with KEGG
-0271         %COMPOUND id between the brackets
-0272         for i=1:(numel(model.metNames))
-0273             if ~isempty(model.metNames{i})
-0274                 if sum(ismember(model.metNames(1:i-1),model.metNames(i)))>=1
-0275                     model.metNames(i) = strcat(model.metNames(i), ' (', model.mets(i),')');
-0276                 end
-0277             end
-0278         end
-0279         %Saves the model
-0280         save(metsFile,'model');
-0281     end
-0282 end
-0283 fprintf('COMPLETE\n');
-0284 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/external/kegg/getModelFromKEGG.html b/doc/external/kegg/getModelFromKEGG.html deleted file mode 100644 index ae4dd1a35..000000000 --- a/doc/external/kegg/getModelFromKEGG.html +++ /dev/null @@ -1,381 +0,0 @@ - - - - Description of getModelFromKEGG - - - - - - - - - -
Home > external > kegg > getModelFromKEGG.m
- - - -

getModelFromKEGG -

- -

PURPOSE ^

-
getModelFromKEGG
- -

SYNOPSIS ^

-
function [model,KOModel]=getModelFromKEGG(keggPath,keepSpontaneous,keepUndefinedStoich,keepIncomplete,keepGeneral)
- -

DESCRIPTION ^

-
 getModelFromKEGG
-   Retrieves information stored in KEGG database and generates a model
-
-   Input:
-   keggPath            if keggGenes.mat, keggMets.mat, keggPhylDist.mat or
-                       keggRxns.mat are not in the RAVEN/external/kegg
-                       directory, this function will attempt to read data
-                       from a local FTP dump of the KEGG database.
-                       keggPath is the path to the root of this database
-                       (optional, default 'RAVEN/external/kegg'). If
-                       keggModel.mat is present in the same directory, the
-                       function reads the data from this file and ignores
-                       keggGenes.mat, keggMets.mat and keggRxns.mat
-   keepSpontaneous     include reactions labeled as "spontaneous" (optional,
-                       default true)
-   keepUndefinedStoich include reactions in the form n A <=> n+1 A. These
-                       will be dealt with as two separate metabolites
-                       (optional, default true)
-   keepIncomplete      include reactions which have been labelled as
-                       "incomplete", "erroneous" or "unclear" (optional,
-                       default true)
-   keepGeneral         include reactions which have been labelled as
-                       "general reaction". These are reactions on the form
-                       "an aldehyde <=> an alcohol", and are therefore
-                       unsuited for modelling purposes. Note that not all
-                       reactions have this type of annotation, and the
-                       script will therefore not be able to remove all
-                       such reactions (optional, default false)
-
-   Output:
-   model               a model structure generated from the database. All
-                       reactions and the metabolites used in them will be
-                       added
-   KOModel             a model structure representing the KEGG Orthology
-                       ids and their associated genes. The KO ids are
-                       saved as reactions
-
-   NOTE: The model output from getModelFromKEGG can be used as template
-   for fillGaps. In that case, ensure that the genes and rxnGeneMat fields
-   are removed before parsing: model=rmfield(model,'genes'), etc.
-
- Usage: [model,KOModel]=getModelFromKEGG(keggPath,keepSpontaneous,...
-    keepUndefinedStoich,keepIncomplete,keepGeneral)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 function [model,KOModel]=getModelFromKEGG(keggPath,keepSpontaneous,...
-0002     keepUndefinedStoich,keepIncomplete,keepGeneral)
-0003 % getModelFromKEGG
-0004 %   Retrieves information stored in KEGG database and generates a model
-0005 %
-0006 %   Input:
-0007 %   keggPath            if keggGenes.mat, keggMets.mat, keggPhylDist.mat or
-0008 %                       keggRxns.mat are not in the RAVEN/external/kegg
-0009 %                       directory, this function will attempt to read data
-0010 %                       from a local FTP dump of the KEGG database.
-0011 %                       keggPath is the path to the root of this database
-0012 %                       (optional, default 'RAVEN/external/kegg'). If
-0013 %                       keggModel.mat is present in the same directory, the
-0014 %                       function reads the data from this file and ignores
-0015 %                       keggGenes.mat, keggMets.mat and keggRxns.mat
-0016 %   keepSpontaneous     include reactions labeled as "spontaneous" (optional,
-0017 %                       default true)
-0018 %   keepUndefinedStoich include reactions in the form n A <=> n+1 A. These
-0019 %                       will be dealt with as two separate metabolites
-0020 %                       (optional, default true)
-0021 %   keepIncomplete      include reactions which have been labelled as
-0022 %                       "incomplete", "erroneous" or "unclear" (optional,
-0023 %                       default true)
-0024 %   keepGeneral         include reactions which have been labelled as
-0025 %                       "general reaction". These are reactions on the form
-0026 %                       "an aldehyde <=> an alcohol", and are therefore
-0027 %                       unsuited for modelling purposes. Note that not all
-0028 %                       reactions have this type of annotation, and the
-0029 %                       script will therefore not be able to remove all
-0030 %                       such reactions (optional, default false)
-0031 %
-0032 %   Output:
-0033 %   model               a model structure generated from the database. All
-0034 %                       reactions and the metabolites used in them will be
-0035 %                       added
-0036 %   KOModel             a model structure representing the KEGG Orthology
-0037 %                       ids and their associated genes. The KO ids are
-0038 %                       saved as reactions
-0039 %
-0040 %   NOTE: The model output from getModelFromKEGG can be used as template
-0041 %   for fillGaps. In that case, ensure that the genes and rxnGeneMat fields
-0042 %   are removed before parsing: model=rmfield(model,'genes'), etc.
-0043 %
-0044 % Usage: [model,KOModel]=getModelFromKEGG(keggPath,keepSpontaneous,...
-0045 %    keepUndefinedStoich,keepIncomplete,keepGeneral)
-0046 
-0047 ravenPath=findRAVENroot();
-0048 
-0049 if nargin<1
-0050     keggPath=fullfile(ravenPath,'external','kegg');
-0051 else
-0052     keggPath=char(keggPath);
-0053 end
-0054 if nargin<2
-0055     keepSpontaneous=true;
-0056 end
-0057 if nargin<3
-0058     keepUndefinedStoich=true;
-0059 end
-0060 if nargin<4
-0061     keepIncomplete=true;
-0062 end
-0063 if nargin<5
-0064     keepGeneral=false;
-0065 end
-0066 
-0067 modelFile=fullfile(ravenPath,'external','kegg','keggModel.mat');
-0068 if exist(modelFile, 'file') && isNewestFile(ravenPath)
-0069     fprintf(['Importing the global KEGG model from ' strrep(modelFile,'\','/') '... ']);
-0070     load(modelFile);
-0071     fprintf('COMPLETE\n');
-0072 else
-0073     fprintf(['NOTE: The file ' strrep(modelFile,'\','/') ' does not exist or is out-of-date and therefore will be (re)generated\n']);
-0074     %First get all reactions
-0075     [model,isSpontaneous,isUndefinedStoich,isIncomplete,isGeneral]=getRxnsFromKEGG(keggPath);
-0076     
-0077     %Get the KO ids that are associated with any of the reactions. They
-0078     %will be used later on to create a rxn-gene matrix
-0079     KOs=cell(numel(model.rxns)*2,1);
-0080     %Make room for two KO ids per reaction
-0081     
-0082     addToIndex=1;
-0083     %Add all KO ids that are used
-0084     for i=1:numel(model.rxns)
-0085         if isstruct(model.rxnMiriams{i})
-0086             for j=1:numel(model.rxnMiriams{i}.name)
-0087                 if strcmpi('kegg.orthology',model.rxnMiriams{i}.name{j})
-0088                     %Add the KO id
-0089                     KOs(addToIndex)=model.rxnMiriams{i}.value(j);
-0090                     addToIndex=addToIndex+1;
-0091                 end
-0092             end
-0093         end
-0094     end
-0095     
-0096     KOs=KOs(1:addToIndex-1);
-0097     KOs=unique(KOs);
-0098     
-0099     %Get all genes from any organism in KEGG that is associated with any of
-0100     %the KOs
-0101     KOModel=getGenesFromKEGG(keggPath,KOs);
-0102     
-0103     fprintf('Pruning the global KEGG model from the partially annotated, lumped KEGG Orthology entries... ')
-0104     model.genes=KOModel.genes;
-0105     
-0106     %It can be that there are KOs from the reactions that have no database
-0107     %entry. These are (as far as I have seen) lumped versions of other KOs
-0108     %and should be removed
-0109     KOsToRemove=setdiff(KOs, KOModel.rxns);
-0110     
-0111     %Loop through all reactions and delete the KOs that were not found
-0112     for i=1:numel(model.rxns)
-0113         if isstruct(model.rxnMiriams{i})
-0114             for j=1:numel(model.rxnMiriams{i}.name)
-0115                 toDel=[];
-0116                 if strcmp(model.rxnMiriams{i}.name{j},'kegg.orthology')
-0117                     if ismember(model.rxnMiriams{i}.value{j},KOsToRemove)
-0118                         toDel=[toDel;j];
-0119                     end
-0120                 end
-0121             end
-0122             %Delete the KOs
-0123             if any(toDel)
-0124                 %If all posts are deleted, then delete the whole structure
-0125                 if numel(toDel)==j
-0126                     model.rxnMiriams{i}=[];
-0127                 else
-0128                     model.rxnMiriams{i}.name(toDel)=[];
-0129                     model.rxnMiriams{i}.value(toDel)=[];
-0130                 end
-0131             end
-0132         end
-0133     end
-0134     fprintf('COMPLETE\n');
-0135     
-0136     fprintf('Constructing the rxnGeneMat for the global KEGG model...   0%% complete');
-0137     %Create the rxnGeneMat for the reactions. This is simply done by
-0138     %merging the gene associations for all the involved KOs
-0139     r=zeros(10000000,1);
-0140     %Store the positions since it's slow to write to a sparse array in a
-0141     %loop
-0142     c=zeros(10000000,1);
-0143     counter=1;
-0144     for i=1:numel(model.rxns)
-0145         if isstruct(model.rxnMiriams{i})
-0146             I=strncmp('kegg.orthology',model.rxnMiriams{i}.name,18);
-0147             if any(I)
-0148                 [J, K]=ismember(model.rxnMiriams{i}.value(I),KOModel.rxns);
-0149                 %Find all gene indexes that correspond to any of these KOs
-0150                 [~, L]=find(KOModel.rxnGeneMat(K(J),:));
-0151                 if any(L)
-0152                     %Allocate room for more elements if needed
-0153                     if counter+numel(L)-1>=numel(r)
-0154                         r=[r;zeros(numel(r),1)];
-0155                         c=[c;zeros(numel(c),1)];
-0156                     end
-0157                     r(counter:counter+numel(L)-1)=ones(numel(L),1)*i;
-0158                     c(counter:counter+numel(L)-1)=L(:);
-0159                     counter=counter+numel(L);
-0160                 end
-0161             end
-0162         end
-0163         if rem(i-1,100) == 0
-0164             progress=pad(num2str(floor(i/numel(model.rxns)*100)),3,'left');
-0165             fprintf('\b\b\b\b\b\b\b\b\b\b\b\b\b%s%% complete',progress);
-0166         end
-0167     end
-0168     
-0169     model.rxnGeneMat=sparse(r(1:counter-1),c(1:counter-1),ones(counter-1,1));
-0170     if size(model.rxnGeneMat,1)~=numel(model.rxns) || size(model.rxnGeneMat,2)~=numel(KOModel.genes)
-0171         model.rxnGeneMat(numel(model.rxns),numel(KOModel.genes))=0;
-0172     end
-0173     fprintf('\b\b\b\b\b\b\b\b\b\b\b\b\bCOMPLETE\n');
-0174     
-0175     %Then get all metabolites
-0176     metModel=getMetsFromKEGG(keggPath);
-0177     
-0178     fprintf('Finalizing the global KEGG model... ');
-0179     %Add information about all metabolites to the model
-0180     [a, b]=ismember(model.mets,metModel.mets);
-0181     a=find(a);
-0182     b=b(a);
-0183     
-0184     if ~isfield(model,'metNames')
-0185         model.metNames=cell(numel(model.mets),1);
-0186         model.metNames(:)={''};
-0187     end
-0188     model.metNames(a)=metModel.metNames(b);
-0189     
-0190     if ~isfield(model,'metFormulas')
-0191         model.metFormulas=cell(numel(model.mets),1);
-0192         model.metFormulas(:)={''};
-0193     end
-0194     model.metFormulas(a)=metModel.metFormulas(b);
-0195     
-0196     if ~isfield(model,'inchis')
-0197         model.inchis=cell(numel(model.mets),1);
-0198         model.inchis(:)={''};
-0199     end
-0200     model.inchis(a)=metModel.inchis(b);
-0201     
-0202     if ~isfield(model,'metMiriams')
-0203         model.metMiriams=cell(numel(model.mets),1);
-0204     end
-0205     model.metMiriams(a)=metModel.metMiriams(b);
-0206     
-0207     %The composition should be loaded from InChIs when available
-0208     I=find(~cellfun(@isempty,model.inchis));
-0209     for i=1:numel(I)
-0210         S=regexp(model.inchis(I(i)),'/','split');
-0211         S=S{1};
-0212         if numel(S)>=2
-0213             %Don't copy if it doesn't look good
-0214             model.metFormulas(I(i))=S(2);
-0215         end
-0216     end
-0217     
-0218     %Put all metabolites in one compartment called 's' (for system). This
-0219     %is done just to be more compatible with the rest of the code
-0220     model.comps={'s'};
-0221     model.compNames={'System'};
-0222     model.metComps=ones(numel(model.mets),1);
-0223     
-0224     %If reactions with undefined stoichiometry are kept, then the
-0225     %corresponding metabolites will have ids such as "(n+1) C00001" and
-0226     %their names will be empty. These ids are not valid SBML identifiers
-0227     %and are therefore replaced with "undefined1, undefined2...". The
-0228     %former ids are stored as the new names
-0229     I=find(cellfun(@any,strfind(model.mets,'n')) | cellfun(@any,strfind(model.mets,'m')));
-0230     model.metNames(I)=model.mets(I);
-0231     repNums=1:numel(I);
-0232     repIDs=strcat('undefined_',cellfun(@num2str,num2cell(repNums(:)),'UniformOutput',false));
-0233     model.mets(I)=repIDs;
-0234     
-0235     %It could also be that the metabolite names are empty for some other
-0236     %reason. In that case, use the ID instead
-0237     I=cellfun(@isempty,model.metNames);
-0238     model.metNames(I)=model.mets(I);
-0239 
-0240     %Deafult LB and UB
-0241     model.annotation.defaultLB = -1000;
-0242     model.annotation.defaultUB = 1000;
-0243     
-0244     %Save the model structure
-0245     save(modelFile,'model','KOModel','isGeneral','isIncomplete','isUndefinedStoich','isSpontaneous');
-0246     fprintf('COMPLETE\n');
-0247 end
-0248 
-0249 %Delete reactions which are labeled as "incomplete", "erroneous",
-0250 %"unclear", "general reaction" or having undefined stoichiometry (depending
-0251 %on settings)
-0252 if keepSpontaneous==false
-0253     model=removeReactions(model,intersect(isSpontaneous,model.rxns),true,true);
-0254 end
-0255 if keepUndefinedStoich==false
-0256     model=removeReactions(model,intersect(isUndefinedStoich,model.rxns),true,true);
-0257 end
-0258 if keepIncomplete==false
-0259     model=removeReactions(model,intersect(isIncomplete,model.rxns),true,true);
-0260 end
-0261 if keepGeneral==false
-0262     model=removeReactions(model,intersect(isGeneral,model.rxns),true,true);
-0263 end
-0264 
-0265 end
-0266 
-0267 function output = isNewestFile(ravenPath)
-0268 %The ad hoc function, which checks whether keggModel.mat is the more
-0269 %recently modified than keggRxns.mat, keggGenes.mat and keggRxns.mat
-0270 modelFile=fullfile(ravenPath,'external','kegg','keggModel.mat');
-0271 rxnsFile=fullfile(ravenPath,'external','kegg','keggRxns.mat');
-0272 genesFile=fullfile(ravenPath,'external','kegg','keggGenes.mat');
-0273 metsFile=fullfile(ravenPath,'external','kegg','keggMets.mat');
-0274 if (getFileTime(modelFile)>getFileTime(rxnsFile))&&...
-0275         (getFileTime(modelFile)>getFileTime(genesFile))&&...
-0276         (getFileTime(modelFile)>getFileTime(metsFile))
-0277     output=1;
-0278 else
-0279     output=0;
-0280 end
-0281 end
-0282 
-0283 function modTime = getFileTime(fileName)
-0284 %Gets a last modification time for a particular file in datenum format that
-0285 %the numbers could be easily compared for different files
-0286 listing = dir(fileName);
-0287 assert(numel(listing) == 1, 'No such file: %s', fileName);
-0288 modTime = listing.datenum;
-0289 format long;
-0290 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/external/kegg/getPhylDist.html b/doc/external/kegg/getPhylDist.html deleted file mode 100644 index 226ba9b73..000000000 --- a/doc/external/kegg/getPhylDist.html +++ /dev/null @@ -1,208 +0,0 @@ - - - - Description of getPhylDist - - - - - - - - - -
Home > external > kegg > getPhylDist.m
- - - -

getPhylDist -

- -

PURPOSE ^

-
getPhylDist
- -

SYNOPSIS ^

-
function phylDistStruct=getPhylDist(keggPath,onlyInKingdom)
- -

DESCRIPTION ^

-
 getPhylDist
-   Calculates distance between species in KEGG based on systematic name
-
-   Input:
-   keggPath        if keggPhylDist.mat is not in the RAVEN\external\kegg
-                   directory, this function will attempt to read data from
-                   a local FTP dump of the KEGG database. keggPath is the
-                   path to the root of this database
-   onlyInKingdom   if true, it generates a distance matrix with distance
-                   Inf for organisms from another domains (Prokaryota,
-                   Eukaryota) (optional, default false)
-
-   Output:
-   phylDistStruct  a structure with a list of organism ids and a matrix
-                   that specifies their pairwise distances
-
-   NOTE: This simple metric is based on the number of nodes two organisms
-   are away from each other in KEGG
-
- Usage: phylDistStruct=getPhylDist(keggPath,onlyInKingdom)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function phylDistStruct=getPhylDist(keggPath,onlyInKingdom)
-0002 % getPhylDist
-0003 %   Calculates distance between species in KEGG based on systematic name
-0004 %
-0005 %   Input:
-0006 %   keggPath        if keggPhylDist.mat is not in the RAVEN\external\kegg
-0007 %                   directory, this function will attempt to read data from
-0008 %                   a local FTP dump of the KEGG database. keggPath is the
-0009 %                   path to the root of this database
-0010 %   onlyInKingdom   if true, it generates a distance matrix with distance
-0011 %                   Inf for organisms from another domains (Prokaryota,
-0012 %                   Eukaryota) (optional, default false)
-0013 %
-0014 %   Output:
-0015 %   phylDistStruct  a structure with a list of organism ids and a matrix
-0016 %                   that specifies their pairwise distances
-0017 %
-0018 %   NOTE: This simple metric is based on the number of nodes two organisms
-0019 %   are away from each other in KEGG
-0020 %
-0021 % Usage: phylDistStruct=getPhylDist(keggPath,onlyInKingdom)
-0022 
-0023 if nargin<1
-0024     keggPath='RAVEN/external/kegg';
-0025 else
-0026     keggPath=char(keggPath);
-0027 end
-0028 if nargin<2
-0029     onlyInKingdom=false;
-0030 end
-0031 
-0032 %Check if the reactions have been parsed before and saved. If so, load the
-0033 %model
-0034 ravenPath=findRAVENroot();
-0035 distFile=fullfile(ravenPath,'external','kegg','keggPhylDist.mat');
-0036 if exist(distFile, 'file')
-0037     fprintf(['Importing the KEGG phylogenetic distance matrix from ' strrep(distFile,'\','/') '... ']);
-0038     load(distFile);
-0039     fprintf('COMPLETE\n');
-0040 else
-0041     fprintf(['Cannot locate ' strrep(distFile,'\','/') '\n']);
-0042     if ~isfile(fullfile(keggPath,'taxonomy'))
-0043         EM=fprintf(['The file ''taxonomy'' cannot be located at ' strrep(keggPath,'\','/') '/ and should be downloaded from the KEGG FTP.\n']);
-0044         dispEM(EM);
-0045     else
-0046         fprintf('Generating keggPhylDist.mat file... ');
-0047         %Open the file that describes the naming of the species
-0048         fid = fopen(fullfile(keggPath,'taxonomy'), 'r');
-0049         
-0050         phylDistStruct.ids={};
-0051         phylDistStruct.names={};
-0052         
-0053         %Keeps the categories for each organism
-0054         orgCat={};
-0055         
-0056         currentCat={};
-0057         %Keeps track of the current category
-0058         
-0059         depth=0;
-0060         %Keeps track of the current tree depth
-0061         
-0062         %Loop through the file
-0063         orgCounter=0;
-0064         while 1
-0065             %Get the next line
-0066             tline = fgetl(fid);
-0067             
-0068             %Abort at end of file
-0069             if ~ischar(tline)
-0070                 break;
-0071             end
-0072             
-0073             if any(tline)
-0074                 %Check if it's a new category
-0075                 if tline(1)=='#'
-0076                     %Find the first space (=depth +1)
-0077                     sPos=strfind(tline,' ')-1;
-0078                     %Should always exist
-0079                     
-0080                     sPos=sPos(1);
-0081                     
-0082                     %If we have stepped back one step in the tree
-0083                     if sPos<depth
-0084                         currentCat=currentCat(1:sPos);
-0085                     end
-0086                     depth=sPos;
-0087                     
-0088                     currentCat{depth}=tline(sPos+2:end);
-0089                 else
-0090                     orgCounter=orgCounter+1;
-0091                     %It is an organism Get the id between first and second
-0092                     %white space
-0093                     sPos=find(isstrprop(tline, 'wspace'));
-0094                     %Should always exist
-0095                     
-0096                     phylDistStruct.ids{orgCounter}=tline(sPos(1)+1:sPos(2)-1);
-0097                     phylDistStruct.names{orgCounter}=tline(sPos(3)+1:end);
-0098                     orgCat{orgCounter}=currentCat;
-0099                 end
-0100             end
-0101         end
-0102         %Generate a distance matrix (very straight forward here, not neat)
-0103         phylDistStruct.distMat=zeros(numel(phylDistStruct.ids));
-0104         phylDistStructOnlyInKingdom.distMat=zeros(numel(phylDistStruct.ids));
-0105         phylDistStructOnlyInKingdom.ids=phylDistStruct.ids;
-0106         for i=1:numel(phylDistStruct.ids)
-0107             for j=1:numel(phylDistStruct.ids)
-0108                 if ~strcmp(orgCat{i}(1),orgCat{j}(1))
-0109                     phylDistStructOnlyInKingdom.distMat(i,j)=Inf;
-0110                 end
-0111                 %Calculate the distance between then
-0112                 dist=numel(orgCat{i})-numel(orgCat{j});
-0113                 if dist>0
-0114                     aCat=orgCat{i}(1:end-dist);
-0115                 else
-0116                     aCat=orgCat{i};
-0117                 end
-0118                 if dist<0
-0119                     bCat=orgCat{j}(1:end+dist);
-0120                 else
-0121                     bCat=orgCat{j};
-0122                 end
-0123                 
-0124                 %Loop through the categories and stop when they are the
-0125                 %same
-0126                 for k=numel(aCat):-1:1
-0127                     if strcmp(aCat{k},bCat{k})
-0128                         break;
-0129                     end
-0130                 end
-0131                 phylDistStruct.distMat(i,j)=dist+numel(aCat)-k;
-0132             end
-0133         end
-0134         %Save the structure
-0135         save(distFile,'phylDistStruct','phylDistStructOnlyInKingdom');
-0136         fprintf('COMPLETE\n');
-0137     end
-0138 end
-0139 if onlyInKingdom==true
-0140     phylDistStruct=phylDistStructOnlyInKingdom;
-0141 end
-0142 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/external/kegg/getRxnsFromKEGG.html b/doc/external/kegg/getRxnsFromKEGG.html deleted file mode 100644 index f419f5d0f..000000000 --- a/doc/external/kegg/getRxnsFromKEGG.html +++ /dev/null @@ -1,620 +0,0 @@ - - - - Description of getRxnsFromKEGG - - - - - - - - - -
Home > external > kegg > getRxnsFromKEGG.m
- - - -

getRxnsFromKEGG -

- -

PURPOSE ^

-
getRxnsFromKEGG
- -

SYNOPSIS ^

-
function [model,isSpontaneous,isUndefinedStoich,isIncomplete,isGeneral]=getRxnsFromKEGG(keggPath)
- -

DESCRIPTION ^

-
 getRxnsFromKEGG
-   Retrieves information on all reactions stored in KEGG database
-
-   Input:
-   keggPath            if keggRxns.mat is not in the RAVEN\external\kegg
-                       directory, this function will attempt to read data
-                       from a local FTP dump of the KEGG database.
-                       keggPath is the path to the root of this database
-
-   Output:
-   model               a model structure generated from the database. The
-                       following fields are filled
-       id                  'KEGG'
-       name         'Automatically generated from KEGG database'
-       rxns                KEGG reaction ids
-       rxnNames            Name for each reaction entry
-       mets                KEGG compound ids. If the equations use
-                           stoichiometry such as ID(n+1) then the whole
-                           expression is saved as the id
-       eccodes             Corresponding ec-number if available
-       rxnMiriams          Contains reaction specific information such as
-                           KO id and pathways that the reaction is
-                           associated to
-       S                   Stoichiometric matrix
-       lb                  -1000 for all reactions
-       ub                  1000 for all reactions
-       rev                 1 for reversible and 0 for irreversible. For
-                           reactions present in pathway maps the
-                           reversibility is taken from there
-       b                   0 for all metabolites
-   isSpontaneous       a cell array with the reactions labelled as
-                       "spontaneous"
-   isUndefinedStoich    a cell array with the reactions labelled as with
-                       undefined stoichiometry
-   isIncomplete        a cell array with the reactions labelled as
-                       "incomplete", "erroneous" or "unclear"
-   isGeneral           a cell array with the reactions labelled as
-                       "general reaction"
-
-   NOTE: Reactions on the form A <=> A + B will not be loaded. If the file
-   keggRxns.mat is in the RAVEN/external/kegg directory it will be loaded
-   instead of parsing of the KEGG files. If it does not exist it will be
-   saved after parsing of the KEGG files. In general, you should remove
-   the keggRxns.mat file along with other KEGG mat files if you want to
-   rebuild the model structure from a newer version of KEGG.
-
- Usage: [model,isSpontaneous,isUndefinedStoich,isIncomplete,...
-    isGeneral]=getRxnsFromKEGG(keggPath)
-
- NOTE: This is how one entry looks in the file
-
- ENTRY       R00010                      Reaction
- NAME        alpha,alpha-trehalose glucohydrolase
- DEFINITION  alpha,alpha-Trehalose + H2O <=> 2 D-Glucose
- EQUATION    C01083 + C00001 <=> 2 C00031
- REMARK      Same as: R06103
- RCLASS      RC00049  C00031_C01083
- ENZYME      3.2.1.28
- PATHWAY     rn00500  Starch and sucrose metabolism
-             rn01100  Metabolic pathways
- ORTHOLOGY   K01194  alpha,alpha-trehalase [EC:3.2.1.28]
- DBLINKS     RHEA: 32678
- ///
-
- The file is not tab-delimited. Instead each label is 12 characters
- (except for '///')
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function [model,isSpontaneous,isUndefinedStoich,isIncomplete,...
-0002     isGeneral]=getRxnsFromKEGG(keggPath)
-0003 % getRxnsFromKEGG
-0004 %   Retrieves information on all reactions stored in KEGG database
-0005 %
-0006 %   Input:
-0007 %   keggPath            if keggRxns.mat is not in the RAVEN\external\kegg
-0008 %                       directory, this function will attempt to read data
-0009 %                       from a local FTP dump of the KEGG database.
-0010 %                       keggPath is the path to the root of this database
-0011 %
-0012 %   Output:
-0013 %   model               a model structure generated from the database. The
-0014 %                       following fields are filled
-0015 %       id                  'KEGG'
-0016 %       name         'Automatically generated from KEGG database'
-0017 %       rxns                KEGG reaction ids
-0018 %       rxnNames            Name for each reaction entry
-0019 %       mets                KEGG compound ids. If the equations use
-0020 %                           stoichiometry such as ID(n+1) then the whole
-0021 %                           expression is saved as the id
-0022 %       eccodes             Corresponding ec-number if available
-0023 %       rxnMiriams          Contains reaction specific information such as
-0024 %                           KO id and pathways that the reaction is
-0025 %                           associated to
-0026 %       S                   Stoichiometric matrix
-0027 %       lb                  -1000 for all reactions
-0028 %       ub                  1000 for all reactions
-0029 %       rev                 1 for reversible and 0 for irreversible. For
-0030 %                           reactions present in pathway maps the
-0031 %                           reversibility is taken from there
-0032 %       b                   0 for all metabolites
-0033 %   isSpontaneous       a cell array with the reactions labelled as
-0034 %                       "spontaneous"
-0035 %   isUndefinedStoich    a cell array with the reactions labelled as with
-0036 %                       undefined stoichiometry
-0037 %   isIncomplete        a cell array with the reactions labelled as
-0038 %                       "incomplete", "erroneous" or "unclear"
-0039 %   isGeneral           a cell array with the reactions labelled as
-0040 %                       "general reaction"
-0041 %
-0042 %   NOTE: Reactions on the form A <=> A + B will not be loaded. If the file
-0043 %   keggRxns.mat is in the RAVEN/external/kegg directory it will be loaded
-0044 %   instead of parsing of the KEGG files. If it does not exist it will be
-0045 %   saved after parsing of the KEGG files. In general, you should remove
-0046 %   the keggRxns.mat file along with other KEGG mat files if you want to
-0047 %   rebuild the model structure from a newer version of KEGG.
-0048 %
-0049 % Usage: [model,isSpontaneous,isUndefinedStoich,isIncomplete,...
-0050 %    isGeneral]=getRxnsFromKEGG(keggPath)
-0051 %
-0052 % NOTE: This is how one entry looks in the file
-0053 %
-0054 % ENTRY       R00010                      Reaction
-0055 % NAME        alpha,alpha-trehalose glucohydrolase
-0056 % DEFINITION  alpha,alpha-Trehalose + H2O <=> 2 D-Glucose
-0057 % EQUATION    C01083 + C00001 <=> 2 C00031
-0058 % REMARK      Same as: R06103
-0059 % RCLASS      RC00049  C00031_C01083
-0060 % ENZYME      3.2.1.28
-0061 % PATHWAY     rn00500  Starch and sucrose metabolism
-0062 %             rn01100  Metabolic pathways
-0063 % ORTHOLOGY   K01194  alpha,alpha-trehalase [EC:3.2.1.28]
-0064 % DBLINKS     RHEA: 32678
-0065 % ///
-0066 %
-0067 % The file is not tab-delimited. Instead each label is 12 characters
-0068 % (except for '///')
-0069 %
-0070 
-0071 ravenPath=findRAVENroot();
-0072 
-0073 if nargin<1
-0074     keggPath=fullfile(ravenPath,'external','kegg');
-0075 else
-0076     keggPath=char(keggPath);
-0077 end
-0078 
-0079 %Check if the reactions have been parsed before and saved. If so, load the
-0080 %model
-0081 rxnsFile=fullfile(ravenPath,'external','kegg','keggRxns.mat');
-0082 if exist(rxnsFile, 'file')
-0083     fprintf(['Importing KEGG reactions from ' strrep(rxnsFile,'\','/') '... ']);
-0084     load(rxnsFile);
-0085 else
-0086     fprintf(['NOTE: Cannot locate ' strrep(rxnsFile,'\','/') ', it will therefore be generated from the local KEGG database\n']);
-0087     if ~isfile(fullfile(keggPath,'reaction')) || ~isfile(fullfile(keggPath,'reaction.lst')) || ~isfile(fullfile(keggPath,'reaction_mapformula.lst'))
-0088         EM=fprintf(['The files ''reaction'', ''reaction.lst'' and ''reaction_mapformula.lst'' cannot be located at ' strrep(keggPath,'\','/') '/ and should be downloaded from the KEGG FTP\n']);
-0089         dispEM(EM);
-0090     else
-0091         fprintf('Generating keggRxns.mat file... ');
-0092         %Add new functionality in the order specified in models
-0093         model.id='KEGG';
-0094         model.name='Automatically generated from KEGG database';
-0095         
-0096         %Preallocate memory for 15000 reactions
-0097         model.rxns=cell(15000,1);
-0098         model.rxnNames=cell(15000,1);
-0099         model.eccodes=cell(15000,1);
-0100         model.subSystems=cell(15000,1);
-0101         model.rxnMiriams=cell(15000,1);
-0102         model.rxnNotes=cell(15000,1);
-0103         equations=cell(15000,1);
-0104         %Temporarily store the equations
-0105         
-0106         isSpontaneous=false(15000,1);
-0107         isIncomplete=false(15000,1);
-0108         isGeneral=false(15000,1);
-0109 
-0110         %First load information on reaction ID, reaction name, KO, pathway,
-0111         %and ec-number
-0112         fid = fopen(fullfile(keggPath,'reaction'), 'r');
-0113         
-0114         %Keep track of how many reactions have been added
-0115         rxnCounter=0;
-0116         
-0117         %Loop through the file
-0118         orthology=false;
-0119         pathway=false;
-0120         module=false;
-0121         while 1
-0122             %Get the next line
-0123             tline = fgetl(fid);
-0124             
-0125             %Abort at end of file
-0126             if ~ischar(tline)
-0127                 break;
-0128             end
-0129             
-0130             %Skip '///'
-0131             if numel(tline)<12
-0132                 continue;
-0133             end
-0134             % Skip other lines with unused information
-0135             if strcmp(tline(1:5),'BRITE')
-0136                 pathway = false;
-0137                 continue;
-0138             end
-0139 
-0140             %Check if it's a new reaction
-0141             if strcmp(tline(1:12),'ENTRY       ')
-0142                 rxnCounter=rxnCounter+1;
-0143                 
-0144                 %Add empty strings where there should be such
-0145                 model.rxnNames{rxnCounter}='';
-0146                 model.eccodes{rxnCounter}='';
-0147                 %model.subSystems{rxnCounter}={''}; %remain empty cell
-0148                 model.rxnNotes{rxnCounter}='';
-0149                 equations{rxnCounter}='';
-0150                 
-0151                 %Add reaction ID (always 6 characters)
-0152                 model.rxns{rxnCounter}=tline(13:18);
-0153                 orthology=false;
-0154                 pathway=false;
-0155                 module=false;
-0156                 
-0157                 %Add KEGG reaction ID miriam
-0158                 tempStruct=model.rxnMiriams{rxnCounter};
-0159                 tempStruct.name{1,1}='kegg.reaction';
-0160                 tempStruct.value{1,1}=tline(13:18);
-0161                 model.rxnMiriams{rxnCounter}=tempStruct;
-0162             end
-0163             
-0164             %Add name
-0165             if strcmp(tline(1:12),'NAME        ')
-0166                 model.rxnNames{rxnCounter}=tline(13:end);
-0167             end
-0168             
-0169             %Add whether the comment includes "incomplete", "erroneous" or
-0170             %"unclear"
-0171             if strcmp(tline(1:12),'COMMENT     ')
-0172                 %Read all text until '///', 'RPAIR', 'ENZYME', 'PATHWAY' or 'RCLASS'
-0173                 commentText=tline(13:end);
-0174                 while 1
-0175                     tline = fgetl(fid);
-0176                     if ~strcmp(tline(1:3),'///') && ~strcmp(tline(1:3),'RPA') && ~strcmp(tline(1:3),'ENZ') && ~strcmp(tline(1:3),'PAT') && ~strcmp(tline(1:3),'RCL')
-0177                         commentText=[commentText ' ' strtrim(tline)];
-0178                     else
-0179                         break;
-0180                     end
-0181                 end
-0182                 if any(regexpi(commentText,'SPONTANEOUS'))
-0183                     %It should start this way
-0184                     isSpontaneous(rxnCounter)=true;
-0185                 end
-0186                 if any(regexpi(commentText,'INCOMPLETE')) || any(regexpi(commentText,'ERRONEOUS')) || any(regexpi(commentText,'UNCLEAR'))
-0187                     isIncomplete(rxnCounter)=true;
-0188                 end
-0189                 if any(regexpi(commentText,'GENERAL REACTION'))
-0190                     %It should start this way
-0191                     isGeneral(rxnCounter)=true;
-0192                 end
-0193                 
-0194                 %Go to next iteration if it is '///'
-0195                 if numel(tline)<12
-0196                     continue;
-0197                 end
-0198             end
-0199             
-0200             %Add ec-number
-0201             if strcmp(tline(1:12),'ENZYME      ')
-0202                 model.eccodes{rxnCounter}=tline(13:end);
-0203                 model.eccodes{rxnCounter}=deblank(model.eccodes{rxnCounter});
-0204                 model.eccodes{rxnCounter}=regexprep(model.eccodes{rxnCounter},'\s+',';');
-0205             end
-0206             if numel(tline)>8
-0207                 if strcmp(tline(1:9),'REFERENCE')
-0208                     pathway=false;
-0209                     orthology=false;
-0210                 end
-0211             end
-0212             
-0213             %Add module ids
-0214             if numel(tline)>18
-0215                 if strcmp(tline(1:12),'MODULE      ') || module==true
-0216                     pathway=false;
-0217                     orthology=false;
-0218                     if isstruct(model.rxnMiriams{rxnCounter})
-0219                         addToIndex=numel(model.rxnMiriams{rxnCounter}.name)+1;
-0220                     else
-0221                         addToIndex=1;
-0222                     end
-0223                     tempStruct=model.rxnMiriams{rxnCounter};
-0224                     tempStruct.name{addToIndex,1}='kegg.module';
-0225                     tempStruct.value{addToIndex,1}=tline(13:18);
-0226                     model.rxnMiriams{rxnCounter}=tempStruct;
-0227                 end
-0228             end
-0229             
-0230             %Add RHEA id
-0231             if numel(tline)>18
-0232                 if strcmp(tline(1:18),'DBLINKS     RHEA: ')
-0233                     pathway=false;
-0234                     orthology=false;
-0235                     module=false;
-0236                     if isstruct(model.rxnMiriams{rxnCounter})
-0237                         addToIndex=numel(model.rxnMiriams{rxnCounter}.name)+1;
-0238                     else
-0239                         addToIndex=1;
-0240                     end
-0241                     tempStruct=model.rxnMiriams{rxnCounter};
-0242                     tempStruct.name{addToIndex,1}='rhea';
-0243                     tempStruct.value{addToIndex,1}=tline(19:end);
-0244                     model.rxnMiriams{rxnCounter}=tempStruct;
-0245                 end
-0246             end
-0247             
-0248             %Add KO-ids
-0249             if numel(tline)>16
-0250                 if strcmp(tline(1:16),'ORTHOLOGY   KO: ') || strcmp(tline(1:16),'            KO: ') || strcmp(tline(1:12),'ORTHOLOGY   ') || orthology==true
-0251                     pathway=false;
-0252                     module=false;
-0253                     %Check if KO has been added already (each reaction may
-0254                     %belong to several)
-0255                     if isstruct(model.rxnMiriams{rxnCounter})
-0256                         addToIndex=numel(model.rxnMiriams{rxnCounter}.name)+1;
-0257                     else
-0258                         addToIndex=1;
-0259                     end
-0260                     
-0261                     tempStruct=model.rxnMiriams{rxnCounter};
-0262                     tempStruct.name{addToIndex,1}='kegg.orthology';
-0263                     if strcmp(tline(13:16),'KO:')
-0264                         %This is in the old version
-0265                         tempStruct.value{addToIndex,1}=tline(17:22);
-0266                     else
-0267                         %This means that it found one KO in the new format
-0268                         %and that subsequent lines might be other KOs
-0269                         orthology=true;
-0270                         tempStruct.value{addToIndex,1}=tline(13:18);
-0271                     end
-0272                     model.rxnMiriams{rxnCounter}=tempStruct;
-0273                 end
-0274             end
-0275             
-0276             %Add pathways
-0277             if numel(tline)>18
-0278                 if strcmp(tline(1:18),'PATHWAY     PATH: ') || strcmp(tline(1:18),'            PATH: ') || strcmp(tline(1:12),'PATHWAY     ') || pathway==true
-0279                     orthology=false;
-0280                     module=false;
-0281                     %Check if annotation has been added already
-0282                     if isstruct(model.rxnMiriams{rxnCounter})
-0283                         addToIndex=numel(model.rxnMiriams{rxnCounter}.name)+1;
-0284                     else
-0285                         addToIndex=1;
-0286                     end
-0287                     
-0288                     tempStruct=model.rxnMiriams{rxnCounter};
-0289                     tempStruct.name{addToIndex,1}='kegg.pathway';
-0290                     %If it is the old version
-0291                     if strcmp(tline(14:17),'PATH:')
-0292                         tempStruct.value{addToIndex,1}=tline(19:25);
-0293                     else
-0294                         %If it is the new version
-0295                         tempStruct.value{addToIndex,1}=tline(13:19);
-0296                         pathway=true;
-0297                     end
-0298                     
-0299                     %Do not save global or overview pathways. The ids for
-0300                     %such pathways begin with rn011 or rn012
-0301                     if ~strcmp('rn011',tempStruct.value{addToIndex,1}(1:5)) && ~strcmp('rn012',tempStruct.value{addToIndex,1}(1:5))
-0302                         model.rxnMiriams{rxnCounter}=tempStruct;
-0303                         
-0304                         %Also save the subSystems names. For the old KEGG
-0305                         %format, only the first mentioned subsystem is
-0306                         %picked. Use the newer KEGG format to fetch all the
-0307                         %subsystems
-0308                         if strcmp(tline(14:17),'PATH:')
-0309                             %The old format
-0310                             model.subSystems{rxnCounter}=tline(28:end);
-0311                         else
-0312                             %The new format
-0313                             model.subSystems{rxnCounter,1}{numel(model.subSystems{rxnCounter,1})+1,1}=tline(22:end);
-0314                         end
-0315                     end
-0316                 end
-0317             end
-0318         end
-0319         
-0320         %Close the file
-0321         fclose(fid);
-0322         
-0323         %This is done here since the the indexes won't match since some
-0324         %reactions are removed along the way
-0325         isIncomplete=model.rxns(isIncomplete);
-0326         isGeneral=model.rxns(isGeneral);
-0327         isSpontaneous=model.rxns(isSpontaneous);
-0328 
-0329         %If too much space was allocated, shrink the model
-0330         model.rxns=model.rxns(1:rxnCounter);
-0331         model.rxnNames=model.rxnNames(1:rxnCounter);
-0332         model.eccodes=model.eccodes(1:rxnCounter);
-0333         equations=equations(1:rxnCounter);
-0334         model.rxnMiriams=model.rxnMiriams(1:rxnCounter);
-0335         model.rxnNotes=model.rxnNotes(1:rxnCounter);
-0336         model.subSystems=model.subSystems(1:rxnCounter);
-0337         
-0338         emptySubSys = cellfun(@isempty,model.subSystems);
-0339         model.subSystems(emptySubSys) = {{''}};
-0340 
-0341         %Then load the equations from another file. This is because the
-0342         %equations are easier to retrieve from there
-0343         
-0344         %The format is rxnID: equation The reactions should have been
-0345         %loaded in the exact same order
-0346         fid = fopen(fullfile(keggPath,'reaction.lst'), 'r');
-0347         
-0348         %Loop through the file
-0349         for i=1:rxnCounter
-0350             %Get the next line
-0351             tline = fgetl(fid);
-0352             
-0353             equations{i}=tline(9:end);
-0354         end
-0355         
-0356         %Close the file
-0357         fclose(fid);
-0358         
-0359         %Several equations may have two whitespaces between the last
-0360         %reactant and the reversible arrow sign. The number of whitespaces
-0361         %is thus reduced to one
-0362         equations = regexprep(equations,'  <=>', ' <=>');
-0363         
-0364         %Construct the S matrix and list of metabolites
-0365         [S, mets, badRxns]=constructS(equations);
-0366         model.S=S;
-0367         model.mets=mets;
-0368         
-0369         %There is some limited evidence for directionality in
-0370         %reaction_mapformula.lst. The information there concerns how the
-0371         %reactions are drawn in the KEGG maps. If a reaction is
-0372         %irreversible in the same direction for all maps, then I consider
-0373         %is irreversible, otherwise reversible. Also, not all reactions are
-0374         %present in the maps, so not all will have directionality. They
-0375         %will be considered to be reversible
-0376         
-0377         %The format is R00005: 00330: C01010 => C00011 Generate a
-0378         %reversibility structure with the fields: *rxns: reaction ids
-0379         %*product: one met id that is a product. This is because the
-0380         %*reactions might be written in another direction compared to in
-0381         % the reactions.lst file
-0382         %*rev: 1 if reversible, otherwise 0
-0383         reversibility.rxns={};
-0384         reversibility.product={};
-0385         reversibility.rev=[];
-0386         
-0387         fid = fopen(fullfile(keggPath,'reaction_mapformula.lst'), 'r');
-0388         while 1
-0389             %Get the next line
-0390             tline = fgetl(fid);
-0391             
-0392             %Abort at end of file
-0393             if ~ischar(tline)
-0394                 break;
-0395             end
-0396             
-0397             rxn=tline(1:6);
-0398             prod=tline(end-5:end);
-0399             rev=any(strfind(tline,'<=>'));
-0400             if isempty(reversibility.rxns)
-0401                 reversibility.rxns{1}=rxn;
-0402                 reversibility.product{1}=prod;
-0403                 reversibility.rev(1)=rev;
-0404             elseif strcmp(reversibility.rxns(end),rxn)
-0405                 %Check if the reaction was added before. It's an ordered
-0406                 %list, so only check the last element If it's reversible in
-0407                 %the new reaction or reversible in the old reaction then
-0408                 %set (keep) to be reversible
-0409                 if rev==1 || reversibility.rev(end)==1
-0410                     reversibility.rev(end)=1;
-0411                 else
-0412                     %This means that the reaction was already loaded, that
-0413                     %it was irreversible before and irreversible in the new
-0414                     %reaction. However, it could be that they are written
-0415                     %in diferent directions. If the product differ, then
-0416                     %set to be reversible. This assumes that the reactions
-0417                     %are written with the same metabolite as the last one
-0418                     %if they are in the same direction
-0419                     if ~strcmp(prod,reversibility.product(end))
-0420                         reversibility.rev(end)=1;
-0421                     end
-0422                 end
-0423             else
-0424                 reversibility.rxns=[reversibility.rxns;rxn];
-0425                 reversibility.product=[reversibility.product;prod];
-0426                 reversibility.rev=[reversibility.rev;rev];
-0427             end
-0428         end
-0429         fclose(fid);
-0430         
-0431         %Update the reversibility
-0432         model.rev=ones(rxnCounter,1);
-0433         %Match the reaction ids
-0434         irrevIDs=find(reversibility.rev==0);
-0435         [~, I]=ismember(reversibility.rxns(irrevIDs),model.rxns);
-0436         [~, prodMetIDs]=ismember(reversibility.product(irrevIDs),model.mets);
-0437         model.rev(I)=0;
-0438         
-0439         %See if the reactions are written in the same order in model.S
-0440         linearInd=sub2ind(size(model.S), prodMetIDs, I);
-0441         changeOrder=I(model.S(linearInd)<0);
-0442         %Change the order of these reactions
-0443         model.S(:,changeOrder)=model.S(:,changeOrder).*-1;
-0444         
-0445         %Add some stuff to get a correct model structure
-0446         model.ub=ones(rxnCounter,1)*1000;
-0447         model.lb=model.rev*-1000;
-0448         model.c=zeros(rxnCounter,1);
-0449         model.b=zeros(numel(model.mets),1);
-0450         model=removeReactions(model,badRxns,true,true);
-0451         
-0452         %Identify reactions with undefined stoichiometry. Such
-0453         %reactions involve metabolites with an ID containing the letter "n"
-0454         %or "m"
-0455         I=cellfun(@any,strfind(model.mets,'n')) | cellfun(@any,strfind(model.mets,'m'));
-0456         [~, J]=find(model.S(I,:));
-0457         isUndefinedStoich=model.rxns(unique(J));   
-0458         %Sort model that metabolites with undefined stoichiometry would
-0459         %appear in the end of metabolites list
-0460         metList=[model.mets(~I);model.mets(I)];
-0461         [~,metIndexes]=ismember(metList,model.mets);
-0462         model=permuteModel(model,metIndexes,'mets');
-0463         
-0464         %Sort model that i) spontaneous, ii) with undefined
-0465         %stoichiometry, iii) incomplete and iv) general reactions would bve
-0466         %ranked in the end of the model
-0467         endRxnList=unique([model.rxns(ismember(model.rxns,isSpontaneous));model.rxns(ismember(model.rxns,isUndefinedStoich));model.rxns(ismember(model.rxns,isIncomplete));model.rxns(ismember(model.rxns,isGeneral))],'stable');
-0468         rxnList=[model.rxns(~ismember(model.rxns,endRxnList));endRxnList];
-0469         [~,rxnIndexes]=ismember(rxnList,model.rxns);
-0470         model=permuteModel(model,rxnIndexes,'rxns');
-0471         
-0472         %Add information in rxnNotes, whether reaction belongs to any of
-0473         %type i-iv mentioned a few lines above
-0474         for i=(numel(rxnList)-numel(endRxnList)+1):numel(model.rxns)
-0475             if ismember(model.rxns(i),isSpontaneous)
-0476                 model.rxnNotes(i)=strcat(model.rxnNotes(i),'Spontaneous');
-0477             end
-0478             if ismember(model.rxns(i),isUndefinedStoich)
-0479                 if isempty(model.rxnNotes{i})
-0480                     model.rxnNotes(i)=strcat(model.rxnNotes(i),'With undefined stoichiometry');
-0481                 else
-0482                     model.rxnNotes(i)=strcat(model.rxnNotes(i),', with undefined stoichiometry');
-0483                 end
-0484             end
-0485             if ismember(model.rxns(i),isIncomplete)
-0486                 if isempty(model.rxnNotes{i})
-0487                     model.rxnNotes(i)=strcat(model.rxnNotes(i),'Incomplete');
-0488                 else
-0489                     model.rxnNotes(i)=strcat(model.rxnNotes(i),', incomplete');
-0490                 end
-0491             end
-0492             if ismember(model.rxns(i),isGeneral)
-0493                 if isempty(model.rxnNotes{i})
-0494                     model.rxnNotes(i)=strcat(model.rxnNotes(i),'General');
-0495                 else
-0496                     model.rxnNotes(i)=strcat(model.rxnNotes(i),', general');
-0497                 end
-0498             end
-0499             model.rxnNotes(i)=strcat(model.rxnNotes(i),' reaction');
-0500         end
-0501         
-0502         %Save the model structure
-0503         save(rxnsFile,'model','isGeneral','isIncomplete','isUndefinedStoich','isSpontaneous');
-0504     end
-0505 end
-0506 fprintf('COMPLETE\n');
-0507 
-0508 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/external/kegg/getWSLpath.html b/doc/external/kegg/getWSLpath.html deleted file mode 100644 index a6bba443a..000000000 --- a/doc/external/kegg/getWSLpath.html +++ /dev/null @@ -1,83 +0,0 @@ - - - - Description of getWSLpath - - - - - - - - - -
Home > external > kegg > getWSLpath.m
- - - -

getWSLpath -

- -

PURPOSE ^

-
getWSLpath
- -

SYNOPSIS ^

-
function path=getWSLpath(path)
- -

DESCRIPTION ^

-
 getWSLpath
-   Translate Windows-style path to its Unix WSL (Windows Subsystem for
-   Linux) equivalent.
-
-   Input:
-   path        string with directory of file path, in Windows-style (e.g.
-               'C:\Directory\')
-
-   Output:
-   path        string with directory of file path, in Unix style (e.g.
-               '/mnt/c/Directory/')
-
-   Uses the WSL function 'wslpath' to translate the path.
-
- Usage: path=getWSLpath(path)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function path=getWSLpath(path)
-0002 % getWSLpath
-0003 %   Translate Windows-style path to its Unix WSL (Windows Subsystem for
-0004 %   Linux) equivalent.
-0005 %
-0006 %   Input:
-0007 %   path        string with directory of file path, in Windows-style (e.g.
-0008 %               'C:\Directory\')
-0009 %
-0010 %   Output:
-0011 %   path        string with directory of file path, in Unix style (e.g.
-0012 %               '/mnt/c/Directory/')
-0013 %
-0014 %   Uses the WSL function 'wslpath' to translate the path.
-0015 %
-0016 % Usage: path=getWSLpath(path)
-0017 [status,path]=system(['wsl wslpath ''' path '''']);
-0018 if status==-1
-0019     error('Cannot get access to Windows Subsystem for Linux, check your WSL installation')
-0020 end
-0021 path=path(1:end-1);% Remove final character (line-break)
-0022 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/external/kegg/index.html b/doc/external/kegg/index.html deleted file mode 100644 index ee1961280..000000000 --- a/doc/external/kegg/index.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - Index for Directory external\kegg - - - - - - - - - - -
< Master indexIndex for external\kegg >
- -

Index for external\kegg

- -

Matlab files in this directory:

- -
 constructMultiFastaconstructMultiFasta
 getGenesFromKEGGgetGenesFromKEGG
 getKEGGModelForOrganismgetKEGGModelForOrganism
 getMetsFromKEGGgetMetsFromKEGG
 getModelFromKEGGgetModelFromKEGG
 getPhylDistgetPhylDist
 getRxnsFromKEGGgetRxnsFromKEGG
 getWSLpathgetWSLpath
- -

Other Matlab-specific files in this directory:

-
    -
  • keggMets.mat
  • keggPhylDist.mat
  • keggRxns.mat
- - -
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/external/makeFakeBlastStructure.html b/doc/external/makeFakeBlastStructure.html deleted file mode 100644 index 4dde45faf..000000000 --- a/doc/external/makeFakeBlastStructure.html +++ /dev/null @@ -1,129 +0,0 @@ - - - - Description of makeFakeBlastStructure - - - - - - - - - -
Home > external > makeFakeBlastStructure.m
- - - -

makeFakeBlastStructure -

- -

PURPOSE ^

-
makeFakeBlastStructure
- -

SYNOPSIS ^

-
function blastStructure=makeFakeBlastStructure(orthologList,sourceModelID,getModelFor)
- -

DESCRIPTION ^

-
 makeFakeBlastStructure
-   Makes a fake blastStructure, that would normally be generated by
-   getBlast. This allows to feed a predefined list of orthologs to
-   getModelFromHomology while retaining the further use of that function.
-   For this function to work, it is crucial that the orthologList is a
-   cell array where the first column contains the genes from the source
-   organism, and the second column contains the genes from the target
-   organism
-  
-   orthologList        cell array of orthologous genes, where the first
-                       column contains the genes from the source organism,
-                       while the second column contains the genes from the
-                       target organism
-   sourceModelID       ID of the model that will be used as template, that
-                       contains the genes in the first column of
-                       orthologList
-   getModelFor         the name of the organism to build a model for,
-                       identical to the getModelFor parameter in the
-                       getModelFromHomology function
-
-   blastStructure      a fake blastStructure, where the evalue, identity
-                       and aligLen are set at extreme values, such that
-                       all orthologous pairs will pass the filter when
-                       running getModelFromHomology
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function blastStructure=makeFakeBlastStructure(orthologList,sourceModelID,getModelFor)
-0002 % makeFakeBlastStructure
-0003 %   Makes a fake blastStructure, that would normally be generated by
-0004 %   getBlast. This allows to feed a predefined list of orthologs to
-0005 %   getModelFromHomology while retaining the further use of that function.
-0006 %   For this function to work, it is crucial that the orthologList is a
-0007 %   cell array where the first column contains the genes from the source
-0008 %   organism, and the second column contains the genes from the target
-0009 %   organism
-0010 %
-0011 %   orthologList        cell array of orthologous genes, where the first
-0012 %                       column contains the genes from the source organism,
-0013 %                       while the second column contains the genes from the
-0014 %                       target organism
-0015 %   sourceModelID       ID of the model that will be used as template, that
-0016 %                       contains the genes in the first column of
-0017 %                       orthologList
-0018 %   getModelFor         the name of the organism to build a model for,
-0019 %                       identical to the getModelFor parameter in the
-0020 %                       getModelFromHomology function
-0021 %
-0022 %   blastStructure      a fake blastStructure, where the evalue, identity
-0023 %                       and aligLen are set at extreme values, such that
-0024 %                       all orthologous pairs will pass the filter when
-0025 %                       running getModelFromHomology
-0026 
-0027 if nargin<3
-0028     error('All three parameters should be set');
-0029 end
-0030 sourceModelID=char(sourceModelID);
-0031 getModelFor=char(getModelFor);
-0032 
-0033 % Check whether orthologList is a cell array, with two columns, and more
-0034 % than 10 rows
-0035 if (~iscell(orthologList) || ~(size(orthologList,2)==2) || ~(size(orthologList,1)>=10))
-0036     error('orthologList should be a cell array with two columns');
-0037 end
-0038 
-0039 blastStructure(1).fromId=sourceModelID;
-0040 blastStructure(1).toId=getModelFor;
-0041 blastStructure(1).fromGenes=orthologList(:,1);
-0042 blastStructure(1).toGenes=orthologList(:,2);
-0043 
-0044 blastStructure(2).fromId=getModelFor;
-0045 blastStructure(2).toId=sourceModelID;
-0046 blastStructure(2).fromGenes=orthologList(:,2);
-0047 blastStructure(2).toGenes=orthologList(:,1);
-0048 
-0049 blastStructure(1).evalue=zeros(size(orthologList,1),1);
-0050 blastStructure(2).evalue=zeros(size(orthologList,1),1);
-0051 blastStructure(1).identity(1:size(orthologList,1),1)=100;
-0052 blastStructure(2).identity(1:size(orthologList,1),1)=100;
-0053 blastStructure(1).aligLen(1:size(orthologList,1),1)=1000;
-0054 blastStructure(2).aligLen(1:size(orthologList,1),1)=1000;
-0055 blastStructure(1).bitscore(1:size(orthologList,1),1)=100;
-0056 blastStructure(2).bitscore(1:size(orthologList,1),1)=100;
-0057 blastStructure(1).ppos(1:size(orthologList,1),1)=100;
-0058 blastStructure(2).ppos(1:size(orthologList,1),1)=100;
-0059 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/external/metacyc/addSpontaneousRxns.html b/doc/external/metacyc/addSpontaneousRxns.html deleted file mode 100644 index 631689503..000000000 --- a/doc/external/metacyc/addSpontaneousRxns.html +++ /dev/null @@ -1,157 +0,0 @@ - - - - Description of addSpontaneousRxns - - - - - - - - - -
Home > external > metacyc > addSpontaneousRxns.m
- - - -

addSpontaneousRxns -

- -

PURPOSE ^

-
addSpontaneousRxns
- -

SYNOPSIS ^

-
function [spontaneousRxnList, pathwayID]=addSpontaneousRxns(rxnList, metList)
- -

DESCRIPTION ^

-
 addSpontaneousRxns
-   Retrieve spontaneous reactions based on the pathway-spontaneousRxn
-   associations curated by the MetaCyc database
-
-   Input:
-   rxnList              query list of reactions in cell array
-   metList              query list of metabolites in cell array
-
-   spontaneousRxnList   reterieved spontaneous reactions associated to
-                        the queried MetaCyc reactions and metabolites
-
-   Output:
-   pathwayID            the cell array of relevant pathways
-
- Usage: spontaneousRxnList=addSpontaneousRxns(rxnList, metList)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function [spontaneousRxnList, pathwayID]=addSpontaneousRxns(rxnList, metList)
-0002 % addSpontaneousRxns
-0003 %   Retrieve spontaneous reactions based on the pathway-spontaneousRxn
-0004 %   associations curated by the MetaCyc database
-0005 %
-0006 %   Input:
-0007 %   rxnList              query list of reactions in cell array
-0008 %   metList              query list of metabolites in cell array
-0009 %
-0010 %   spontaneousRxnList   reterieved spontaneous reactions associated to
-0011 %                        the queried MetaCyc reactions and metabolites
-0012 %
-0013 %   Output:
-0014 %   pathwayID            the cell array of relevant pathways
-0015 %
-0016 % Usage: spontaneousRxnList=addSpontaneousRxns(rxnList, metList)
-0017 
-0018 metList=convertCharArray(metList);
-0019 rxnList=convertCharArray(rxnList);
-0020 rxnList=unique(rxnList);
-0021 
-0022 % Create the matrix of MetaCyc pathways and spontaneous reactions
-0023 load('metaCycRxns.mat');
-0024 pathways={};
-0025 for i=1:numel(metaCycRxns.rxns)
-0026     if ~isempty(metaCycRxns.pwys{i})
-0027         pathways=[pathways;transpose(strsplit(metaCycRxns.pwys{i},';'))];
-0028     end
-0029 end
-0030 pathways=unique(pathways);
-0031 
-0032 % Genearte the matirx, row: spontaneousRxns, column: pathways
-0033 sprxnPwyMat=zeros(numel(isSpontaneous),numel(pathways));
-0034 for i=1:numel(isSpontaneous)
-0035     [a, b]=ismember(isSpontaneous{i},metaCycRxns.rxns);
-0036     if ~isempty(metaCycRxns.pwys{b})
-0037         [crap, indexes]=ismember(strsplit(metaCycRxns.pwys{b},';'),pathways);
-0038         sprxnPwyMat(i,indexes)=1;
-0039     end
-0040 end
-0041 
-0042 % Go through the rxnList to obtain relevant pathways
-0043 pwys={};
-0044 for i=1:numel(rxnList)
-0045     [a, b]=ismember(rxnList{i},metaCycRxns.rxns);
-0046     if a && ~isempty(metaCycRxns.pwys{b})
-0047         pwys=[pwys;transpose(strsplit(metaCycRxns.pwys{b},';'))];
-0048     end
-0049 end
-0050 pwys=unique(pwys);
-0051 
-0052 % Get spontaneous reactions associated with the pathways
-0053 hits=[];
-0054 for i=1:numel(pwys)
-0055     [a, b]=ismember(pwys{i},pathways);
-0056     if ~isempty(find(sprxnPwyMat(:,b)))
-0057         hits=[hits;find(sprxnPwyMat(:,b))];
-0058     end
-0059 end
-0060 spontaneousRxnList=isSpontaneous(unique(hits));
-0061 
-0062 % Check if the reactants/products are included in metList
-0063 for i=1:numel(spontaneousRxnList)
-0064     [a, b]=ismember(spontaneousRxnList{i},metaCycRxns.rxns);
-0065     
-0066     %Obtain the reactants and products
-0067     reactants=all(ismember(metaCycRxns.mets(find(metaCycRxns.S(:,b)==-1)),metList));
-0068     products=all(ismember(metaCycRxns.mets(find(metaCycRxns.S(:,b)==1)),metList));
-0069     
-0070     %Either reactants or products should be present for reversible reaction
-0071     if metaCycRxns.rev(b)==1
-0072         if ~(reactants || products)
-0073             spontaneousRxnList{i}=[];
-0074         end
-0075         %Reactants should be present for irreversible reactions
-0076     else
-0077         if ~reactants
-0078             spontaneousRxnList{i}=[];
-0079         end
-0080     end
-0081 end
-0082 spontaneousRxnList=spontaneousRxnList(~cellfun(@isempty, spontaneousRxnList));
-0083 
-0084 % Remove the spontaneousRxns that have already been included
-0085 spontaneousRxnList=setdiff(spontaneousRxnList,rxnList);
-0086 
-0087 % Generate the cell array of relevant pathways
-0088 pathwayID=cell(numel(spontaneousRxnList),1);
-0089 for i=1:numel(spontaneousRxnList)
-0090     index=find(strcmp(spontaneousRxnList{i},isSpontaneous));
-0091     % locate the relevant pathways
-0092     relevantpwys=intersect(pathways(find(sprxnPwyMat(index,:))),pwys);
-0093     pathwayID{i}=strjoin(relevantpwys,';');
-0094 end
-0095 
-0096 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/external/metacyc/getEnzymesFromMetaCyc.html b/doc/external/metacyc/getEnzymesFromMetaCyc.html deleted file mode 100644 index e1e221272..000000000 --- a/doc/external/metacyc/getEnzymesFromMetaCyc.html +++ /dev/null @@ -1,366 +0,0 @@ - - - - Description of getEnzymesFromMetaCyc - - - - - - - - - -
Home > external > metacyc > getEnzymesFromMetaCyc.m
- - - -

getEnzymesFromMetaCyc -

- -

PURPOSE ^

-
getEnzymesFromMetaCyc
- -

SYNOPSIS ^

-
function metaCycEnzymes=getEnzymesFromMetaCyc(metacycPath)
- -

DESCRIPTION ^

-
 getEnzymesFromMetaCyc
-    Retrieves all enzymes and reaction-enzyme association information in MetaCyc
-
-   Input:
-    metacycPath  if metaCycEnzymes.mat is not in the RAVEN\external\metacyc
-                directory, this function will attempt to build it by reading
-                info from a local dump of MetaCyc database, and metacycPath
-                is the path to the MetaCyc data files
-
-   Output:
-    model        a model structure generated from the database. The following
-                fields are filled
-                id:             'MetaCyc'
-                name:    'Automatically generated from MetaCyc database'
-                rxns:           Reaction id
-                rxnNames:       Reaction name
-                enzymes:        Enzyme id
-                enzrxns:        Enzymatic-reaction id
-                cplxs:          Enzyme complexes
-                cplxComp:       Subunit components of enzyme complexes
-                rxnEnzymeMat    A binary matrix that indicates association of a
-                                specific enzyme to the reactions it catalyze
-                version:        MetaCyc database version
-
-    If the file metaCycEnzymes.mat is in the RAVEN\external\metacyc directory
-    it will be loaded. Otherwise, it will be generated by parsing the MetaCyc
-    database files. In general, this metaCycEnzymes.mat file should be removed
-    and rebuilt when a newer version of MetaCyc is released.
-
-    Usage: model=getEnzymesFromMetaCyc(metacycPath)
-
-NOTE: This is how one entry looks in the files
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function metaCycEnzymes=getEnzymesFromMetaCyc(metacycPath)
-0002 % getEnzymesFromMetaCyc
-0003 %    Retrieves all enzymes and reaction-enzyme association information in MetaCyc
-0004 %
-0005 %   Input:
-0006 %    metacycPath  if metaCycEnzymes.mat is not in the RAVEN\external\metacyc
-0007 %                directory, this function will attempt to build it by reading
-0008 %                info from a local dump of MetaCyc database, and metacycPath
-0009 %                is the path to the MetaCyc data files
-0010 %
-0011 %   Output:
-0012 %    model        a model structure generated from the database. The following
-0013 %                fields are filled
-0014 %                id:             'MetaCyc'
-0015 %                name:    'Automatically generated from MetaCyc database'
-0016 %                rxns:           Reaction id
-0017 %                rxnNames:       Reaction name
-0018 %                enzymes:        Enzyme id
-0019 %                enzrxns:        Enzymatic-reaction id
-0020 %                cplxs:          Enzyme complexes
-0021 %                cplxComp:       Subunit components of enzyme complexes
-0022 %                rxnEnzymeMat    A binary matrix that indicates association of a
-0023 %                                specific enzyme to the reactions it catalyze
-0024 %                version:        MetaCyc database version
-0025 %
-0026 %    If the file metaCycEnzymes.mat is in the RAVEN\external\metacyc directory
-0027 %    it will be loaded. Otherwise, it will be generated by parsing the MetaCyc
-0028 %    database files. In general, this metaCycEnzymes.mat file should be removed
-0029 %    and rebuilt when a newer version of MetaCyc is released.
-0030 %
-0031 %    Usage: model=getEnzymesFromMetaCyc(metacycPath)
-0032 %
-0033 %NOTE: This is how one entry looks in the files
-0034 
-0035 %proteins.dat
-0036 % UNIQUE-ID - MONOMER-8570
-0037 % TYPES - Polypeptides
-0038 % COMMON-NAME - D-carnitine dehydrogenase subunit
-0039 % COMPONENT-OF - CPLX-5143
-0040 % MOLECULAR-WEIGHT-EXP - 23
-0041 % MOLECULAR-WEIGHT-KD - 23
-0042 % SPECIES - ORG-6256
-0043 % //
-0044 
-0045 %enzrxns.dat
-0046 % UNIQUE-ID - ENZRXN-14974
-0047 % TYPES - Enzymatic-Reactions
-0048 % COMMON-NAME - (1S,4R)-iso-dihydrocarvone monooxygenase
-0049 % BASIS-FOR-ASSIGNMENT - :MANUAL
-0050 % CITATIONS - 10769172:EV-EXP-IDA-PURIFIED-PROTEIN:3419689584:caspi
-0051 % COFACTORS - FAD
-0052 % ENZYME - MONOMER-13964
-0053 % PHYSIOLOGICALLY-RELEVANT? - T
-0054 % REACTION - RXN-9435
-0055 % REGULATED-BY - REG-12241
-0056 % REGULATED-BY - REG-12240
-0057 % TEMPERATURE-OPT - 35
-0058 
-0059 % A line that contains only '//' separates each object.
-0060 
-0061 if nargin<1
-0062     ravenPath=findRAVENroot();
-0063     metacycPath=fullfile(ravenPath,'external','metacyc');
-0064 else
-0065     metacycPath=char(metacycPath);
-0066 end
-0067 
-0068 %Check if the enzymatic proteins have been parsed before and saved. If so,
-0069 %load the model.
-0070 enzymesFile=fullfile(metacycPath,'metaCycEnzymes.mat');
-0071 metaCycProteinFile='proteins.dat';
-0072 metaCycEnzrxnsFile='enzrxns.dat';
-0073 
-0074 try
-0075     (['Importing MetaCyc enzymes and reaction-enzyme association from ' strrep(enzymesFile,'\','/') '... ']);
-0076     load(enzymesFile);
-0077     fprintf('done\n');
-0078 catch
-0079     fprintf(['Cannot locate ' strrep(enzymesFile,'\','/') '\nNow try to generate it from local MetaCyc data files...\n']);
-0080     if ~isfile(fullfile(metacycPath,metaCycProteinFile)) || ~isfile(fullfile(metacycPath,metaCycEnzrxnsFile))
-0081         EM=fprintf(['The files of enzymes or proteins cannot be located, and should be downloaded from MetaCyc.\n']);
-0082         dispEM(EM);
-0083     else
-0084         metaCycEnzymes.id='MetaCyc';
-0085         metaCycEnzymes.name='Automatically generated from MetaCyc database';
-0086         
-0087         %Reserve space for 10000 enzyme complexs
-0088         metaCycEnzymes.cplxs=cell(10000,1);
-0089         metaCycEnzymes.cplxComp=cell(10000,1);
-0090         metaCycEnzymes.enzymes=cell(50000,1);
-0091         
-0092         %Get the information of protein complexes and their components
-0093         nCplx=0;
-0094         enzymeCounter=0;
-0095         
-0096         fid = fopen(fullfile(metacycPath,metaCycProteinFile), 'r');
-0097         %Loop through the file
-0098         while 1
-0099             tline = fgetl(fid);
-0100             
-0101             %Abort at end of file
-0102             if ~ischar(tline)
-0103                 break;
-0104             end
-0105             
-0106             %Add Enzyme id
-0107             if numel(tline)>12 && strcmp(tline(1:12),'UNIQUE-ID - ')
-0108                 enzymeCounter=enzymeCounter+1;
-0109                 addMe=false;
-0110                 enzymeID=tline(13:end);
-0111                 metaCycEnzymes.enzymes{enzymeCounter}=enzymeID;
-0112             end
-0113             
-0114             %Check if enzyme complexes
-0115             if strcmp(tline(1:end),'TYPES - Protein-Complexes')
-0116                 nCplx=nCplx+1;
-0117                 nComp=0;
-0118                 
-0119                 %Reserve 100 subunits for each enzyme complex
-0120                 Comp.subunit=cell(100,1);
-0121                 metaCycEnzymes.cplxs{nCplx}=enzymeID;
-0122                 
-0123                 addMe=true;
-0124             end
-0125             
-0126             if numel(tline)>13 && strcmp(tline(1:13),'COMPONENTS - ')
-0127                 if addMe
-0128                     nComp=nComp+1;
-0129                     Comp.subunit{nComp}=tline(14:end);
-0130                 end
-0131             end
-0132             
-0133             if strcmp(tline(1:end),'//')
-0134                 if addMe
-0135                     Comp.subunit=Comp.subunit(1:nComp);
-0136                     metaCycEnzymes.cplxComp{nCplx}=Comp;
-0137                     addMe=false;
-0138                 end
-0139             end
-0140         end
-0141         %Close the file
-0142         fclose(fid);
-0143         
-0144         %If too much space was allocated, shrink the model
-0145         metaCycEnzymes.cplxs=metaCycEnzymes.cplxs(1:nCplx);
-0146         metaCycEnzymes.cplxComp=metaCycEnzymes.cplxComp(1:nCplx);
-0147         metaCycEnzymes.enzymes=metaCycEnzymes.enzymes(1:enzymeCounter);
-0148         
-0149         % Iteratively go through the components of each complex
-0150         for i=1:numel(metaCycEnzymes.cplxComp)
-0151             
-0152             %replace all complex-type components with their subunits
-0153             checkCplx=true;
-0154             while checkCplx
-0155                 x=0;
-0156                 mat=[]; %Matrix for component of protein-complexs
-0157                 for j=1:numel(metaCycEnzymes.cplxComp{i}.subunit)
-0158                     [a, b]=ismember(metaCycEnzymes.cplxComp{i}.subunit{j},metaCycEnzymes.cplxs);
-0159                     if a
-0160                         x=x+1;   %record this value j, and the cplx id b
-0161                         mat(x,:)=[j b];
-0162                     end
-0163                 end
-0164                 
-0165                 if isempty(mat)
-0166                     checkCplx=false; % No complexs found among components
-0167                 else
-0168                     %go through matrix JB
-0169                     for k=1:x
-0170                         %disp(metaCycEnzymes.cplxComp{i}.subunit{mat(k,1)});
-0171                         metaCycEnzymes.cplxComp{i}.subunit(mat(k,1))=[];
-0172                         metaCycEnzymes.cplxComp{i}.subunit=[metaCycEnzymes.cplxComp{i}.subunit; metaCycEnzymes.cplxComp{mat(k,2)}.subunit];
-0173                     end
-0174                 end
-0175                 
-0176             end
-0177             
-0178             % make sure the subunits are all included in the enzyme list
-0179             % since in one case subunit was not found in enzyme dump file
-0180             [a, b] = ismember(metaCycEnzymes.cplxComp{i}.subunit,metaCycEnzymes.enzymes);
-0181             if ~all(a)
-0182                 metaCycEnzymes.cplxComp{i}.subunit = metaCycEnzymes.enzymes(b(find(a)));
-0183             end
-0184         end
-0185         
-0186         %Preallocate space for 500000 enzymatic reactions
-0187         metaCycEnzymes.enzrxns=cell(50000,1);
-0188         metaCycEnzymes.rxns=cell(50000,1);
-0189         metaCycEnzymes.rxnNames=cell(50000,1);
-0190         metaCycEnzymes.commoname=cell(50000,1);
-0191         metaCycEnzymes.rxnEnzymeMat=sparse(50000,enzymeCounter); % row: rxn, column: enzymes
-0192         
-0193         %Load enzyme and reaction association information
-0194         fid = fopen(fullfile(metacycPath,metaCycEnzrxnsFile), 'r');
-0195         
-0196         %Keeps track of how many enzymes and reactions have been added
-0197         enzrxnCounter=0;
-0198         nRxn=0;
-0199         
-0200         %These contain the mapping between Reactions and Enzymes Loop
-0201         %through the file
-0202         while 1
-0203             tline = fgetl(fid);
-0204             
-0205             %Abort at end of file
-0206             if ~ischar(tline)
-0207                 break;
-0208             end
-0209 
-0210             % Get the version of MetaCyc database
-0211             if numel(tline)>11 && strcmp(tline(1:11),'# Version: ')
-0212                 metaCycEnzymes.version=tline(12:end);
-0213             end
-0214 
-0215             %Check if it is a new enzymatic reaction
-0216             if numel(tline)>12 && strcmp(tline(1:12),'UNIQUE-ID - ')
-0217                 enzrxnCounter=enzrxnCounter+1;
-0218                 metaCycEnzymes.enzrxns{enzrxnCounter}=tline(13:end);
-0219                 metaCycEnzymes.commoname{enzrxnCounter}='';
-0220             end
-0221             
-0222             %Add common name of enzymatic reactions
-0223             if numel(tline)>14 && strcmp(tline(1:14),'COMMON-NAME - ')
-0224                 metaCycEnzymes.commoname{enzrxnCounter}=tline(15:end);
-0225                 
-0226                 %Remove HTML symobls
-0227                 metaCycEnzymes.commoname{enzrxnCounter}=regexprep(metaCycEnzymes.commoname{enzrxnCounter},'<(\w+)>','');
-0228                 metaCycEnzymes.commoname{enzrxnCounter}=regexprep(metaCycEnzymes.commoname{enzrxnCounter},'</(\w+)>','');
-0229                 metaCycEnzymes.commoname{enzrxnCounter}=regexprep(metaCycEnzymes.commoname{enzrxnCounter},'[&;]','');
-0230             end
-0231             
-0232             % I add one cell array rxns for checking existing ones by
-0233             % ismember because I cannot manage field rxns in this function
-0234             
-0235             %Add enzyme name
-0236             if numel(tline)>9 && strcmp(tline(1:9),'ENZYME - ')
-0237                 
-0238                 %Save the index in enzymes field to nEnzyme
-0239                 [x, nEnzyme]=ismember(tline(10:end),metaCycEnzymes.enzymes);
-0240                 if ~x
-0241                     %disp(tline(10:end));
-0242                 end
-0243             end
-0244             
-0245             %Add reaction id, and rxnNames by concatenating unique common
-0246             %names
-0247             if numel(tline)>11 && strcmp(tline(1:11),'REACTION - ')
-0248                 nRxn=nRxn+1;
-0249                 rxns{nRxn}='';
-0250                 rxnID=tline(12:end);
-0251                 [c, d]=ismember(rxnID,rxns);
-0252                 if c
-0253                     nRxn=nRxn-1;
-0254                     
-0255                     %Check if this common name has been included by
-0256                     %rxnNames
-0257                     k=strfind(metaCycEnzymes.rxnNames{d},metaCycEnzymes.commoname{enzrxnCounter});
-0258                     if isempty(k)
-0259                         metaCycEnzymes.rxnNames{d}=strcat(metaCycEnzymes.rxnNames{d},';',metaCycEnzymes.commoname{enzrxnCounter});
-0260                     end
-0261                     metaCycEnzymes.rxnEnzymeMat(d,nEnzyme)=1;
-0262                 else
-0263                     metaCycEnzymes.rxns{nRxn}=rxnID;
-0264                     metaCycEnzymes.rxnNames{nRxn}=metaCycEnzymes.commoname{enzrxnCounter};
-0265                     rxns{nRxn}=rxnID;
-0266                     metaCycEnzymes.rxnEnzymeMat(nRxn,nEnzyme)=1;
-0267                 end
-0268             end
-0269             
-0270         end
-0271         
-0272         %Close the file
-0273         fclose(fid);
-0274         
-0275         %Shrink the sizes
-0276         metaCycEnzymes.enzrxns=metaCycEnzymes.enzrxns(1:enzrxnCounter);
-0277         metaCycEnzymes.commoname=metaCycEnzymes.commoname(1:enzrxnCounter);
-0278         metaCycEnzymes.rxns=metaCycEnzymes.rxns(1:nRxn);
-0279         metaCycEnzymes.rxnNames=metaCycEnzymes.rxnNames(1:nRxn);
-0280         metaCycEnzymes.rxnEnzymeMat=metaCycEnzymes.rxnEnzymeMat(1:nRxn,:);
-0281         
-0282         %Save the model structure
-0283         save(enzymesFile,'metaCycEnzymes');
-0284         fprintf(['New metaCycEnzymes.mat has been successfully updated!\n\n']);
-0285     end
-0286     
-0287 end
-0288 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/external/metacyc/getMetaCycModelForOrganism.html b/doc/external/metacyc/getMetaCycModelForOrganism.html deleted file mode 100644 index 5809a21cd..000000000 --- a/doc/external/metacyc/getMetaCycModelForOrganism.html +++ /dev/null @@ -1,350 +0,0 @@ - - - - Description of getMetaCycModelForOrganism - - - - - - - - - -
Home > external > metacyc > getMetaCycModelForOrganism.m
- - - -

getMetaCycModelForOrganism -

- -

PURPOSE ^

-
getMetaCycModelForOrganism
- -

SYNOPSIS ^

-
function [model, metacycBlastStruct] = getMetaCycModelForOrganism(organismID,fastaFile,keepTransportRxns,keepUnbalanced,keepUndetermined,minScore,minPositives,useDiamond,metacycBlastStruct)
- -

DESCRIPTION ^

-
 getMetaCycModelForOrganism
-   Reconstructs a genome-scale metabolic model based on protein homology to the
-   MetaCyc pathway database
-
-   Input:
-   organismID          the query organism's abbreviation, which is defined
-                       by user
-   fastaFile           a FASTA file that contains the protein sequences of
-                       the organism for which to reconstruct a model
-   keepTransportRxns   include transportation reactions, which often have identical
-                       reactants and products that turn to be all-zero columns in
-                       the S matrix (optional, default false)
-   keepUnbalanced      include reactions cannot be unbalanced reactions, usually
-                       because they are polymeric reactions or because of a
-                       specific difficulty in balancing class structures
-                       (optional, default false)
-   keepUndetermined    include reactions that have substrates lack chemical
-                       structures or with non-numerical coefficients (e.g. n+1)
-                       (optional, default false)
-   minScore            minimum Bit scores of BLASTp search (optional, default 100)
-   minPositives        minimum Positives values of BLASTp search (optional, default 45 %)
-   useDiamond          use DIAMOND alignment tools to perform homology search
-                       if true, otherwise the BLASTP is used (optional, default true)
-   metacycBlastStruct  provided an earlier generated metacycBlastStruct
-                       from getMetaCycModelForOrganism (optional, default empty).
-                       Useful when trying different cutoffs for minScore
-                       and minPositives without having to regenerate the
-                       blastStructure each time.
-
-   Output:
-   model               a model structure for the query organism
-   metacycBlastStruct  result from getBlast or getDiamond, before the
-                       minScore and minPositives cutoffs are applied
-
- Usage: [model, metacycBlastStruct] = getMetaCycModelForOrganism(organismID,fastaFile,...
-    keepTransportRxns,keepUnbalanced,keepUndetermined,minScore,minPositives,useDiamond,metacycBlastStruct)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function [model, metacycBlastStruct] = getMetaCycModelForOrganism(organismID,fastaFile,...
-0002     keepTransportRxns,keepUnbalanced,keepUndetermined,minScore,minPositives,useDiamond,metacycBlastStruct)
-0003 % getMetaCycModelForOrganism
-0004 %   Reconstructs a genome-scale metabolic model based on protein homology to the
-0005 %   MetaCyc pathway database
-0006 %
-0007 %   Input:
-0008 %   organismID          the query organism's abbreviation, which is defined
-0009 %                       by user
-0010 %   fastaFile           a FASTA file that contains the protein sequences of
-0011 %                       the organism for which to reconstruct a model
-0012 %   keepTransportRxns   include transportation reactions, which often have identical
-0013 %                       reactants and products that turn to be all-zero columns in
-0014 %                       the S matrix (optional, default false)
-0015 %   keepUnbalanced      include reactions cannot be unbalanced reactions, usually
-0016 %                       because they are polymeric reactions or because of a
-0017 %                       specific difficulty in balancing class structures
-0018 %                       (optional, default false)
-0019 %   keepUndetermined    include reactions that have substrates lack chemical
-0020 %                       structures or with non-numerical coefficients (e.g. n+1)
-0021 %                       (optional, default false)
-0022 %   minScore            minimum Bit scores of BLASTp search (optional, default 100)
-0023 %   minPositives        minimum Positives values of BLASTp search (optional, default 45 %)
-0024 %   useDiamond          use DIAMOND alignment tools to perform homology search
-0025 %                       if true, otherwise the BLASTP is used (optional, default true)
-0026 %   metacycBlastStruct  provided an earlier generated metacycBlastStruct
-0027 %                       from getMetaCycModelForOrganism (optional, default empty).
-0028 %                       Useful when trying different cutoffs for minScore
-0029 %                       and minPositives without having to regenerate the
-0030 %                       blastStructure each time.
-0031 %
-0032 %   Output:
-0033 %   model               a model structure for the query organism
-0034 %   metacycBlastStruct  result from getBlast or getDiamond, before the
-0035 %                       minScore and minPositives cutoffs are applied
-0036 %
-0037 % Usage: [model, metacycBlastStruct] = getMetaCycModelForOrganism(organismID,fastaFile,...
-0038 %    keepTransportRxns,keepUnbalanced,keepUndetermined,minScore,minPositives,useDiamond,metacycBlastStruct)
-0039 
-0040 organismID=char(organismID);
-0041 if nargin<2
-0042     EM='No query protein fasta file is specified';
-0043     dispEM(EM);
-0044 else
-0045     fastaFile=char(fastaFile);
-0046 end
-0047 if nargin<3
-0048     keepTransportRxns=false;
-0049 end
-0050 if nargin<4
-0051     keepUnbalanced=false;
-0052 end
-0053 if nargin<5
-0054     keepUndetermined=false;
-0055 end
-0056 if nargin<6
-0057     minScore=100;
-0058 end
-0059 if nargin<7
-0060     minPositives=45;
-0061 end
-0062 if nargin<8
-0063     useDiamond=true;
-0064 end
-0065 if nargin<9
-0066     metacycBlastStruct=[];
-0067 end
-0068 
-0069 if isempty(fastaFile)
-0070     error('*** The query FASTA filename cannot be empty! ***');
-0071 else
-0072     fprintf('\nChecking existence of query FASTA file... ');
-0073     %Check if query fasta exists
-0074     fastaFile=checkFileExistence(fastaFile,2); %Copy file to temp dir
-0075     fprintf('done\n');
-0076 end
-0077 
-0078 %First generate the full MetaCyc model
-0079 metaCycModel=getModelFromMetaCyc([],keepTransportRxns,keepUnbalanced,keepUndetermined);
-0080 fprintf('The full MetaCyc model loaded\n');
-0081 
-0082 %Create the draft model from MetaCyc super model model=metaCycModel;
-0083 model.id=organismID;
-0084 model.name='Generated by homology with MetaCyc database';
-0085 model.rxns=metaCycModel.rxns;
-0086 model.rxnNames=metaCycModel.rxnNames;
-0087 model.eccodes=metaCycModel.eccodes;
-0088 model.subSystems=metaCycModel.subSystems;
-0089 model.rxnMiriams=metaCycModel.rxnMiriams;
-0090 model.rxnReferences=metaCycModel.rxnReferences;
-0091 model.lb=metaCycModel.lb;
-0092 model.ub=metaCycModel.ub;
-0093 model.rev=metaCycModel.rev;
-0094 model.c=metaCycModel.c;
-0095 model.equations=metaCycModel.equations;
-0096 
-0097 %Get the root directory for RAVEN Toolbox.
-0098 ravenPath=findRAVENroot();
-0099 
-0100 %Generate blast strcture by either DIAMOND or BLASTP
-0101 if isempty(metacycBlastStruct)
-0102     if useDiamond
-0103         blastStruc=getDiamond(organismID,fastaFile,{'MetaCyc'},fullfile(ravenPath,'external','metacyc','protseq.fsa'));
-0104     else
-0105         blastStruc=getBlast(organismID,fastaFile,{'MetaCyc'},fullfile(ravenPath,'external','metacyc','protseq.fsa'));
-0106     end
-0107     %Only look the query
-0108     blastStructure=blastStruc(2);
-0109     metacycBlastStruct=blastStructure;
-0110 else
-0111     blastStructure=metacycBlastStruct;
-0112 end
-0113 
-0114 %Remove all blast hits that are below the cutoffs
-0115 indexes=blastStructure.bitscore>=minScore & blastStructure.ppos>=minPositives;
-0116 blastStructure.toGenes(~indexes)=[];
-0117 blastStructure.fromGenes(~indexes)=[];
-0118 blastStructure.evalue(~indexes)=[];
-0119 blastStructure.aligLen(~indexes)=[];
-0120 blastStructure.identity(~indexes)=[];
-0121 blastStructure.bitscore(~indexes)=[];
-0122 blastStructure.ppos(~indexes)=[];
-0123 fprintf('Completed searching against MetaCyc protein sequences.\n');
-0124 
-0125 % Get the qualified genes of query organism from blast structure
-0126 model.genes=cell(100000,1);
-0127 model.proteins=cell(100000,1);
-0128 model.bitscore=zeros(100000,1);
-0129 model.ppos=zeros(100000,1);
-0130 num=1;
-0131 
-0132 %Go through the strucutre and find out the hit with the best bit score
-0133 for i=1:numel(blastStructure.fromGenes)
-0134     if num==1
-0135         model.genes(num)=blastStructure.fromGenes(i);
-0136         model.proteins(num)=strrep(blastStructure.toGenes(i), 'gnl|META|', '');
-0137         model.bitscore(num)=blastStructure.bitscore(i);
-0138         model.ppos(num)=blastStructure.ppos(i);
-0139         num=num+1;
-0140         lastGene=blastStructure.fromGenes(i);
-0141     else
-0142         if ~isequal(lastGene,blastStructure.fromGenes(i))
-0143             model.genes(num)=blastStructure.fromGenes(i);
-0144             model.proteins(num)=strrep(blastStructure.toGenes(i), 'gnl|META|', '');
-0145             model.bitscore(num)=blastStructure.bitscore(i);
-0146             model.ppos(num)=blastStructure.ppos(i);
-0147             num=num+1;
-0148             lastGene=blastStructure.fromGenes(i);
-0149         else
-0150             if model.bitscore(num)<blastStructure.bitscore(i)
-0151                 model.bitscore(num)=blastStructure.bitscore(i);
-0152                 model.proteins(num)=strrep(blastStructure.toGenes(i), 'gnl|META|', '');
-0153                 model.ppos(num)=blastStructure.ppos(i);
-0154             end
-0155         end
-0156     end
-0157 end
-0158 model.genes=model.genes(1:num-1);
-0159 model.proteins=model.proteins(1:num-1);
-0160 model.bitscore=model.bitscore(1:num-1);
-0161 model.ppos=model.ppos(1:num-1);
-0162 
-0163 % Get the indexes of matched genes in the metaCycModel
-0164 % because some enzymes in the FASTA file cannot be found in the dump file
-0165 [hits, indexes]=ismember(model.proteins,metaCycModel.genes);
-0166 found = find(hits);
-0167 model.genes=model.genes(found);
-0168 
-0169 % Restructure the rxnGeneMat matrix
-0170 model.rxnGeneMat=sparse(metaCycModel.rxnGeneMat(:,indexes(found)));
-0171 
-0172 %Remove all reactions without genes
-0173 hasGenes=any(model.rxnGeneMat,2);
-0174 model=removeReactions(model,~hasGenes,true);
-0175 
-0176 %Generate grRules, only consider the or relationship here Matched enzymes
-0177 %are stored in field rxnScores,
-0178 rxnNum=numel(model.rxns);
-0179 model.rxnConfidenceScores=NaN(rxnNum,1);
-0180 model.rxnConfidenceScores(:)=2;
-0181 model.grRules=cell(rxnNum,1);
-0182 %model.rxnScores=cell(rxnNum,1);
-0183 for j=1:rxnNum
-0184     model.grRules{j}='';
-0185     I=find(model.rxnGeneMat(j,:));
-0186     for k=1:numel(I)
-0187         if isempty(model.grRules{j})
-0188             model.grRules(j)=model.genes(I(k));
-0189             %model.rxnScores(j)=model.proteins(I(k));
-0190         else
-0191             model.grRules(j)=strcat(model.grRules(j),{' or '},model.genes(I(k)));
-0192             %model.rxnScores(j)=strcat(model.rxnScores(j),{' or
-0193             %'},model.proteins(I(k)));
-0194         end
-0195     end
-0196 end
-0197 %update genes field
-0198 model.genes=model.genes(any(model.rxnGeneMat));
-0199 
-0200 %Construct the S matrix and list of metabolites
-0201 [S, mets, badRxns]=constructS(model.equations);
-0202 model.S=S;
-0203 model.mets=mets;
-0204 
-0205 %model=removeReactions(model,badRxns,true,true);
-0206 
-0207 %Then match up metabolites
-0208 metaCycMets=getMetsFromMetaCyc([]);
-0209 
-0210 %Add information about all metabolites to the model
-0211 [a, b]=ismember(model.mets,metaCycMets.mets);
-0212 a=find(a);
-0213 b=b(a);
-0214 
-0215 if ~isfield(model,'metNames')
-0216     model.metNames=cell(numel(model.mets),1);
-0217     model.metNames(:)={''};
-0218 end
-0219 model.metNames(a)=metaCycMets.metNames(b);
-0220 
-0221 if ~isfield(model,'metFormulas')
-0222     model.metFormulas=cell(numel(model.mets),1);
-0223     model.metFormulas(:)={''};
-0224 end
-0225 model.metFormulas(a)=metaCycMets.metFormulas(b);
-0226 
-0227 if ~isfield(model,'metCharges')
-0228     model.metCharges=zeros(numel(model.mets),1);
-0229 end
-0230 model.metCharges(a)=metaCycMets.metCharges(b);
-0231 
-0232 if ~isfield(model,'b')
-0233     model.b=zeros(numel(model.mets),1);
-0234 end
-0235 %model.b(a)=metaCycMets.b(b);
-0236 
-0237 if ~isfield(model,'inchis')
-0238     model.inchis=cell(numel(model.mets),1);
-0239     model.inchis(:)={''};
-0240 end
-0241 model.inchis(a)=metaCycMets.inchis(b);
-0242 
-0243 if ~isfield(model,'metMiriams')
-0244     model.metMiriams=cell(numel(model.mets),1);
-0245 end
-0246 model.metMiriams(a)=metaCycMets.metMiriams(b);
-0247 
-0248 %Put all metabolites in one compartment called 's' (for system). This is
-0249 %done just to be more compatible with the rest of the code
-0250 model.comps={'s'};
-0251 model.compNames={'System'};
-0252 model.metComps=ones(numel(model.mets),1);
-0253 
-0254 %It could also be that the metabolite names are empty for some reason In
-0255 %that case, use the ID instead
-0256 I=cellfun(@isempty,model.metNames);
-0257 model.metNames(I)=model.mets(I);
-0258 
-0259 %Remove additional fields
-0260 model=rmfield(model,{'proteins','bitscore','ppos'});
-0261 
-0262 %In the end fix grRules and rxnGeneMat
-0263 [grRules,rxnGeneMat] = standardizeGrRules(model,false); %Get detailed output
-0264 model.grRules = grRules;
-0265 model.rxnGeneMat = rxnGeneMat;
-0266 %Remove the temp fasta file
-0267 delete(fastaFile)
-0268 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/external/metacyc/getMetsFromMetaCyc.html b/doc/external/metacyc/getMetsFromMetaCyc.html deleted file mode 100644 index fa08c3b39..000000000 --- a/doc/external/metacyc/getMetsFromMetaCyc.html +++ /dev/null @@ -1,362 +0,0 @@ - - - - Description of getMetsFromMetaCyc - - - - - - - - - -
Home > external > metacyc > getMetsFromMetaCyc.m
- - - -

getMetsFromMetaCyc -

- -

PURPOSE ^

-
getMetsFromMetaCyc
- -

SYNOPSIS ^

-
function metaCycMets=getMetsFromMetaCyc(metacycPath)
- -

DESCRIPTION ^

-
 getMetsFromMetaCyc
-   Retrieves information of all metabolites in MetaCyc database
-
-   Input:
-   metacycPath  if metacycMets.mat is not in the RAVEN\external\metacyc directory,
-                this function will attempt to build it by reading info from
-                a local dump of MetaCyc database, and metacycPath is the path
-                to the MetaCyc data files
-
-   Output:
-   model        a model structure generated from the database. The following
-                fields are filled
-                id:             'MetaCyc'
-                name:    'Automatically generated from MetaCyc database'
-                mets:           MetaCyc compound ids
-                metNames:       Compound name. Reuse compound id here if
-                                there is no name provided
-                metFormulas:    The chemical composition of the metabolite.
-                inchis:         InChI string for the metabolite
-                metCharges:     Compound charge state
-                metMiriams:     If there is a CHEBI id available, then that
-                                will be saved here
-                keggid:         The corresponding KEGG compound id if available
-                version:        MetaCyc database version
-
-   If the file metaCycMets.mat is in the RAVEN\external\metacyc directory
-   it will be directly loaded. Otherwise, it will be generated by parsing
-   the MetaCyc database files. In general, this metaCycMets.mat file should
-   be removed and rebuilt when a newer version of MetaCyc is released.
-               
- Usage: model=getMetsFromMetaCyc(metacycPath)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function metaCycMets=getMetsFromMetaCyc(metacycPath)
-0002 % getMetsFromMetaCyc
-0003 %   Retrieves information of all metabolites in MetaCyc database
-0004 %
-0005 %   Input:
-0006 %   metacycPath  if metacycMets.mat is not in the RAVEN\external\metacyc directory,
-0007 %                this function will attempt to build it by reading info from
-0008 %                a local dump of MetaCyc database, and metacycPath is the path
-0009 %                to the MetaCyc data files
-0010 %
-0011 %   Output:
-0012 %   model        a model structure generated from the database. The following
-0013 %                fields are filled
-0014 %                id:             'MetaCyc'
-0015 %                name:    'Automatically generated from MetaCyc database'
-0016 %                mets:           MetaCyc compound ids
-0017 %                metNames:       Compound name. Reuse compound id here if
-0018 %                                there is no name provided
-0019 %                metFormulas:    The chemical composition of the metabolite.
-0020 %                inchis:         InChI string for the metabolite
-0021 %                metCharges:     Compound charge state
-0022 %                metMiriams:     If there is a CHEBI id available, then that
-0023 %                                will be saved here
-0024 %                keggid:         The corresponding KEGG compound id if available
-0025 %                version:        MetaCyc database version
-0026 %
-0027 %   If the file metaCycMets.mat is in the RAVEN\external\metacyc directory
-0028 %   it will be directly loaded. Otherwise, it will be generated by parsing
-0029 %   the MetaCyc database files. In general, this metaCycMets.mat file should
-0030 %   be removed and rebuilt when a newer version of MetaCyc is released.
-0031 %
-0032 % Usage: model=getMetsFromMetaCyc(metacycPath)
-0033 
-0034 % NOTE: This is how one entry looks in the file
-0035 
-0036 % //
-0037 % UNIQUE-ID - CPD-18846
-0038 % TYPES - CPD-18866
-0039 % COMMON-NAME - 12-ethyl-8-propyl-bacteriochlorophyllide <i>d</i>
-0040 % ATOM-CHARGES - (43 -1)
-0041 % ATOM-CHARGES - (12 -1)
-0042 % CHEMICAL-FORMULA - (C 35)
-0043 % CHEMICAL-FORMULA - (H 36)
-0044 % CHEMICAL-FORMULA - (N 4)
-0045 % CHEMICAL-FORMULA - (O 4)
-0046 % CHEMICAL-FORMULA - (MG 1)
-0047 % CITATIONS - 26331578
-0048 % CITATIONS - 2350541
-0049 % CREDITS - SRI
-0050 % CREDITS - caspi
-0051 % MOLECULAR-WEIGHT - 600.999
-0052 % MONOISOTOPIC-MW - 602.274347629
-0053 % NON-STANDARD-INCHI - InChI=1S/C35H39N4O4.Mg/c1-7-9-21-16(3)24-14-29-32(19(6)40)18(5)26(37-29)13-25-17(4)22(10-11-31(42)43)34(38-25)23-12-30(41)33-20(8-2)27(39-35(23)33)15-28(21)36-24;/h12-15,17,19,22,40H,7-11H2,1-6H3,(H3,36,37,38,39,41,42,43);/q-1;+2/p-3/t17-,19?,22-;/m0./s1
-0054 % SMILES - CCCC5(=C(C)C9(N6([Mg]27(N1(C(C(C)C(CCC(=O)[O-])C=1C4([C-]C(=O)C3(=C(CC)C(N2C3=4)=CC5=6)))=CC8(=C(C)C(C(O)C)=C(N78)C=9))))))
-0055 
-0056 % A line that contains only '//' separates each object.
-0057 
-0058 % Check if the metabolites have been parsed before and saved. If so, load
-0059 % the model.
-0060 if nargin<1
-0061     ravenPath=findRAVENroot();
-0062     metacycPath=fullfile(ravenPath,'external','metacyc');
-0063 else
-0064     metacycPath=char(metacycPath);
-0065 end
-0066 
-0067 metsFile=fullfile(metacycPath,'metaCycMets.mat');
-0068 metaCycMetFile='compounds.dat';
-0069 
-0070 if exist(metsFile, 'file')
-0071     fprintf(['Importing MetaCyc metabolites from ' strrep(metsFile,'\','/') '... ']);
-0072     load(metsFile);
-0073     fprintf('done\n');
-0074 else
-0075     fprintf(['Cannot locate ' strrep(metsFile,'\','/') '\nNow try to generate it from local MetaCyc data files...\n']);
-0076     if ~isfile(fullfile(metacycPath,metaCycMetFile))
-0077         EM=fprintf(['The file of metabolites cannot be located, and should be downloaded from MetaCyc.\n']);
-0078         dispEM(EM);
-0079     else
-0080         %Add new functionality in the order specified in models
-0081         metaCycMets.id='MetaCyc';
-0082         metaCycMets.name='Automatically generated from MetaCyc database';
-0083         
-0084         %Preallocate memory for 50000 metabolites
-0085         metaCycMets.mets=cell(50000,1);
-0086         metaCycMets.metNames=cell(50000,1);
-0087         metaCycMets.metFormulas=cell(50000,1);
-0088         metaCycMets.inchis=cell(50000,1);
-0089         metaCycMets.metCharges=zeros(50000,1);
-0090         metaCycMets.metMiriams=cell(50000,1);
-0091         metaCycMets.keggid=cell(50000,1);
-0092         
-0093         %First load information on metabolite ID, name, formula, and others
-0094         fid = fopen(fullfile(metacycPath,metaCycMetFile), 'r');
-0095         
-0096         %Keeps track of how many metabolites that have been added
-0097         metCounter=0;
-0098         
-0099         %Loop through the file
-0100         while 1
-0101             %Get the next line
-0102             tline = fgetl(fid);
-0103             %disp(tline);
-0104             
-0105             % Abort at end of file
-0106             if ~ischar(tline)
-0107                 break;
-0108             end
-0109             
-0110             % Get the version of MetaCyc database
-0111             if numel(tline)>11 && strcmp(tline(1:11),'# Version: ')
-0112                 metaCycMets.version=tline(12:end);
-0113             end
-0114 
-0115             %Check if it is a new entry
-0116             if numel(tline)>12 && strcmp(tline(1:12),'UNIQUE-ID - ')
-0117                 metCounter=metCounter+1;
-0118                 
-0119                 %Add empty strings as initial values
-0120                 metaCycMets.metNames{metCounter}='';
-0121                 metaCycMets.metFormulas{metCounter}='';
-0122                 metaCycMets.inchis{metCounter}='';
-0123                 %metaCycMets.smiles{metCounter}='';
-0124                 %metaCycMets.pubchem{metCounter}='';
-0125                 metaCycMets.keggid{metCounter}='';
-0126                 nonStandardInchis = '';
-0127                 
-0128                 %Add compound ID
-0129                 metaCycMets.mets{metCounter}=tline(13:end);
-0130             end
-0131             
-0132             
-0133             %Add name
-0134             if numel(tline)>14 &&    strcmp(tline(1:14),'COMMON-NAME - ')
-0135                 metaCycMets.metNames{metCounter}=tline(15:end);
-0136                 
-0137                 %Romve HTML symbols
-0138                 metaCycMets.metNames{metCounter}=regexprep(metaCycMets.metNames{metCounter},'<(\w+)>','');
-0139                 metaCycMets.metNames{metCounter}=regexprep(metaCycMets.metNames{metCounter},'</(\w+)>','');
-0140                 metaCycMets.metNames{metCounter}=regexprep(metaCycMets.metNames{metCounter},'[&;]','');
-0141             end
-0142             
-0143             %Add charge
-0144             if numel(tline)>16 &&    strcmp(tline(1:16),'ATOM-CHARGES - (')
-0145                 atomCharge=tline(17:end-1);
-0146                 
-0147                 s=strfind(atomCharge,' ');
-0148                 if any(s)
-0149                     atomCharge=atomCharge(s+1:end);
-0150                     metaCycMets.metCharges(metCounter,1)=metaCycMets.metCharges(metCounter,1)+str2num(atomCharge);
-0151                 end
-0152             end
-0153             
-0154             %Add inchis
-0155             if numel(tline)>14 && strcmp(tline(1:14),'INCHI - InChI=')
-0156                 metaCycMets.inchis{metCounter}=tline(15:end);
-0157             end
-0158             
-0159             %Add non-standard inchis
-0160             if numel(tline)>27 && strcmp(tline(1:27),'NON-STANDARD-INCHI - InChI=')
-0161                 nonStandardInchis=tline(28:end);
-0162             end
-0163             
-0164             %Add SMILES
-0165             if numel(tline)>9 && strcmp(tline(1:9),'SMILES - ')
-0166                 
-0167                 if isstruct(metaCycMets.metMiriams{metCounter})
-0168                     addToIndex=numel(metaCycMets.metMiriams{metCounter}.name)+1;
-0169                 else
-0170                     addToIndex=1;
-0171                 end
-0172                 tempStruct=metaCycMets.metMiriams{metCounter};
-0173                 tempStruct.name{addToIndex,1}='SMILES';
-0174                 tempStruct.value{addToIndex,1}=tline(10:end);
-0175                 metaCycMets.metMiriams{metCounter}=tempStruct;
-0176             end
-0177             
-0178             %Add formula
-0179             if numel(tline)>20 && strcmp(tline(1:20),'CHEMICAL-FORMULA - (')
-0180                 metaCycMets.metFormulas{metCounter}=strcat(metaCycMets.metFormulas{metCounter},tline(21:end-1));
-0181                 metaCycMets.metFormulas{metCounter}(isspace(metaCycMets.metFormulas{metCounter})) = [];
-0182             end
-0183             
-0184             %Add KEGG id
-0185             if numel(tline)>23 && strcmp(tline(1:23),'DBLINKS - (LIGAND-CPD "')
-0186                 keggid=tline(24:end);
-0187                 
-0188                 s=strfind(keggid,'"');
-0189                 if any(s)
-0190                     keggid=keggid(1:s-1);
-0191                 end
-0192                 
-0193                 metaCycMets.keggid{metCounter}=keggid;
-0194             end
-0195             
-0196             %Add CHEBI id
-0197             if numel(tline)>18 && strcmp(tline(1:18),'DBLINKS - (CHEBI "')
-0198                 chebiID=tline(20:end); %This is because there is sometimes more than one CHEBI index
-0199                 
-0200                 s=strfind(chebiID,'"');
-0201                 if any(s)
-0202                     chebiID=chebiID(1:s-1);
-0203                 end
-0204                 
-0205                 if isstruct(metaCycMets.metMiriams{metCounter})
-0206                     addToIndex=numel(metaCycMets.metMiriams{metCounter}.name)+1;
-0207                 else
-0208                     addToIndex=1;
-0209                 end
-0210                 tempStruct=metaCycMets.metMiriams{metCounter};
-0211                 tempStruct.name{addToIndex,1}='chebi';
-0212                 tempStruct.value{addToIndex,1}=strcat('CHEBI:',chebiID);
-0213                 metaCycMets.metMiriams{metCounter}=tempStruct;
-0214             end
-0215             
-0216             %Add PubChem
-0217             if numel(tline)>20 && strcmp(tline(1:20),'DBLINKS - (PUBCHEM "')
-0218                 pubchemID=tline(21:end);
-0219                 
-0220                 s=strfind(pubchemID,'"');
-0221                 if any(s)
-0222                     pubchemID=pubchemID(1:s-1);
-0223                 end
-0224                 
-0225                 if isstruct(metaCycMets.metMiriams{metCounter})
-0226                     addToIndex=numel(metaCycMets.metMiriams{metCounter}.name)+1;
-0227                 else
-0228                     addToIndex=1;
-0229                 end
-0230                 tempStruct=metaCycMets.metMiriams{metCounter};
-0231                 tempStruct.name{addToIndex,1}='pubchem.compound';
-0232                 tempStruct.value{addToIndex,1}=pubchemID;
-0233                 metaCycMets.metMiriams{metCounter}=tempStruct;
-0234             end
-0235             
-0236             %Add non-standard inchis when standard one is unavailable
-0237             if strcmp(tline,'//') && strcmp(metaCycMets.inchis{metCounter},'')
-0238                 metaCycMets.inchis{metCounter}=nonStandardInchis;
-0239                 nonStandardInchis = '';
-0240                 
-0241                 %Refine formula from inchis
-0242                 s=strfind(metaCycMets.inchis{metCounter},'/');
-0243                 if any(s)
-0244                     inchiFormula=metaCycMets.inchis{metCounter}(s(1)+1:s(2)-1);
-0245                     
-0246                     %And remove dot characters
-0247                     inchiFormula(regexp(inchiFormula,'[.]'))=[];
-0248                     if ~strcmp(metaCycMets.metFormulas{metCounter},inchiFormula)
-0249                         metaCycMets.metFormulas{metCounter}=inchiFormula;
-0250                     end
-0251                 end
-0252                 
-0253             end
-0254             
-0255         end
-0256         
-0257         %Close the file
-0258         fclose(fid);
-0259         
-0260         %If too much space was allocated, shrink the model
-0261         metaCycMets.mets=metaCycMets.mets(1:metCounter);
-0262         metaCycMets.metNames=metaCycMets.metNames(1:metCounter);
-0263         metaCycMets.metFormulas=metaCycMets.metFormulas(1:metCounter);
-0264         metaCycMets.metMiriams=metaCycMets.metMiriams(1:metCounter);
-0265         metaCycMets.inchis=metaCycMets.inchis(1:metCounter);
-0266         metaCycMets.metCharges=metaCycMets.metCharges(1:metCounter,:);
-0267         %metaCycMets.smiles=metaCycMets.smiles(1:metCounter);
-0268         %metaCycMets.pubchem=metaCycMets.pubchem(1:metCounter);
-0269         metaCycMets.keggid=metaCycMets.keggid(1:metCounter);
-0270         
-0271         %If the metMiriams structure is empty, use MetaCyc id as metMiriams
-0272         for i=1:numel(metaCycMets.mets)
-0273             if ~isstruct(metaCycMets.metMiriams{i})
-0274                 miriamStruct.name{1}='metacyc.compound';
-0275                 miriamStruct.value{1}=metaCycMets.mets{i};
-0276                 metaCycMets.metMiriams{i}=miriamStruct;
-0277             end
-0278         end
-0279         
-0280         %Saves the model
-0281         save(metsFile,'metaCycMets');
-0282         fprintf(['New metaCycMets.mat has been successfully updated!\n\n']);
-0283     end
-0284 end
-0285 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/external/metacyc/getModelFromMetaCyc.html b/doc/external/metacyc/getModelFromMetaCyc.html deleted file mode 100644 index 4e38fde03..000000000 --- a/doc/external/metacyc/getModelFromMetaCyc.html +++ /dev/null @@ -1,261 +0,0 @@ - - - - Description of getModelFromMetaCyc - - - - - - - - - -
Home > external > metacyc > getModelFromMetaCyc.m
- - - -

getModelFromMetaCyc -

- -

PURPOSE ^

-
getModelFromMetaCyc
- -

SYNOPSIS ^

-
function metaCycModel=getModelFromMetaCyc(metacycPath,keepTransportRxns,keepUnbalanced,keepUndetermined)
- -

DESCRIPTION ^

-
 getModelFromMetaCyc
-   Retrieves information stored in MetaCyc flat files and generates a super model
-
-   Input:
-   metacycPath         By setting this parameter as empty (default ''), a 
-                       super model of MetaCyc can be directly generated from
-                       the Matlab files (metaCycRxns, metaCycMets and metaCycEnzymes)
-                       that are in the RAVEN\external\metacyc directory.
-                       Alternatively, this function attempts to re-generate
-                       the Matlab files from a local dump of MetaCyc data files
-                       (e.g. reactions.dat, proteins.dat, compounds.dat),
-                       to which the path should be defined by this parameter
-   keepTransportRxns   include transportation reactions, which often have identical
-                       reactants and products that turn to be all-zero columns in
-                       the S matrix (optional, default false)
-   keepUnbalanced      include reactions cannot be unbalanced reactions, usually
-                       because they are polymeric reactions or because of a
-                       specific difficulty in balancing class structures
-                       (optional, default false)
-   keepUndetermined    include reactions that have substrates lack chemical
-                       structures or with non-numerical coefficients (e.g. n+1)
-                       (optional, default false)
-
-   Output:
-   metaCycModel        a model structure generated from MetaCyc database
-                       including all reactions, metabolites and enzymes
-                       in MetaCyc
-
-   NOTE: This function allows users to update the MetaCyc Matlab files from
-   a local dump of data files, which can be obtained through subscribing to
-   the database (https://metacyc.org/download.shtml).
-
- Usage: getModelFromMetaCyc(metacycPath,keepTransportRxns,keepUnbalanced,keepUndetermined)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function metaCycModel=getModelFromMetaCyc(metacycPath,keepTransportRxns,keepUnbalanced,keepUndetermined)
-0002 % getModelFromMetaCyc
-0003 %   Retrieves information stored in MetaCyc flat files and generates a super model
-0004 %
-0005 %   Input:
-0006 %   metacycPath         By setting this parameter as empty (default ''), a
-0007 %                       super model of MetaCyc can be directly generated from
-0008 %                       the Matlab files (metaCycRxns, metaCycMets and metaCycEnzymes)
-0009 %                       that are in the RAVEN\external\metacyc directory.
-0010 %                       Alternatively, this function attempts to re-generate
-0011 %                       the Matlab files from a local dump of MetaCyc data files
-0012 %                       (e.g. reactions.dat, proteins.dat, compounds.dat),
-0013 %                       to which the path should be defined by this parameter
-0014 %   keepTransportRxns   include transportation reactions, which often have identical
-0015 %                       reactants and products that turn to be all-zero columns in
-0016 %                       the S matrix (optional, default false)
-0017 %   keepUnbalanced      include reactions cannot be unbalanced reactions, usually
-0018 %                       because they are polymeric reactions or because of a
-0019 %                       specific difficulty in balancing class structures
-0020 %                       (optional, default false)
-0021 %   keepUndetermined    include reactions that have substrates lack chemical
-0022 %                       structures or with non-numerical coefficients (e.g. n+1)
-0023 %                       (optional, default false)
-0024 %
-0025 %   Output:
-0026 %   metaCycModel        a model structure generated from MetaCyc database
-0027 %                       including all reactions, metabolites and enzymes
-0028 %                       in MetaCyc
-0029 %
-0030 %   NOTE: This function allows users to update the MetaCyc Matlab files from
-0031 %   a local dump of data files, which can be obtained through subscribing to
-0032 %   the database (https://metacyc.org/download.shtml).
-0033 %
-0034 % Usage: getModelFromMetaCyc(metacycPath,keepTransportRxns,keepUnbalanced,keepUndetermined)
-0035 
-0036 if nargin<1
-0037     ravenPath=findRAVENroot();
-0038     metacycPath=fullfile(ravenPath,'external','metacyc');
-0039 else
-0040     metacycPath=char(metacycPath);
-0041 end
-0042 if nargin<2
-0043     keepTransportRxns=false;
-0044 end
-0045 if nargin<3
-0046     keepUnbalanced=false;
-0047 end
-0048 if nargin<4
-0049     keepUndetermined=false;
-0050 end
-0051 
-0052 %First get all reactions
-0053 metaCycModel=getRxnsFromMetaCyc(metacycPath,keepTransportRxns,keepUnbalanced,keepUndetermined);
-0054 
-0055 %Get reaction and enzyme association
-0056 metaCycEnzymes=getEnzymesFromMetaCyc(metacycPath);
-0057 
-0058 %Replace rxnNames with those from metaCycEnzymes
-0059 [a, b]=ismember(metaCycModel.rxns,metaCycEnzymes.rxns);
-0060 a=find(a);
-0061 b=b(a);
-0062 metaCycModel.rxnNames(a)=metaCycEnzymes.rxnNames(b);
-0063 
-0064 fprintf('Reorganizing reaction-enzyme associations... ')
-0065 %Create the rxnGeneMat for the reactions, by geting all enzymes and
-0066 %corresponding subunits
-0067 rxnNum=numel(metaCycModel.rxns);
-0068 metaCycModel.genes=metaCycEnzymes.enzymes;
-0069 metaCycModel.rxnGeneMat=sparse(rxnNum,numel(metaCycEnzymes.enzymes));
-0070 metaCycModel.grRules=cell(rxnNum,1);
-0071 
-0072 %Loop through all reactions to generate rxnGeneMat matrix and grRules This
-0073 %step also cross-link reactions to their catalyzing enzymes
-0074 for i=1:rxnNum
-0075     
-0076     metaCycModel.grRules{i}='';
-0077     %Find out if this is an enzymatic reaction
-0078     [a, b]=ismember(metaCycModel.rxns(i),metaCycEnzymes.rxns);
-0079     if a
-0080         I=[];   %Find out all catalyzing enzymes, which are treated as isoenzymes
-0081         I=find(metaCycEnzymes.rxnEnzymeMat(b,:));
-0082         if ~isempty(I)
-0083             
-0084             grRule='';
-0085             for j=1:numel(I)
-0086                 
-0087                 subgrRule=''; %Find out if enzyme complex
-0088                 [c, d]=ismember(metaCycEnzymes.enzymes(I(j)),metaCycEnzymes.cplxs);
-0089                 if c   %In cases of an enzyme complex
-0090                     %With single subunit
-0091                     if numel(metaCycEnzymes.cplxComp{d}.subunit)==1
-0092                         subgrRule=metaCycEnzymes.cplxComp{d}.subunit{1};
-0093                         %With multiple subunits
-0094                     else
-0095                         subgrRule=strjoin(metaCycEnzymes.cplxComp{d}.subunit,' and ');
-0096                         subgrRule=strcat('(',subgrRule,')');
-0097                     end
-0098                     [x, geneIndex]=ismember(metaCycEnzymes.cplxComp{d}.subunit,metaCycModel.genes);
-0099                     metaCycModel.rxnGeneMat(i,geneIndex)=1;
-0100                     
-0101                 else  %In cases of NOT an enzyme complex
-0102                     subgrRule=metaCycEnzymes.enzymes(I(j));
-0103                     metaCycModel.rxnGeneMat(i,I(j))=1;
-0104                 end
-0105                 
-0106                 %Generating grRules
-0107                 if ~strcmp(subgrRule,'')
-0108                     if ~strcmp(grRule,'')
-0109                         grRule=strcat(grRule,{' or '},subgrRule);
-0110                     else
-0111                         grRule=subgrRule;
-0112                     end
-0113                 end
-0114                 
-0115             end
-0116             if iscell(grRule)
-0117                 metaCycModel.grRules{i}=grRule{1};
-0118             else
-0119                 metaCycModel.grRules{i}=grRule;
-0120             end
-0121             
-0122         end
-0123         
-0124     end
-0125 end
-0126 fprintf('done\n')
-0127 %Then get all metabolites
-0128 metaCycMets=getMetsFromMetaCyc(metacycPath);
-0129 
-0130 %Add information about all metabolites to the model
-0131 [a, b]=ismember(metaCycModel.mets,metaCycMets.mets);
-0132 a=find(a);
-0133 b=b(a);
-0134 
-0135 if ~isfield(metaCycModel,'metNames')
-0136     metaCycModel.metNames=cell(numel(metaCycModel.mets),1);
-0137     metaCycModel.metNames(:)={''};
-0138 end
-0139 metaCycModel.metNames(a)=metaCycMets.metNames(b);
-0140 
-0141 if ~isfield(metaCycModel,'metFormulas')
-0142     metaCycModel.metFormulas=cell(numel(metaCycModel.mets),1);
-0143     metaCycModel.metFormulas(:)={''};
-0144 end
-0145 metaCycModel.metFormulas(a)=metaCycMets.metFormulas(b);
-0146 
-0147 if ~isfield(metaCycModel,'metCharges')
-0148     metaCycModel.metCharges=zeros(numel(metaCycModel.mets),1);
-0149 end
-0150 metaCycModel.metCharges(a)=metaCycMets.metCharges(b);
-0151 
-0152 if ~isfield(metaCycModel,'inchis')
-0153     metaCycModel.inchis=cell(numel(metaCycModel.mets),1);
-0154     metaCycModel.inchis(:)={''};
-0155 end
-0156 metaCycModel.inchis(a)=metaCycMets.inchis(b);
-0157 
-0158 if ~isfield(metaCycModel,'metMiriams')
-0159     metaCycModel.metMiriams=cell(numel(metaCycModel.mets),1);
-0160 end
-0161 metaCycModel.metMiriams(a)=metaCycMets.metMiriams(b);
-0162 
-0163 if ~isfield(metaCycModel,'keggid')
-0164     metaCycModel.keggid=cell(numel(metaCycModel.mets),1);
-0165 end
-0166 metaCycModel.keggid(a)=metaCycMets.keggid(b);
-0167 
-0168 %Put all metabolites in one compartment called 's' (for system). This is
-0169 %done just to be more compatible with the rest of the code
-0170 metaCycModel.comps={'s'};
-0171 metaCycModel.compNames={'System'};
-0172 metaCycModel.metComps=ones(numel(metaCycModel.mets),1);
-0173 
-0174 
-0175 %It could also be that the metabolite and reaction names are empty for some
-0176 %reasons. In that case, use the ID instead
-0177 I=cellfun(@isempty,metaCycModel.metNames);
-0178 metaCycModel.metNames(I)=metaCycModel.mets(I);
-0179 I=cellfun(@isempty,metaCycModel.rxnNames);
-0180 metaCycModel.rxnNames(I)=metaCycModel.rxns(I);
-0181 
-0182 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/external/metacyc/getRxnsFromMetaCyc.html b/doc/external/metacyc/getRxnsFromMetaCyc.html deleted file mode 100644 index f3b265898..000000000 --- a/doc/external/metacyc/getRxnsFromMetaCyc.html +++ /dev/null @@ -1,629 +0,0 @@ - - - - Description of getRxnsFromMetaCyc - - - - - - - - - -
Home > external > metacyc > getRxnsFromMetaCyc.m
- - - -

getRxnsFromMetaCyc -

- -

PURPOSE ^

-
getRxnsFromMetaCyc
- -

SYNOPSIS ^

-
function model=getRxnsFromMetaCyc(metacycPath,keepTransportRxns,keepUnbalanced,keepUndetermined)
- -

DESCRIPTION ^

-
 getRxnsFromMetaCyc
-   Retrieves reactions information from MetaCyc database
-
-   Input:
-   metacycPath         if metaCycRxns.mat is not in the RAVEN\external\metacyc
-                       directory, this function will attempt to build it by
-                       reading info from a local dump of MetaCyc database,
-                       metacycPath is the path to the MetaCyc data files
-   keepTransportRxns   include transportation reactions, which often have identical
-                       reactants and products that turn to be all-zero columns in
-                       the S matrix (optional, default false)
-   keepUnbalanced      include reactions cannot be balanced, usually
-                       because they are polymeric reactions or with
-                       specific difficulty in balancing class structures
-                       (optional, default false)
-   keepUndetermined    include reactions that have substrates lack chemical
-                       structures or with non-numerical coefficients (e.g. n+1)
-                       (optional, default false)
-
-   Output:
-   model     a model structure generated from the database. The following
-             fields are filled
-             id:             'MetaCyc'
-             name:    'Automatically generated from MetaCyc database'
-             rxns:           MetaCyc reaction ids
-             rxnNames:       Name for each reaction entry
-             mets:           MetaCyc compound ids. If the equations use
-                             stoichiometry such as ID(n+1) then the whole
-                             expression is saved as the id
-             pwys:           MetaCyc pathway id
-             eccodes:        Corresponding ec-number if available
-             rxnMiriams:     Contains reaction specific information such as
-                             associated RHEA and KEGG reaction ids
-             S:              Stoichiometric matrix
-             lb:             -1000 for all reactions
-             ub:             1000 for all reactions
-             rev:            1 for reversible and 0 for irreversible. For
-                             reactions present in pathway maps the reversibility
-                             is taken from there
-             b:              0 for all metabolites
-             version:        MetaCyc database version
-
-   If the file metaCycRxns.mat is in the RAVEN/external/metacyc directory, it
-   will be directly loaded instead of parsing the MetaCyc data files and
-   pre-prepared lists of MetaCyc transport and undetermined reactions.
-
- Usage: model=getRxnsFromMetaCyc(metacycPath,keepTransportRxns,keepUnbalanced,keepUndetermined)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 function model=getRxnsFromMetaCyc(metacycPath,keepTransportRxns,keepUnbalanced,keepUndetermined)
-0002 % getRxnsFromMetaCyc
-0003 %   Retrieves reactions information from MetaCyc database
-0004 %
-0005 %   Input:
-0006 %   metacycPath         if metaCycRxns.mat is not in the RAVEN\external\metacyc
-0007 %                       directory, this function will attempt to build it by
-0008 %                       reading info from a local dump of MetaCyc database,
-0009 %                       metacycPath is the path to the MetaCyc data files
-0010 %   keepTransportRxns   include transportation reactions, which often have identical
-0011 %                       reactants and products that turn to be all-zero columns in
-0012 %                       the S matrix (optional, default false)
-0013 %   keepUnbalanced      include reactions cannot be balanced, usually
-0014 %                       because they are polymeric reactions or with
-0015 %                       specific difficulty in balancing class structures
-0016 %                       (optional, default false)
-0017 %   keepUndetermined    include reactions that have substrates lack chemical
-0018 %                       structures or with non-numerical coefficients (e.g. n+1)
-0019 %                       (optional, default false)
-0020 %
-0021 %   Output:
-0022 %   model     a model structure generated from the database. The following
-0023 %             fields are filled
-0024 %             id:             'MetaCyc'
-0025 %             name:    'Automatically generated from MetaCyc database'
-0026 %             rxns:           MetaCyc reaction ids
-0027 %             rxnNames:       Name for each reaction entry
-0028 %             mets:           MetaCyc compound ids. If the equations use
-0029 %                             stoichiometry such as ID(n+1) then the whole
-0030 %                             expression is saved as the id
-0031 %             pwys:           MetaCyc pathway id
-0032 %             eccodes:        Corresponding ec-number if available
-0033 %             rxnMiriams:     Contains reaction specific information such as
-0034 %                             associated RHEA and KEGG reaction ids
-0035 %             S:              Stoichiometric matrix
-0036 %             lb:             -1000 for all reactions
-0037 %             ub:             1000 for all reactions
-0038 %             rev:            1 for reversible and 0 for irreversible. For
-0039 %                             reactions present in pathway maps the reversibility
-0040 %                             is taken from there
-0041 %             b:              0 for all metabolites
-0042 %             version:        MetaCyc database version
-0043 %
-0044 %   If the file metaCycRxns.mat is in the RAVEN/external/metacyc directory, it
-0045 %   will be directly loaded instead of parsing the MetaCyc data files and
-0046 %   pre-prepared lists of MetaCyc transport and undetermined reactions.
-0047 %
-0048 % Usage: model=getRxnsFromMetaCyc(metacycPath,keepTransportRxns,keepUnbalanced,keepUndetermined)
-0049 
-0050 %NOTE: This is how one entry looks in the file
-0051 
-0052 % UNIQUE-ID - 4-HYDROXY-2-KETOPIMELATE-LYSIS-RXN
-0053 % TYPES - Small-Molecule-Reactions
-0054 % TYPES - Chemical-Reactions
-0055 % ATOM-MAPPINGS - (:NO-HYDROGEN-ENCODING (6 7 0 8 1 9 2 10 3 12 11 5 4) (((PYRUVATE 0 5) (SUCC-S-ALD 6 12)) ((CPD-804 0 12))))
-0056 % DBLINKS - (LIGAND-RXN "R01647" NIL |kr| 3650824949 NIL NIL)
-0057 % DBLINKS - (LIGAND-RXN "R01645" NIL |taltman| 3459474590 NIL NIL)
-0058 % EC-NUMBER - EC-4.1.2.52
-0059 % ^OFFICIAL? - T
-0060 % ENZYMATIC-REACTION - ENZRXN-3009
-0061 % IN-PATHWAY - 3-HYDROXYPHENYLACETATE-DEGRADATION-PWY
-0062 % LEFT - CPD-804
-0063 % ORPHAN? - :NO
-0064 % PHYSIOLOGICALLY-RELEVANT? - T
-0065 % REACTION-DIRECTION - LEFT-TO-RIGHT
-0066 % RIGHT - SUCC-S-ALD
-0067 % RIGHT - PYRUVATE
-0068 % //
-0069 
-0070 % A line that contains only '//' separates each object.
-0071 if nargin<1
-0072     ravenPath=findRAVENroot();
-0073     metacycPath=fullfile(ravenPath,'external','metacyc');
-0074 else
-0075     metacycPath=char(metacycPath);
-0076 end
-0077 if nargin<2
-0078     keepTransportRxns=false;
-0079 end
-0080 if nargin<3
-0081     keepUnbalanced=false;
-0082 end
-0083 if nargin<4
-0084     keepUndetermined=false;
-0085 end
-0086 
-0087 %Check if the reactions have been parsed before and saved. Directly load
-0088 %the model if so.
-0089 rxnsFile=fullfile(metacycPath,'metaCycRxns.mat');
-0090 metaCycRxnFile='reactions.dat';
-0091 metaCycPwyFile='pathway-links.dat';
-0092 
-0093 if exist(rxnsFile, 'file')
-0094     fprintf(['Importing MetaCyc reactions from ' strrep(rxnsFile,'\','/') '... ']);
-0095     load(rxnsFile);
-0096     fprintf('done\n');
-0097 else
-0098     fprintf(['Cannot locate ' strrep(rxnsFile,'\','/') '\nNow try to generate it from local MetaCyc data files...\n']);
-0099     if ~isfile(fullfile(metacycPath,metaCycRxnFile)) || ~isfile(fullfile(metacycPath,metaCycPwyFile))
-0100         EM=fprintf(['The files of reactions or pathways cannot be located, and should be downloaded from MetaCyc.\n']);
-0101         dispEM(EM);
-0102     else
-0103         metaCycRxns.id='MetaCyc';
-0104         metaCycRxns.name='Automatically generated from MetaCyc database';
-0105         
-0106         %Get pathway names and add them to the field of subSystems
-0107         fid = fopen(fullfile(metacycPath,metaCycPwyFile), 'r');
-0108         
-0109         %Keeps track of how many pathways that have been added
-0110         pwyCounter=0;
-0111         pwys=cell(10000,1);
-0112         pwyNames=cell(10000,1);
-0113         
-0114         %Loop through the file
-0115         while 1
-0116             %Get the next line
-0117             tline = fgetl(fid);
-0118             
-0119             %Abort at end of file
-0120             if ~ischar(tline)
-0121                 break;
-0122             end
-0123             
-0124             %Read in pathway ids and names
-0125             if ~strcmp(tline(1),'#')
-0126                 pwyCounter=pwyCounter+1;
-0127                 vars = regexp(tline, '\t', 'split');
-0128                 pwys{pwyCounter}=vars{1};
-0129                 pwyNames{pwyCounter}=vars{2};
-0130                 
-0131                 %Romve HTML symbols
-0132                 pwyNames{pwyCounter}=removeHTMLcodes(pwyNames{pwyCounter});
-0133                 
-0134             end
-0135         end
-0136         fclose(fid);
-0137         pwys=pwys(1:pwyCounter);
-0138         pwyNames=pwyNames(1:pwyCounter);
-0139         
-0140         %Preallocate memory for 50000 reactions
-0141         metaCycRxns.rxns=cell(50000,1);
-0142         metaCycRxns.rxnNames=cell(50000,1);
-0143         metaCycRxns.eccodes=cell(50000,1);
-0144         metaCycRxns.subSystems=cell(50000,1);
-0145         metaCycRxns.pwys=cell(50000,1);
-0146         metaCycRxns.rxnMiriams=cell(50000,1);
-0147         metaCycRxns.rxnReferences=cell(50000,1);
-0148         metaCycRxns.rev=ones(50000,1); %reversibility;
-0149         
-0150         rxnLinks.metacyc=cell(10000,1);
-0151         rxnLinks.kegg=cell(10000,1);
-0152         rxnLinks.check=cell(10000,1);
-0153         isSpontaneous=false(10000,1); %spontaneous;
-0154         UNBALANCED=false(10000,1);
-0155         UNDETERMINED=false(10000,1);
-0156         TRANSPORT={};                 %transport reactions;
-0157         
-0158         metaCycRxns.equations=cell(50000,1); %reaction equations
-0159         left=cell(50000,1); %Temporarily stores the equations
-0160         right=cell(50000,1); %Temporarily stores the equations
-0161         
-0162         %First load information on reaction ID, reaction name,, pathway,
-0163         %and ec-number
-0164         fid = fopen(fullfile(metacycPath,metaCycRxnFile), 'r');
-0165         
-0166         %Keeps track of how many reactions that have been added
-0167         rxnCounter=0;
-0168         addSpont=false;
-0169         dbLinkCounter=0;
-0170         
-0171         %Loop through the file
-0172         while 1
-0173             %Get the next line
-0174             tline = fgetl(fid);
-0175             
-0176             %Abort at end of file
-0177             if ~ischar(tline)
-0178                 break;
-0179             end
-0180 
-0181             % Get the version of MetaCyc database
-0182             if numel(tline)>11 && strcmp(tline(1:11),'# Version: ')
-0183                 version=tline(12:end);
-0184             end
-0185 
-0186             %Check if it is a new reaction
-0187             if numel(tline)>12 && strcmp(tline(1:12),'UNIQUE-ID - ')
-0188                 rxnCounter=rxnCounter+1;
-0189                 nPwys=0;
-0190                 
-0191                 %Add empty strings where there should be such
-0192                 metaCycRxns.rxnNames{rxnCounter}='';
-0193                 metaCycRxns.eccodes{rxnCounter}='';
-0194                 metaCycRxns.subSystems{rxnCounter}='';
-0195                 metaCycRxns.pwys{rxnCounter}='';
-0196                 metaCycRxns.equations{rxnCounter}='';
-0197                 metaCycRxns.rxnReferences{rxnCounter}='';
-0198                 reverse=0;   %Value for reversing the equation when necessary
-0199                 
-0200                 % A complex evaluation system for generating the equations
-0201                 left{rxnCounter}='';
-0202                 right{rxnCounter}='';
-0203                 coefficient='';
-0204                 templeft='';
-0205                 tempright='';
-0206                 % might be simplified with a better algorithem
-0207                 
-0208                 %Add reaction ID
-0209                 metaCycRxns.rxns{rxnCounter}=tline(13:end);
-0210                 
-0211             end
-0212             
-0213             %Add name
-0214             if numel(tline)>14 && strcmp(tline(1:14),'COMMON-NAME - ')
-0215                 metaCycRxns.rxnNames{rxnCounter}=tline(15:end);
-0216                 
-0217                 %Romve HTML symbols
-0218                 metaCycRxns.rxnNames{rxnCounter}=removeHTMLcodes(metaCycRxns.rxnNames{rxnCounter});
-0219             end
-0220             
-0221             %Add eccodes
-0222             if numel(tline)>15 && strcmp(tline(1:15),'EC-NUMBER - EC-')
-0223                 if isempty(metaCycRxns.eccodes{rxnCounter})
-0224                     metaCycRxns.eccodes{rxnCounter}=strcat('ec-code/',tline(16:end));
-0225                 else
-0226                     metaCycRxns.eccodes{rxnCounter}=strcat(metaCycRxns.eccodes{rxnCounter},';ec-code/',tline(16:end));
-0227                 end
-0228             end
-0229             if numel(tline)>16 && strcmp(tline(1:16),'EC-NUMBER - |EC-')
-0230                 if isempty(metaCycRxns.eccodes{rxnCounter})
-0231                     metaCycRxns.eccodes{rxnCounter}=strcat('ec-code/',tline(17:end-1));
-0232                 else
-0233                     metaCycRxns.eccodes{rxnCounter}=strcat(metaCycRxns.eccodes{rxnCounter},';ec-code/',tline(17:end-1));
-0234                 end
-0235             end
-0236             
-0237             %Add pathway id and assign pathway name to subSystem field
-0238             if numel(tline)>13 && strcmp(tline(1:13),'IN-PATHWAY - ')
-0239                 if isempty(metaCycRxns.pwys{rxnCounter})
-0240                     metaCycRxns.pwys{rxnCounter}=tline(14:end);
-0241                 else
-0242                     metaCycRxns.pwys{rxnCounter}=strcat(metaCycRxns.pwys{rxnCounter},';',tline(14:end));
-0243                 end
-0244                 
-0245                 [x, y]=ismember(tline(14:end),pwys);
-0246                 if x
-0247                     metaCycRxns.subSystems{rxnCounter,1}{numel(metaCycRxns.subSystems{rxnCounter,1})+1,1}=pwyNames{y};
-0248                 end
-0249             end
-0250             
-0251             %Add references (pubmed ids)
-0252             if numel(tline)>12 && strcmp(tline(1:12),'CITATIONS - ')
-0253                 if isempty(metaCycRxns.rxnReferences{rxnCounter})
-0254                     metaCycRxns.rxnReferences{rxnCounter}=strcat('pubmed/',tline(13:end));
-0255                 else
-0256                     metaCycRxns.rxnReferences{rxnCounter}=strcat(metaCycRxns.rxnReferences{rxnCounter},';pubmed/',tline(13:end));
-0257                 end
-0258             end
-0259             
-0260             %Add Miriam info (cross-links other database)
-0261             if numel(tline)>11 && strcmp(tline(1:11),'DBLINKS - (')
-0262                 dblink=tline(12:end);
-0263                 %KEGG reaction id
-0264                 if strcmp(dblink(1:12),'LIGAND-RXN "')
-0265                     dblink=dblink(13:end);
-0266                     s=strfind(dblink,'"');
-0267                     if any(s)
-0268                         dblink=dblink(1:s-1);
-0269                     end
-0270                     
-0271                     if isstruct(metaCycRxns.rxnMiriams{rxnCounter})
-0272                         addToIndex=numel(metaCycRxns.rxnMiriams{rxnCounter}.name)+1;
-0273                     else
-0274                         addToIndex=1;
-0275                     end
-0276                     tempStruct=metaCycRxns.rxnMiriams{rxnCounter};
-0277                     tempStruct.name{addToIndex,1}='kegg.reaction';
-0278                     tempStruct.value{addToIndex,1}=dblink;
-0279                     metaCycRxns.rxnMiriams{rxnCounter}=tempStruct;
-0280                     
-0281                     %For generating the rxnLinks structure
-0282                     dbLinkCounter=dbLinkCounter+1;
-0283                     rxnLinks.metacyc{dbLinkCounter}=metaCycRxns.rxns{rxnCounter};
-0284                     rxnLinks.kegg{dbLinkCounter}=dblink;
-0285                     rxnLinks.check{dbLinkCounter}=strcat(metaCycRxns.rxns{rxnCounter},dblink);
-0286                 end
-0287                 
-0288                 %RHEA reaction id
-0289                 if strcmp(dblink(1:6),'RHEA "')
-0290                     dblink=dblink(7:end);
-0291                     s=strfind(dblink,'"');
-0292                     if any(s)
-0293                         dblink=dblink(1:s-1);
-0294                     end
-0295                     
-0296                     if isstruct(metaCycRxns.rxnMiriams{rxnCounter})
-0297                         addToIndex=numel(metaCycRxns.rxnMiriams{rxnCounter}.name)+1;
-0298                     else
-0299                         addToIndex=1;
-0300                     end
-0301                     tempStruct=metaCycRxns.rxnMiriams{rxnCounter};
-0302                     tempStruct.name{addToIndex,1}='rhea';
-0303                     tempStruct.value{addToIndex,1}=dblink;
-0304                     metaCycRxns.rxnMiriams{rxnCounter}=tempStruct;
-0305                 end
-0306             end
-0307             
-0308             if numel(tline)>21 && strcmp(tline(1:21),'REACTION-DIRECTION - ')
-0309                 rxnDirection=tline(22:end);
-0310                 switch(rxnDirection)
-0311                     case 'IRREVERSIBLE-LEFT-TO-RIGHT'
-0312                         metaCycRxns.rev(rxnCounter,1)=0;
-0313                     case 'LEFT-TO-RIGHT'
-0314                         metaCycRxns.rev(rxnCounter,1)=0;
-0315                     case 'PHYSIOL-LEFT-TO-RIGHT'
-0316                         metaCycRxns.rev(rxnCounter,1)=0;
-0317                     case 'IRREVERSIBLE-RIGHT-TO-LEFT'
-0318                         metaCycRxns.rev(rxnCounter,1)=0;
-0319                         reverse=1;
-0320                     case 'RIGHT-TO-LEFT'
-0321                         metaCycRxns.rev(rxnCounter,1)=0;
-0322                         reverse=1;
-0323                     case 'PHYSIOL-RIGHT-TO-LEFT'
-0324                         metaCycRxns.rev(rxnCounter,1)=0;
-0325                         reverse=1;
-0326                 end
-0327             end
-0328             
-0329             %Tag transport reactions
-0330             if strcmp(tline,'TYPES - Transport-Reactions')
-0331                 TRANSPORT=[TRANSPORT;metaCycRxns.rxns{rxnCounter}];
-0332             end
-0333             
-0334             %Add spontaneous
-0335             if strcmp(tline,'SPONTANEOUS? - T')
-0336                 %metaCycRxns.spontaneous(rxnCounter,1)=1;
-0337                 isSpontaneous(rxnCounter)=true;
-0338             end
-0339             
-0340             %Extract mass-balance status
-0341             if numel(tline)>27 && strcmp(tline(1:27),'REACTION-BALANCE-STATUS - :')
-0342                 if isequal(tline(28:35), 'UNBALANC')
-0343                     UNBALANCED(rxnCounter)=true;
-0344                 elseif isequal(tline(28:35), 'UNDETERM')
-0345                     UNDETERMINED(rxnCounter)=true;
-0346                 end
-0347             end
-0348             
-0349             %Add left side equation
-0350             if numel(tline)>7 && strcmp(tline(1:7),'LEFT - ')
-0351                 if strcmp(left{rxnCounter},'')
-0352                     if strcmp(templeft,'')
-0353                         templeft=tline(8:end); % this is the real first, save to a temp variable
-0354                     else % count in the coefficient here
-0355                         if strcmp(coefficient,'')
-0356                             left{rxnCounter}=templeft;
-0357                         else
-0358                             left{rxnCounter}=strcat(coefficient,32,templeft);
-0359                             coefficient='';
-0360                         end
-0361                         templeft=tline(8:end);
-0362                     end
-0363                 else
-0364                     if strcmp(coefficient,'')
-0365                         left{rxnCounter}=strcat(left{rxnCounter},' +',32,templeft);
-0366                     else
-0367                         left{rxnCounter}=strcat(left{rxnCounter},' +',32,coefficient,32,templeft);
-0368                         coefficient='';
-0369                     end
-0370                     templeft=tline(8:end);
-0371                 end
-0372             end
-0373             
-0374             %Add right side equation
-0375             if numel(tline)>8 && strcmp(tline(1:8),'RIGHT - ')
-0376                 if strcmp(right{rxnCounter},'')
-0377                     if strcmp(tempright,'')
-0378                         
-0379                         % a complicated process for the last left
-0380                         % metabolite
-0381                         if strcmp(coefficient,'')
-0382                             if strcmp(left{rxnCounter},'')
-0383                                 left{rxnCounter}=templeft;
-0384                             else
-0385                                 left{rxnCounter}=strcat(left{rxnCounter},' +',32,templeft);
-0386                             end
-0387                             
-0388                         else
-0389                             if strcmp(left{rxnCounter},'')
-0390                                 left{rxnCounter}=strcat(coefficient,32,templeft);
-0391                             else
-0392                                 left{rxnCounter}=strcat(left{rxnCounter},' +',32,coefficient,32,templeft);
-0393                             end
-0394                             coefficient='';
-0395                         end
-0396                         % process end
-0397                         
-0398                         tempright=tline(9:end); % this is the real first, save to a temp variable
-0399                     else
-0400                         if strcmp(coefficient,'')
-0401                             right{rxnCounter}=tempright;
-0402                         else
-0403                             right{rxnCounter}=strcat(coefficient,32,tempright);
-0404                             coefficient='';
-0405                         end
-0406                         tempright=tline(9:end);
-0407                     end
-0408                 else
-0409                     if strcmp(coefficient,'')
-0410                         right{rxnCounter}=strcat(right{rxnCounter},' +',32,tempright);
-0411                     else
-0412                         right{rxnCounter}=strcat(right{rxnCounter},' +',32,coefficient,32,tempright);
-0413                         coefficient='';
-0414                     end
-0415                     tempright=tline(9:end);
-0416                 end
-0417                 
-0418             end
-0419             
-0420             if numel(tline)>15 && strcmp(tline(1:15),'^COEFFICIENT - ')
-0421                 coefficient=tline(16:end);
-0422             end
-0423             
-0424             %Generate equation at the end of each object section
-0425             if strcmp(tline,'//')
-0426                 
-0427                 % a complicated process for the last right metabolite,
-0428                 % sub-function is needed here
-0429                 if strcmp(coefficient,'')
-0430                     if strcmp(right{rxnCounter},'')
-0431                         right{rxnCounter}=tempright;
-0432                     else
-0433                         right{rxnCounter}=strcat(right{rxnCounter},' +',32,tempright);
-0434                     end
-0435                     
-0436                 else
-0437                     if strcmp(right{rxnCounter},'')
-0438                         right{rxnCounter}=strcat(coefficient,32,tempright);
-0439                     else
-0440                         right{rxnCounter}=strcat(right{rxnCounter},' +',32,coefficient,32,tempright);
-0441                     end
-0442                     coefficient='';
-0443                 end
-0444                 % process end
-0445                 
-0446                 %get the right direction symbol
-0447                 if metaCycRxns.rev(rxnCounter,1)
-0448                     symbol = ' <=>';
-0449                 else
-0450                     symbol = ' =>';
-0451                 end
-0452                 
-0453                 if reverse
-0454                     metaCycRxns.equations{rxnCounter}=strcat(right{rxnCounter},symbol,32,left{rxnCounter});
-0455                 else
-0456                     metaCycRxns.equations{rxnCounter}=strcat(left{rxnCounter},symbol,32,right{rxnCounter});
-0457                 end
-0458                 
-0459                 %Final equation check
-0460                 if strcmp(left{rxnCounter},'') || strcmp(right{rxnCounter},'')
-0461                     rxnCounter=rxnCounter-1;
-0462                     
-0463                 end
-0464                 
-0465             end
-0466             
-0467         end
-0468         %Close the file
-0469         fclose(fid);
-0470         
-0471         %===
-0472         UNBALANCED=metaCycRxns.rxns(UNBALANCED);
-0473         UNDETERMINED=metaCycRxns.rxns(UNDETERMINED);
-0474         isSpontaneous=metaCycRxns.rxns(isSpontaneous);
-0475         
-0476         %If too much space was allocated, shrink the model
-0477         metaCycRxns.rxns=metaCycRxns.rxns(1:rxnCounter);
-0478         metaCycRxns.rxnNames=metaCycRxns.rxnNames(1:rxnCounter);
-0479         metaCycRxns.eccodes=metaCycRxns.eccodes(1:rxnCounter);
-0480         metaCycRxns.equations=metaCycRxns.equations(1:rxnCounter);
-0481         metaCycRxns.rxnMiriams=metaCycRxns.rxnMiriams(1:rxnCounter);
-0482         metaCycRxns.rxnReferences=metaCycRxns.rxnReferences(1:rxnCounter);
-0483         metaCycRxns.subSystems=metaCycRxns.subSystems(1:rxnCounter);
-0484         metaCycRxns.pwys=metaCycRxns.pwys(1:rxnCounter);
-0485         metaCycRxns.rev=metaCycRxns.rev(1:rxnCounter,:);
-0486         
-0487         rxnLinks.kegg=rxnLinks.kegg(1:dbLinkCounter);
-0488         rxnLinks.metacyc=rxnLinks.metacyc(1:dbLinkCounter);
-0489         rxnLinks.check=rxnLinks.check(1:dbLinkCounter);
-0490         [~,index]=unique(rxnLinks.check);
-0491         rxnLinks.kegg=rxnLinks.kegg(index);
-0492         rxnLinks.metacyc=rxnLinks.metacyc(index);
-0493         rxnLinks=rmfield(rxnLinks,'check');
-0494         
-0495         %Construct the S matrix and list of metabolites
-0496         [S, mets, badRxns]=constructS(metaCycRxns.equations);
-0497         metaCycRxns.S=S;
-0498         metaCycRxns.mets=mets;
-0499         
-0500         %Add some stuff to get a correct model structure
-0501         metaCycRxns.ub=ones(rxnCounter,1)*1000;
-0502         metaCycRxns.lb=metaCycRxns.rev*-1000;
-0503         metaCycRxns.c=zeros(rxnCounter,1);
-0504         metaCycRxns.b=zeros(numel(metaCycRxns.mets),1);
-0505         metaCycRxns.version=version;
-0506         
-0507         %Save the model structure
-0508         save(rxnsFile,'metaCycRxns','rxnLinks','TRANSPORT','UNBALANCED','UNDETERMINED','isSpontaneous');
-0509         fprintf(['New metaCycRxns.mat has been successfully updated!\n\n']);
-0510     end
-0511 end
-0512 
-0513 %Deal with reactions that are labeled as "TRANSPORT", "UNBALANCED", or
-0514 %"UNDETERMINED" (depending on settings).
-0515 model=metaCycRxns;
-0516 if keepTransportRxns==false
-0517     model=removeReactions(model,intersect(TRANSPORT,model.rxns),true,true);
-0518 end
-0519 if keepUnbalanced==false
-0520     model=removeReactions(model,intersect(UNBALANCED,model.rxns),true,true);
-0521 end
-0522 if keepUndetermined==false
-0523     model=removeReactions(model,intersect(UNDETERMINED,model.rxns),true,true);
-0524 end
-0525 end
-0526 
-0527 %Sub function for romving HTML symbols from the names of reaction and
-0528 %pathway
-0529 function newString=removeHTMLcodes(string)
-0530 string=regexprep(string,'<(\w+)>','');
-0531 string=regexprep(string,'</(\w+)>','');
-0532 string=regexprep(string,'[&;]','');
-0533 newString=string;
-0534 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/external/metacyc/index.html b/doc/external/metacyc/index.html deleted file mode 100644 index 10337f067..000000000 --- a/doc/external/metacyc/index.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - Index for Directory external\metacyc - - - - - - - - - - -
< Master indexIndex for external\metacyc >
- -

Index for external\metacyc

- -

Matlab files in this directory:

- -
 addSpontaneousRxnsaddSpontaneousRxns
 getEnzymesFromMetaCycgetEnzymesFromMetaCyc
 getMetaCycModelForOrganismgetMetaCycModelForOrganism
 getMetsFromMetaCycgetMetsFromMetaCyc
 getModelFromMetaCycgetModelFromMetaCyc
 getRxnsFromMetaCycgetRxnsFromMetaCyc
 linkMetaCycKEGGRxnslinkMetaCycKEGGRxns
- -

Other Matlab-specific files in this directory:

-
    -
  • metaCycEnzymes.mat
  • metaCycMets.mat
  • metaCycRxns.mat
- - -
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/external/metacyc/linkMetaCycKEGGRxns.html b/doc/external/metacyc/linkMetaCycKEGGRxns.html deleted file mode 100644 index 0ffecbbe1..000000000 --- a/doc/external/metacyc/linkMetaCycKEGGRxns.html +++ /dev/null @@ -1,159 +0,0 @@ - - - - Description of linkMetaCycKEGGRxns - - - - - - - - - -
Home > external > metacyc > linkMetaCycKEGGRxns.m
- - - -

linkMetaCycKEGGRxns -

- -

PURPOSE ^

-
linkMetaCycKEGGRxns
- -

SYNOPSIS ^

-
function linkMetaCycKEGGRxns
- -

DESCRIPTION ^

-
 linkMetaCycKEGGRxns
-   Link additional MetaCyc and KEGG reactions through metabolite mapping
-   This function only need to run once when the MetaCyc database is updated
-
-   NOTE: No arguments are required
-
- Usage: linkMetaCycKEGGRxns
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function linkMetaCycKEGGRxns
-0002 % linkMetaCycKEGGRxns
-0003 %   Link additional MetaCyc and KEGG reactions through metabolite mapping
-0004 %   This function only need to run once when the MetaCyc database is updated
-0005 %
-0006 %   NOTE: No arguments are required
-0007 %
-0008 % Usage: linkMetaCycKEGGRxns
-0009 
-0010 load('metaCycRxns.mat'); %load MetaCyc reactions
-0011 fprintf('NOTE: Importing MetaCyc reactions...\n');
-0012 metaCycModel = metaCycRxns;
-0013 metaCycModel.rxnFrom=cell(numel(metaCycModel.rxns),1);
-0014 metaCycModel.rxnFrom(:)={'MetaCyc'};
-0015 metaCycModel.grRules={};
-0016 metaCycModel.genes={};
-0017 metaCycModel.rxnGeneMat=sparse(numel(metaCycModel.rxns),1);
-0018 
-0019 
-0020 keggModel=getRxnsFromKEGG(); %load KEGG reactions
-0021 
-0022 %Remove KEGG reactions with MetaCyc links based on original rxnLinks
-0023 rxnToRemove=intersect(rxnLinks.kegg,keggModel.rxns);
-0024 rxnToRemove=unique(rxnToRemove);
-0025 shrinkedKeggModel=removeReactions(keggModel,rxnToRemove,true,true);
-0026 
-0027 fprintf('Mapping MetaCyc and KEGG reactions...\n');
-0028 %Resolve the shared but unmapped reactions (through mapping the involved
-0029 %metabolites). Replace mets information in KEGG model with the
-0030 %corresponding ones in MetaCyc.
-0031 load('metaCycMets.mat');
-0032 for i=1:numel(shrinkedKeggModel.mets)
-0033     [a, b]=ismember(shrinkedKeggModel.mets{i},metaCycMets.keggid);
-0034     if a
-0035         %Replace the met ids
-0036         shrinkedKeggModel.mets{i}=metaCycMets.mets{b};
-0037         shrinkedKeggModel.metNames{i}=metaCycMets.mets{b};
-0038     end
-0039 end
-0040 
-0041 %Prepare for the merge of KEGG and MetaCyc super models
-0042 
-0043 %Adding fields (comps, compNames, metNames, metComps)
-0044 metaCycModel.comps={'s'};
-0045 metaCycModel.compNames={'System'};
-0046 metaCycModel.metNames=metaCycModel.mets;
-0047 if ~isfield(metaCycModel,'metComps')
-0048     metaCycModel.metComps=ones(numel(metaCycModel.mets),1);
-0049 end
-0050 
-0051 shrinkedKeggModel.comps={'s'};
-0052 shrinkedKeggModel.compNames={'System'};
-0053 shrinkedKeggModel.metNames=shrinkedKeggModel.mets;
-0054 if ~isfield(shrinkedKeggModel,'metComps')
-0055     shrinkedKeggModel.metComps=ones(numel(shrinkedKeggModel.mets),1);
-0056 end
-0057 
-0058 %Merge models
-0059 mappingModel=mergeModels({shrinkedKeggModel metaCycModel},'metNames');
-0060 
-0061 %Remove compounds proton and water because KEGG reactions often miss them
-0062 mappingModel=removeMets(mappingModel,{'PROTON','WATER'});
-0063 
-0064 %Find same/similiar reactions by check identical columns in S matrix Go
-0065 %through the pure KEGG model and collect rxns id that have identical
-0066 %reactions to the ones in MetaCyc
-0067 I=find(ismember(mappingModel.rxnFrom,'KEGG'));
-0068 for i=1:numel(I)
-0069     testRxn=mappingModel.S(:,I(i));
-0070     match=find(~any(bsxfun(@minus, mappingModel.S,testRxn))); %Figure out the matched columns in S matrix
-0071     % if ~isequal(match,I(i))
-0072     count=numel(match);
-0073     if count>1 %Only consider one-to-one match here
-0074         for j=2:count
-0075             %Only consider the match between KEGG and MetaCyc
-0076             if isequal(mappingModel.rxnFrom{match(j)},'MetaCyc')
-0077                 %disp([mappingModel.rxns(match(1))
-0078                 %mappingModel.rxns(match(j))]); %keep this for later
-0079                 %checking
-0080                 rxnLinks.kegg=[rxnLinks.kegg;mappingModel.rxns(match(1))];
-0081                 rxnLinks.metacyc=[rxnLinks.metacyc;mappingModel.rxns(match(j))];
-0082             end
-0083         end
-0084     end
-0085     % end
-0086 end
-0087 
-0088 % Load orginal rxnLinks
-0089 numLink=numel(rxnLinks.kegg);
-0090 rxnLinks.check=cell(numLink,1);
-0091 for i=1:numLink
-0092     rxnLinks.check{i}=strcat(rxnLinks.kegg{i},rxnLinks.metacyc{i});
-0093 end
-0094 
-0095 [~, index]=unique(rxnLinks.check);
-0096 rxnLinks.kegg=rxnLinks.kegg(index);
-0097 rxnLinks.metacyc=rxnLinks.metacyc(index);
-0098 rxnLinks=rmfield(rxnLinks,'check');
-0099 
-0100 %Get the MetaCyc path and update the metaCycRxns.mat
-0101 ravenPath=findRAVENroot();
-0102 rxnsFile=fullfile(ravenPath,'external','metacyc','metaCycRxns.mat');
-0103 save(rxnsFile,'metaCycRxns','rxnLinks','TRANSPORT','UNBALANCED','UNDETERMINED','isSpontaneous');
-0104 fprintf(['Reaction associations between MetaCyc and KEGG have been successfully updated!\n\n']);
-0105 
-0106 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/external/parseScores.html b/doc/external/parseScores.html deleted file mode 100644 index d82f859d4..000000000 --- a/doc/external/parseScores.html +++ /dev/null @@ -1,189 +0,0 @@ - - - - Description of parseScores - - - - - - - - - -
Home > external > parseScores.m
- - - -

parseScores -

- -

PURPOSE ^

-
parseScores
- -

SYNOPSIS ^

-
function GSS = parseScores(inputFile, predictor)
- -

DESCRIPTION ^

-
 parseScores
-    Parse the output from a predictor to generate the GSS
-
-    Input:
-    inputFile    a file with the output from the predictor
-    predictor    the predictor that was used. 'wolf' for WoLF PSORT, 'cello'
-               for CELLO, 'deeploc' for DeepLoc (optional, default 'wolf')
-
-    Output:
-    GSS         a gene scoring structure to be used in predictLocalization
-
-    The function normalizes the scores so that the best score for each gene
-    is 1.0.
-
-    Usage: GSS = parseScores(inputFile, predictor)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function GSS = parseScores(inputFile, predictor)
-0002 % parseScores
-0003 %    Parse the output from a predictor to generate the GSS
-0004 %
-0005 %    Input:
-0006 %    inputFile    a file with the output from the predictor
-0007 %    predictor    the predictor that was used. 'wolf' for WoLF PSORT, 'cello'
-0008 %               for CELLO, 'deeploc' for DeepLoc (optional, default 'wolf')
-0009 %
-0010 %    Output:
-0011 %    GSS         a gene scoring structure to be used in predictLocalization
-0012 %
-0013 %    The function normalizes the scores so that the best score for each gene
-0014 %    is 1.0.
-0015 %
-0016 %    Usage: GSS = parseScores(inputFile, predictor)
-0017 
-0018 if nargin<2
-0019     predictor='wolf';
-0020 else
-0021     predictor=char(predictor);
-0022 end
-0023 
-0024 fid=fopen(inputFile,'r');
-0025 
-0026 if fid<1
-0027     EM='Could not open file';
-0028     dispEM(EM);
-0029 end
-0030 
-0031 if strcmpi(predictor,'wolf')
-0032     A=textscan(fid,'%s','Delimiter','\n','CommentStyle','#');
-0033     
-0034     %Each element should be for one gene, but some of them are on the form
-0035     %"Pc20g11350: treating 9 X's as Glycines". Those should be removed
-0036     I=~cellfun(@any,strfind(A{1},'treating'));
-0037     
-0038     B=regexp(A{1}(I),' ','split');
-0039     
-0040     %Reserve space for stuff
-0041     GSS.compartments={};
-0042     GSS.scores=[]; %Do not know number of comps yet
-0043     GSS.genes=cell(numel(B),1);
-0044     
-0045     %Parsing is a bit cumbersome as ', ' is used as a delimiter in some
-0046     %cases and ' ' in others. Use strrep to get rid of ','
-0047     for i=1:numel(B)
-0048         b=strrep(B{i},',','');
-0049         GSS.genes{i}=b{1};
-0050         
-0051         %Then go through the compartments and add new ones as they are
-0052         %found
-0053         for j=2:2:numel(b)-1
-0054             [~, J]=ismember(b(j),GSS.compartments);
-0055             
-0056             %Add new compartment if it does not exist
-0057             if J==0
-0058                 GSS.compartments=[GSS.compartments;b(j)];
-0059                 J=numel(GSS.compartments);
-0060                 GSS.scores=[GSS.scores zeros(numel(B),1)];
-0061             end
-0062             
-0063             GSS.scores(i,J)=str2double(b(j+1));
-0064         end
-0065     end
-0066 elseif strcmpi(predictor,'cello')
-0067     fid=fopen(inputFile,'r');
-0068     %Read the title line and fetch the list of compartments
-0069     tline = fgetl(fid);
-0070     tline=regexprep(tline,'^.+#Combined:\t','');
-0071     tline=regexprep(tline,'\t#Most-likely-Location.+','');
-0072     GSS.compartments=transpose(regexp(tline,'\t','split'));
-0073     
-0074     %Now iterate through the following lines in the file. Each row
-0075     %corresponds to one gene and it consists of the scores for
-0076     %compartments. Gene name is in the end of each line
-0077     row=0;
-0078     while 1
-0079         row=row+1;
-0080         tline = fgetl(fid);
-0081         if ~ischar(tline)
-0082             break;
-0083         end
-0084         tline=regexprep(tline,'^.+:\t','');
-0085         tline=regexprep(tline,' .+','');
-0086         tline=regexp(tline,'\t','split');
-0087         GSS.scores(row,:)=str2double(tline(1:numel(GSS.compartments)));
-0088         GSS.genes{row,1}=tline{1,end};
-0089     end
-0090 elseif strcmpi(predictor,'deeploc')
-0091     fid=fopen(inputFile,'r');
-0092     %Read the title line and fetch the list of compartments
-0093     tline = fgetl(fid);
-0094     GSS.compartments=regexp(tline,',','split');
-0095     GSS.compartments=transpose(GSS.compartments(4:end));
-0096     
-0097     %Now iterate through the following lines in the file. Each row
-0098     %corresponds to one gene and it consists of the scores for
-0099     %compartments. Gene name is in the end of each line
-0100     row=0;
-0101     while 1
-0102         row=row+1;
-0103         tline = fgetl(fid);
-0104         if ~ischar(tline)
-0105             break;
-0106         end
-0107         tline=regexp(tline,',','split');
-0108         GSS.scores(row,:)=str2double(tline(4:end));
-0109         GSS.genes{row,1}=tline{1,1};
-0110     end
-0111 end
-0112 
-0113 %Check if there are duplicate genes
-0114 [~, J, K]=unique(GSS.genes);
-0115 
-0116 if numel(J)~=numel(K)
-0117     EM='There are duplicate genes in the input file';
-0118     dispEM(EM,false);
-0119     GSS.genes=GSS.genes(J);
-0120     GSS.scores=GSS.scores(J,:);
-0121 end
-0122 
-0123 %Normalize
-0124 I=max(GSS.scores,[],2);
-0125 GSS.scores=bsxfun(@times, GSS.scores, 1./I);
-0126 
-0127 fclose(fid);
-0128 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/external/updateDocumentation.html b/doc/external/updateDocumentation.html deleted file mode 100644 index 8967f8766..000000000 --- a/doc/external/updateDocumentation.html +++ /dev/null @@ -1,95 +0,0 @@ - - - - Description of updateDocumentation - - - - - - - - - -
Home > external > updateDocumentation.m
- - - -

updateDocumentation -

- -

PURPOSE ^

-
updateDocumentation
- -

SYNOPSIS ^

-
function updateDocumentation()
- -

DESCRIPTION ^

-
 updateDocumentation
-    Updates HTML documentation files for all RAVEN functions. It should
-    only be used when preparing `develop` branch for a new RAVEN release
-
-    Usage: updateDocumentation()
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function updateDocumentation()
-0002 % updateDocumentation
-0003 %    Updates HTML documentation files for all RAVEN functions. It should
-0004 %    only be used when preparing `develop` branch for a new RAVEN release
-0005 %
-0006 %    Usage: updateDocumentation()
-0007 
-0008 %Get the RAVEN path
-0009 ravenDir=findRAVENroot();
-0010 %Make sure that RAVEN-provided m2html is used
-0011 path(fullfile(ravenDir,'software','m2html'),path);
-0012 %Get a non-redundant list of RAVEN subdirectories containing MATLAB
-0013 %functions. Absolute paths are not compatible with M2HTML, so convert them
-0014 %to the relative paths instead.
-0015 ravenDirs=dir(fullfile(ravenDir,'**/*.m'));
-0016 ravenDirs=unique({ravenDirs.folder})';
-0017 
-0018 %Get rid of MATLAB functions from external software
-0019 ravenDirs(startsWith(ravenDirs,strcat(ravenDir,filesep,'software')))=[];
-0020 ravenDirs(startsWith(ravenDirs,strcat(ravenDir,filesep,'legacy',filesep,'software')))=[];
-0021 
-0022 %Remove keggModel.mat if it exists
-0023 if exist(fullfile(ravenDir,'external','kegg','keggModel.mat'), 'file') == 2
-0024     delete(fullfile(ravenDir,'external','kegg','keggModel.mat'));
-0025 end
-0026 
-0027 %Remove existing "doc" directory from RAVEN
-0028 rmdir(fullfile(ravenDir,'doc'),'s');
-0029 
-0030 %Make relative path
-0031 relStart = numel(ravenDir)+2;
-0032 for i=1:numel(ravenDirs)
-0033     ravenDirs{i,1} = ravenDirs{i,1}(relStart:end);
-0034 end
-0035 
-0036 %Save the current working directory and go to RAVEN root directory
-0037 originalDir=pwd;
-0038 cd(ravenDir);
-0039 %Generate HTML documentation files for RAVEN MATLAB functions
-0040 m2html('mFiles',ravenDirs,'htmldir','doc');
-0041 %Go back to the original working directory
-0042 cd(originalDir);
-0043 
-0044 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/fortran.png b/doc/fortran.png deleted file mode 100644 index 350c572ee38fc5aa8cef025284caa41a46921cbf..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 265 zcmV+k0rvihP)z zQ4Yf(2!?U#(c~&{CVCaUn|okwjJWCAv@Y{YACUYt5I|c;L@*Nz0Eo!wFm8gG7quL( z=eJ8jF~;-zT!i-?03M^mxSQz{PD1(=o)3a5h-huxIH1YJR@TpAUHLpGAzkjqF33Gq z5HW;M#1ulv?Ojv&dqVG&6;xWfSwIyu&pDe3Y?b*+^Nvd@T*dL)Y-z<7!R9u;!a16o zt!IDE1;u=7(6;lN@7iT2j)+8Ll6#n$r@xl|p4XvuY#=TA`S#1W+5VQEsg98Zwj;#Z P00000NkvXXu0mjf06Tac diff --git a/doc/hp.png b/doc/hp.png deleted file mode 100644 index d09f988fb289d659869dbb1b2f199fd967a93958..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 255 zcmVz z%MHUI3_wlAXs`;N$*f{_qX$Rw9FO zez{B`r8K|JmvGJjz-@IJXS2Omg-^gRJ-6O z&=syLR&U^^a}=eRZLpT@KTChlV@n^^it_t*Wz253r911aWh5p(A;kay002ovPDHLk FV1l-WYkL3y diff --git a/doc/hpa/index.html b/doc/hpa/index.html deleted file mode 100644 index a659dab22..000000000 --- a/doc/hpa/index.html +++ /dev/null @@ -1,29 +0,0 @@ - - - - Index for Directory hpa - - - - - - - - - - -
< Master indexIndex for hpa >
- -

Index for hpa

- -

Matlab files in this directory:

- -
 parseHPAparseHPA
 parseHPArnaparseHPA
 scoreModelscoreRxns
- - - - -
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/hpa/parseHPA.html b/doc/hpa/parseHPA.html deleted file mode 100644 index c6064594f..000000000 --- a/doc/hpa/parseHPA.html +++ /dev/null @@ -1,188 +0,0 @@ - - - - Description of parseHPA - - - - - - - - - -
Home > hpa > parseHPA.m
- - - -

parseHPA -

- -

PURPOSE ^

-
parseHPA
- -

SYNOPSIS ^

-
function hpaData=parseHPA(fileName, version)
- -

DESCRIPTION ^

-
 parseHPA
-   Parses a database dump of the Human Protein Atlas (HPA)
-
-   Input:
-   fileName            comma- or tab-separated database dump of HPA. For details
-                       regarding the format, see
-                       http://www.proteinatlas.org/about/download.
-   version             version of HPA [optional, default=19]
-
-
-   Output:
-   hpaData
-       genes               cell array with the unique gene names. In
-                           version >=18 this is the ensemble name, see
-                           geneNames below for the names in ver >=18
-       geneNames           cell array with the gene names, indexed the
-                           same way as genes.
-       tissues             cell array with the tissue names. The list may not be
-                           unique, as there can be multiple cell types per tissue
-       celltypes           cell array with the cell type names for each tissue
-       levels              cell array with the unique expression levels
-       types               cell array with the unique evidence types
-       reliabilities       cell array with the unique reliability levels
-
-       gene2Level          gene-to-expression level mapping in sparse matrix form.
-                           The value for element i,j is the index in
-                           hpaData.levels of gene i in cell type j
-       gene2Type           gene-to-evidence type mapping in sparse matrix form.
-                           The value for element i,j is the index in
-                           hpaData.types of gene i in cell type j. Doesn't
-                           exist in version >=18.
-       gene2Reliability    gene-to-reliability level mapping in sparse matrix form.
-                           The value for element i,j is the index in
-                           hpaData.reliabilities of gene i in cell type j
-
- Usage: hpaData=parseHPA(fileName,version)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function hpaData=parseHPA(fileName, version)
-0002 % parseHPA
-0003 %   Parses a database dump of the Human Protein Atlas (HPA)
-0004 %
-0005 %   Input:
-0006 %   fileName            comma- or tab-separated database dump of HPA. For details
-0007 %                       regarding the format, see
-0008 %                       http://www.proteinatlas.org/about/download.
-0009 %   version             version of HPA [optional, default=19]
-0010 %
-0011 %
-0012 %   Output:
-0013 %   hpaData
-0014 %       genes               cell array with the unique gene names. In
-0015 %                           version >=18 this is the ensemble name, see
-0016 %                           geneNames below for the names in ver >=18
-0017 %       geneNames           cell array with the gene names, indexed the
-0018 %                           same way as genes.
-0019 %       tissues             cell array with the tissue names. The list may not be
-0020 %                           unique, as there can be multiple cell types per tissue
-0021 %       celltypes           cell array with the cell type names for each tissue
-0022 %       levels              cell array with the unique expression levels
-0023 %       types               cell array with the unique evidence types
-0024 %       reliabilities       cell array with the unique reliability levels
-0025 %
-0026 %       gene2Level          gene-to-expression level mapping in sparse matrix form.
-0027 %                           The value for element i,j is the index in
-0028 %                           hpaData.levels of gene i in cell type j
-0029 %       gene2Type           gene-to-evidence type mapping in sparse matrix form.
-0030 %                           The value for element i,j is the index in
-0031 %                           hpaData.types of gene i in cell type j. Doesn't
-0032 %                           exist in version >=18.
-0033 %       gene2Reliability    gene-to-reliability level mapping in sparse matrix form.
-0034 %                           The value for element i,j is the index in
-0035 %                           hpaData.reliabilities of gene i in cell type j
-0036 %
-0037 % Usage: hpaData=parseHPA(fileName,version)
-0038 
-0039 if nargin<2
-0040     version=19; %Change this and add code for more versions when the current HPA version is increased and the format is changed
-0041 end
-0042 
-0043 fileName=char(fileName);
-0044 if ~isfile(fileName)
-0045     error('HPA file %s cannot be found',string(fileName));
-0046 end
-0047 
-0048 if (version >= 17)
-0049     fid=fopen(fileName,'r');
-0050     hpa=textscan(fid,'%q %q %q %q %q %q','Delimiter','\t');
-0051     fclose(fid);
-0052     
-0053     %Go through and see if the headers match what was expected
-0054     headers={'Gene' 'Gene name' 'Tissue' 'Cell type' 'Level' 'Reliability'};
-0055     for i=1:numel(headers)
-0056         if ~strcmpi(headers(i),hpa{i}(1))
-0057             EM=['Could not find the header "' headers{i} '". Make sure that the input file matches the format specified at http://www.proteinatlas.org/about/download'];
-0058             dispEM(EM);
-0059         end
-0060         %Remove the header line here
-0061         hpa{i}(1)=[];
-0062     end
-0063     
-0064     %Get the unique values of each data type
-0065     [hpaData.genes, P, I]=unique(hpa{1});
-0066     hpaData.geneNames=hpa{2}(P); %make this vector use the index as genes
-0067     [~, J, K]=unique(strcat(hpa{3},'€',hpa{4}));
-0068     hpaData.tissues=hpa{3}(J);
-0069     hpaData.celltypes=hpa{4}(J);
-0070     [hpaData.levels, ~, L]=unique(hpa{5});
-0071     [hpaData.reliabilities, ~, N]=unique(hpa{6});
-0072     
-0073     %Map the data to be sparse matrises instead
-0074     hpaData.gene2Level=sparse(I,K,L,numel(hpaData.genes),numel(hpaData.tissues));
-0075     hpaData.gene2Reliability=sparse(I,K,N,numel(hpaData.genes),numel(hpaData.tissues));
-0076 else
-0077     fid=fopen(fileName,'r');
-0078     hpa=textscan(fid,'%q %q %q %q %q %q','Delimiter',',');
-0079     fclose(fid);
-0080     
-0081     %Go through and see if the headers match what was expected
-0082     headers={'Gene' 'Tissue' 'Cell type' 'Level' 'Expression type' 'Reliability'};
-0083     for i=1:numel(headers)
-0084         if ~strcmpi(headers(i),hpa{i}(1))
-0085             EM=['Could not find the header "' headers{i} '". Make sure that the input file matches the format specified at http://www.proteinatlas.org/about/download'];
-0086             dispEM(EM);
-0087         end
-0088         %Remove the header line here
-0089         hpa{i}(1)=[];
-0090     end
-0091     
-0092     %Get the unique values of each data type
-0093     [hpaData.genes, ~, I]=unique(hpa{1});
-0094     [~, J, K]=unique(strcat(hpa{2},'€',hpa{3}));
-0095     hpaData.tissues=hpa{2}(J);
-0096     hpaData.celltypes=hpa{3}(J);
-0097     [hpaData.levels, ~, L]=unique(hpa{4});
-0098     [hpaData.types, ~, M]=unique(hpa{5});
-0099     [hpaData.reliabilities, ~, N]=unique(hpa{6});
-0100     
-0101     %Map the data to be sparse matrises instead
-0102     hpaData.gene2Level=sparse(I,K,L,numel(hpaData.genes),numel(hpaData.tissues));
-0103     hpaData.gene2Type=sparse(I,K,M,numel(hpaData.genes),numel(hpaData.tissues));
-0104     hpaData.gene2Reliability=sparse(I,K,N,numel(hpaData.genes),numel(hpaData.tissues));
-0105 end
-0106 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/hpa/parseHPArna.html b/doc/hpa/parseHPArna.html deleted file mode 100644 index 8aae52fce..000000000 --- a/doc/hpa/parseHPArna.html +++ /dev/null @@ -1,136 +0,0 @@ - - - - Description of parseHPArna - - - - - - - - - -
Home > hpa > parseHPArna.m
- - - -

parseHPArna -

- -

PURPOSE ^

-
parseHPA
- -

SYNOPSIS ^

-
function arrayData=parseHPArna(fileName, version)
- -

DESCRIPTION ^

-
 parseHPA
-   Parses a database dump of the Human Protein Atlas (HPA) RNA-Seq data.
-
-   Input:
-   fileName            tab-separated database dump of HPA RNA data. For
-                       details regarding the format, see
-                       http://www.proteinatlas.org/about/download.
-   version             version of HPA [optional, default=19]
-
-
-   Output:
-   arrayData
-       genes               cell array with the unique ensemble gene IDs
-       geneNames           cell array with the gene names (gene abbrevs)
-       tissues             cell array with the tissue names
-       levels              matrix of gene expression levels (TPM), where
-                           rows correspond to genes, and columns
-                           correspond to tissues
-
- Usage: arrayData=parseHPArna(fileName,version)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function arrayData=parseHPArna(fileName, version)
-0002 % parseHPA
-0003 %   Parses a database dump of the Human Protein Atlas (HPA) RNA-Seq data.
-0004 %
-0005 %   Input:
-0006 %   fileName            tab-separated database dump of HPA RNA data. For
-0007 %                       details regarding the format, see
-0008 %                       http://www.proteinatlas.org/about/download.
-0009 %   version             version of HPA [optional, default=19]
-0010 %
-0011 %
-0012 %   Output:
-0013 %   arrayData
-0014 %       genes               cell array with the unique ensemble gene IDs
-0015 %       geneNames           cell array with the gene names (gene abbrevs)
-0016 %       tissues             cell array with the tissue names
-0017 %       levels              matrix of gene expression levels (TPM), where
-0018 %                           rows correspond to genes, and columns
-0019 %                           correspond to tissues
-0020 %
-0021 % Usage: arrayData=parseHPArna(fileName,version)
-0022 
-0023 if nargin<2
-0024     %Change this and add code for more versions when the current HPA
-0025     %version is increased and the format is changed
-0026     version=19;
-0027 end
-0028 
-0029 fileName=char(fileName);
-0030 if ~isfile(fileName)
-0031     error('HPA file %s cannot be found', string(fileName));
-0032 end
-0033 
-0034 %NOTE! This function assumes that the first 4 columns contain (in order):
-0035 % (1) gene ensembl ID, (2) gene abbrev, (3) tissue name,  (4) TPM value
-0036 if (version == 19)
-0037     headers={'Gene' 'Gene name' 'Tissue' 'TPM' 'pTPM' 'NX'};
-0038 elseif (version == 18)
-0039     headers={'Gene' 'Gene name' 'Sample' 'Value' 'Unit'};
-0040 else
-0041     error('Only HPA versions 18 and 19 are currently supported.');
-0042 end
-0043 
-0044 %extract data from file
-0045 formatSpec = strip(repmat('%q ', 1, numel(headers)));
-0046 fid=fopen(fileName, 'r');
-0047 hpa=textscan(fid, formatSpec, 'Delimiter', '\t');
-0048 fclose(fid);
-0049 
-0050 %Go through and see if the headers match what was expected
-0051 for i=1:numel(headers)
-0052     if ~strcmpi(headers(i),hpa{i}(1))
-0053         EM=['Could not find the header "' headers{i} '". Make sure that the input file matches the format specified at http://www.proteinatlas.org/about/download'];
-0054         dispEM(EM);
-0055     end
-0056     %Remove the header line here
-0057     hpa{i}(1)=[];
-0058 end
-0059 
-0060 %Get unique gene IDs and tissue names
-0061 [arrayData.genes, P, I] = unique(hpa{1});
-0062 arrayData.geneNames = hpa{2}(P);  % retrieve corresponding gene names
-0063 [arrayData.tissues, ~, J] = unique(hpa{3});
-0064 
-0065 %Now extract the gene levels and organize into matrix
-0066 arrayData.levels = NaN(max(I),max(J));
-0067 linearInd = sub2ind(size(arrayData.levels),I,J);
-0068 arrayData.levels(linearInd) = str2double(hpa{4});
-0069     
-0070
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/hpa/scoreModel.html b/doc/hpa/scoreModel.html deleted file mode 100644 index 5e37f5449..000000000 --- a/doc/hpa/scoreModel.html +++ /dev/null @@ -1,428 +0,0 @@ - - - - Description of scoreModel - - - - - - - - - -
Home > hpa > scoreModel.m
- - - -

scoreModel -

- -

PURPOSE ^

-
scoreRxns
- -

SYNOPSIS ^

-
function [rxnScores, geneScores, hpaScores, arrayScores]=scoreModel(model,hpaData,arrayData,tissue,celltype,noGeneScore,multipleGeneScoring,multipleCellScoring,hpaLevelScores)
- -

DESCRIPTION ^

-
 scoreRxns
-   Scores the reactions and genes in a model based on expression data
-   from HPA and/or gene arrays
-
-   Input:
-   model               a model structure
-   hpaData             HPA data structure from parseHPA (optional if arrayData is
-                       supplied, default [])
-   arrayData           gene expression data structure (optional if hpaData is
-                       supplied, default [])
-       genes           cell array with the unique gene names
-       tissues         cell array with the tissue names. The list may not be
-                       unique, as there can be multiple cell types per tissue
-       celltypes       cell array with the cell type names for each tissue
-       levels          GENESxTISSUES array with the expression level for
-                       each gene in each tissue/celltype. NaN should be
-                       used when no measurement was performed
-       threshold       a single value or a vector of gene expression 
-                       thresholds, above which genes are considered to be
-                       "expressed". (optional, by default, the mean expression
-                       levels of each gene across all tissues in arrayData
-                       will be used as the threshold values)
-   tissue              tissue to score for. Should exist in either
-                       hpaData.tissues or arrayData.tissues
-   celltype            cell type to score for. Should exist in either
-                       hpaData.celltypes or arrayData.celltypes for this
-                       tissue (optional, default is to use the best values
-                       among all the cell types for the tissue. Use [] if
-                       you want to supply more arguments)
-   noGeneScore         score for reactions without genes (optional, default -2)
-   multipleGeneScoring determines how scores are calculated for reactions
-                       with several genes ('best' or 'average')
-                       (optional, default 'best')
-   multipleCellScoring determines how scores are calculated when several
-                       cell types are used ('best' or 'average')
-                       (optional, default 'best')
-   hpaLevelScores      structure with numerical scores for the expression
-                       level categories from HPA. The structure should have a
-                       "names" and a "scores" field (optional, see code for
-                       default scores)
-
-
-   Output:
-   rxnScores       scores for each of the reactions in model
-   geneScores      scores for each of the genes in model. Genes which are
-                   not in the dataset(s) have -Inf as scores
-   hpaScores       scores for each of the genes in model if only taking hpaData
-                   into account. Genes which are not in the dataset(s)
-                   have -Inf as scores
-   arrayScores     scores for each of the genes in model if only taking arrayData
-                   into account. Genes which are not in the dataset(s)
-                   have -Inf as scores
-
- Usage: [rxnScores, geneScores, hpaScores, arrayScores]=scoreModel(model,...
-               hpaData,arrayData,tissue,celltype,noGeneScore,multipleGeneScoring,...
-               multipleCellScoring,hpaLevelScores)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 function [rxnScores, geneScores, hpaScores, arrayScores]=scoreModel(model,hpaData,arrayData,tissue,celltype,noGeneScore,multipleGeneScoring,multipleCellScoring,hpaLevelScores)
-0002 % scoreRxns
-0003 %   Scores the reactions and genes in a model based on expression data
-0004 %   from HPA and/or gene arrays
-0005 %
-0006 %   Input:
-0007 %   model               a model structure
-0008 %   hpaData             HPA data structure from parseHPA (optional if arrayData is
-0009 %                       supplied, default [])
-0010 %   arrayData           gene expression data structure (optional if hpaData is
-0011 %                       supplied, default [])
-0012 %       genes           cell array with the unique gene names
-0013 %       tissues         cell array with the tissue names. The list may not be
-0014 %                       unique, as there can be multiple cell types per tissue
-0015 %       celltypes       cell array with the cell type names for each tissue
-0016 %       levels          GENESxTISSUES array with the expression level for
-0017 %                       each gene in each tissue/celltype. NaN should be
-0018 %                       used when no measurement was performed
-0019 %       threshold       a single value or a vector of gene expression
-0020 %                       thresholds, above which genes are considered to be
-0021 %                       "expressed". (optional, by default, the mean expression
-0022 %                       levels of each gene across all tissues in arrayData
-0023 %                       will be used as the threshold values)
-0024 %   tissue              tissue to score for. Should exist in either
-0025 %                       hpaData.tissues or arrayData.tissues
-0026 %   celltype            cell type to score for. Should exist in either
-0027 %                       hpaData.celltypes or arrayData.celltypes for this
-0028 %                       tissue (optional, default is to use the best values
-0029 %                       among all the cell types for the tissue. Use [] if
-0030 %                       you want to supply more arguments)
-0031 %   noGeneScore         score for reactions without genes (optional, default -2)
-0032 %   multipleGeneScoring determines how scores are calculated for reactions
-0033 %                       with several genes ('best' or 'average')
-0034 %                       (optional, default 'best')
-0035 %   multipleCellScoring determines how scores are calculated when several
-0036 %                       cell types are used ('best' or 'average')
-0037 %                       (optional, default 'best')
-0038 %   hpaLevelScores      structure with numerical scores for the expression
-0039 %                       level categories from HPA. The structure should have a
-0040 %                       "names" and a "scores" field (optional, see code for
-0041 %                       default scores)
-0042 %
-0043 %
-0044 %   Output:
-0045 %   rxnScores       scores for each of the reactions in model
-0046 %   geneScores      scores for each of the genes in model. Genes which are
-0047 %                   not in the dataset(s) have -Inf as scores
-0048 %   hpaScores       scores for each of the genes in model if only taking hpaData
-0049 %                   into account. Genes which are not in the dataset(s)
-0050 %                   have -Inf as scores
-0051 %   arrayScores     scores for each of the genes in model if only taking arrayData
-0052 %                   into account. Genes which are not in the dataset(s)
-0053 %                   have -Inf as scores
-0054 %
-0055 % Usage: [rxnScores, geneScores, hpaScores, arrayScores]=scoreModel(model,...
-0056 %               hpaData,arrayData,tissue,celltype,noGeneScore,multipleGeneScoring,...
-0057 %               multipleCellScoring,hpaLevelScores)
-0058 
-0059 if nargin<3
-0060     arrayData=[];
-0061 end
-0062 if nargin<5
-0063     celltype=[];
-0064 else
-0065     celltype=char(celltype);
-0066 end
-0067 if nargin<6
-0068     noGeneScore=-2;
-0069 end
-0070 if nargin<7
-0071     multipleGeneScoring='best';
-0072 else
-0073     multipleGeneScoring=char(multipleGeneScoring);
-0074 end
-0075 if nargin<8
-0076     multipleCellScoring='best';
-0077 else
-0078     multipleCellScoring=char(multipleCellScoring);    
-0079 end
-0080 if nargin<9
-0081     %The first four are for APE, the other ones for staining
-0082     hpaLevelScores.names={'High' 'Medium' 'Low' 'None' 'Strong' 'Moderate' 'Weak' 'Negative' 'Not detected'};
-0083     hpaLevelScores.scores=[20 15 10 -8 20 15 10 -8 -8];
-0084 end
-0085 
-0086 if isempty(hpaData) && isempty(arrayData)
-0087     EM='Must supply hpaData, arrayData or both';
-0088     dispEM(EM);
-0089 end
-0090 if ~strcmpi(multipleGeneScoring,'best') && ~strcmpi(multipleGeneScoring,'average')
-0091     EM='Valid options for multipleGeneScoring are "best" or "average"';
-0092     dispEM(EM);
-0093 end
-0094 if ~strcmpi(multipleCellScoring,'best') && ~strcmpi(multipleCellScoring,'average')
-0095     EM='Valid options for multipleCellScoring are "best" or "average"';
-0096     dispEM(EM);
-0097 end
-0098 
-0099 
-0100 %Throw an error if array data for only one tissue is supplied without
-0101 %specifying threshold values
-0102 if ~isempty(arrayData)
-0103     if numel(unique(arrayData.tissues))<2
-0104         if ~isfield(arrayData,'threshold') || isempty(arrayData.threshold)
-0105             EM='arrayData must contain measurements for at least two celltypes/tissues since the score is calculated based on the expression level compared to the overall average';
-0106             dispEM(EM);
-0107         end
-0108     end
-0109 end
-0110 
-0111 %Process arrayData.threshold if necessary
-0112 if isfield(arrayData,'threshold') && (numel(arrayData.threshold) == 1)
-0113     % if only a single gene threshold value is provided, then just
-0114     % duplicate this value for all genes.
-0115     arrayData.threshold = arrayData.threshold*ones(size(arrayData.genes));
-0116 end
-0117 
-0118 %This is so that the code can ignore which combination of input data that is
-0119 %used
-0120 if isempty(arrayData)
-0121     arrayData.genes={};
-0122     arrayData.tissues={};
-0123     arrayData.celltypes={};
-0124     arrayData.levels=[];
-0125     arrayData.threshold=[];
-0126 end
-0127 if isempty(hpaData)
-0128     hpaData.genes={};
-0129     hpaData.tissues={};
-0130     hpaData.celltypes={};
-0131     hpaData.levels={};
-0132     hpaData.types={};
-0133     hpaData.reliabilities={};
-0134     hpaData.gene2Level=[];
-0135     hpaData.gene2Type=[];
-0136     hpaData.gene2Reliability=[];
-0137 end
-0138 
-0139 %Check that the tissue exists
-0140 if ~ismember(upper(tissue),upper(hpaData.tissues)) && ~ismember(upper(tissue),upper(arrayData.tissues))
-0141     EM='The tissue name does not match';
-0142     dispEM(EM);
-0143 end
-0144 if any(celltype)
-0145     %Check that both data types has cell type defined if that is to be used
-0146     if ~isfield(hpaData,'celltypes') || ~isfield(arrayData,'celltypes')
-0147         EM='Both hpaData and arrayData must contain cell type information if cell type is to be used';
-0148         dispEM(EM);
-0149     end
-0150     if ~ismember(upper(celltype),upper(hpaData.celltypes)) && ~ismember(upper(celltype),upper(arrayData.celltypes))
-0151         EM='The cell type name does not match';
-0152         dispEM(EM);
-0153     end
-0154 end
-0155 
-0156 %Some preprocessing of the structures to speed up a little Remove all
-0157 %tissues that are not the correct one
-0158 J=~strcmpi(hpaData.tissues,tissue);
-0159 
-0160 %If cell type is supplied, then only keep that cell type
-0161 if any(celltype)
-0162     J=J | ~strcmpi(hpaData.celltypes,celltype);
-0163 end
-0164 
-0165 hpaData.tissues(J)=[];
-0166 if isfield(hpaData,'celltypes')
-0167     hpaData.celltypes(J)=[];
-0168 end
-0169 if isfield(hpaData,'gene2Level')
-0170     hpaData.gene2Level(:,J)=[];
-0171 end
-0172 if isfield(hpaData,'gene2Type')
-0173     hpaData.gene2Type(:,J)=[];
-0174 end
-0175 if isfield(hpaData,'gene2Reliability')
-0176     hpaData.gene2Reliability(:,J)=[];
-0177 end
-0178 
-0179 %Remove all genes from the structures that are not in model or that aren't
-0180 %measured in the tissue
-0181 if ~isempty(hpaData.genes) %This should not be necessary, but the summation is a 0x1 matrix and the other is []
-0182     I=~ismember(hpaData.genes,model.genes) | sum(hpaData.gene2Level,2)==0;
-0183 else
-0184     I=[];
-0185 end
-0186 hpaData.genes(I)=[];
-0187 if isfield(hpaData,'gene2Level')
-0188     hpaData.gene2Level(I,:)=[];
-0189 end
-0190 if isfield(hpaData,'gene2Type')
-0191     hpaData.gene2Type(I,:)=[];
-0192 end
-0193 if isfield(hpaData,'gene2Reliability')
-0194     hpaData.gene2Reliability(I,:)=[];
-0195 end
-0196 
-0197 I=strcmpi(arrayData.tissues,tissue);
-0198 %If cell type is supplied, then only keep that cell type
-0199 if any(celltype)
-0200     I=I & strcmpi(arrayData.celltypes,celltype);
-0201 end
-0202 
-0203 %Remove all genes from the structures that are not in model or that aren't
-0204 %measured in the tissue
-0205 J=~ismember(arrayData.genes,model.genes) | myAll(isnan(arrayData.levels(:,I)),2);
-0206 arrayData.genes(J)=[];
-0207 arrayData.levels(J,:)=[];
-0208 if isfield(arrayData,'threshold')
-0209     arrayData.threshold(J) = [];
-0210 end
-0211 
-0212 %Calculate the scores for the arrayData. These scores are calculated for
-0213 %each genes from its fold change between the tissue/celltype(s) in question
-0214 %and all other celltypes. This is a lower quality data than protein
-0215 %abundance, since a gene that is equally highly expressed in all cell types
-0216 %will have a score of 0.0. These scores are therefore only used for genes
-0217 %for which there is no HPA data available. The fold changes are transformed
-0218 %as min(log(x),10) for x>1 and max(log(x),-5) for x<1 in order to have
-0219 %negative scores for lower expressed genes and to scale the scrores to have
-0220 %somewhat lower weights than the HPA scores
-0221 tempArrayLevels=arrayData.levels;
-0222 tempArrayLevels(isnan(tempArrayLevels))=0;
-0223 if isfield(arrayData,'threshold') && ~isempty(arrayData.threshold)
-0224     % if provided, the user-supplied expression threshold value(s) will be
-0225     % used as the "average" expression level to which each gene is
-0226     % compared.
-0227     average=arrayData.threshold;
-0228 else
-0229     average=sum(tempArrayLevels,2)./sum(~isnan(arrayData.levels),2);
-0230 end
-0231 if strcmpi(multipleCellScoring,'best')
-0232     current=max(tempArrayLevels(:,I),[],2);
-0233 else
-0234     current=sum(tempArrayLevels(:,I),2)./sum(~isnan(arrayData.levels(:,I)),2);
-0235 end
-0236 if ~isempty(current)
-0237     aScores=5*log(current./average);
-0238 else
-0239     aScores=[];
-0240 end
-0241 aScores(aScores>0)=min(aScores(aScores>0),10);
-0242 aScores(aScores<0)=max(aScores(aScores<0),-5);
-0243 aScores(isnan(aScores)) = -5;  % NaNs occur when gene expression is zero across all tissues
-0244 
-0245 %Map the HPA levels to scores
-0246 [I, J]=ismember(upper(hpaData.levels),upper(hpaLevelScores.names));
-0247 if ~all(I)
-0248     EM='There are expression level categories that do not match to hpaLevelScores';
-0249     dispEM(EM);
-0250 end
-0251 [K, L, M]=find(hpaData.gene2Level);
-0252 scores=hpaLevelScores.scores(J);
-0253 if strcmpi(multipleCellScoring,'best')
-0254     hScores=max(sparse(K,L,scores(M),numel(hpaData.genes),numel(hpaData.tissues)),[],2);
-0255 else
-0256     hScores=mean(sparse(K,L,scores(M),numel(hpaData.genes),numel(hpaData.tissues)),2);
-0257 end
-0258 
-0259 %Get the scores for the genes, only use HPA if available
-0260 geneScores=inf(numel(model.genes),1)*-1;
-0261 hpaScores=geneScores;
-0262 arrayScores=geneScores;
-0263 
-0264 [I, J]=ismember(model.genes,hpaData.genes);
-0265 hpaScores(I)=hScores(J(I));
-0266 geneScores(I)=hScores(J(I));
-0267 [I, J]=ismember(model.genes,arrayData.genes);
-0268 arrayScores(I)=aScores(J(I));
-0269 geneScores(I & myIsInf(geneScores))=aScores(J(I & myIsInf(geneScores)));
-0270 
-0271 %Remove the genes that have no data from the model
-0272 I=ismember(model.genes,hpaData.genes) | ismember(model.genes,arrayData.genes);
-0273 model.genes(~I)=[];
-0274 model.rxnGeneMat(:,~I)=[];
-0275 
-0276 %Map the genes to the HPA/array genes
-0277 [hpaExist, hpaMap]=ismember(model.genes,hpaData.genes);
-0278 [arrayExist, arrayMap]=ismember(model.genes,arrayData.genes);
-0279 
-0280 %Set the default scores for reactions without genes
-0281 rxnScores=ones(numel(model.rxns),1)*noGeneScore;
-0282 
-0283 %Loop through the reactions and calculate the scores
-0284 for i=1:numel(model.rxns)
-0285     %Check if it has genes
-0286     I=find(model.rxnGeneMat(i,:));
-0287     if any(I)
-0288         %If any of the genes exist in hpaData, then don't use arrayData
-0289         if any(hpaExist(I))
-0290             %At least one gene was found in HPA
-0291             if strcmpi(multipleGeneScoring,'best')
-0292                 rxnScores(i)=max(hScores(hpaMap(I(hpaExist(I)))));
-0293             else
-0294                 rxnScores(i)=mean(hScores(hpaMap(I(hpaExist(I)))));
-0295             end
-0296         else
-0297             %Use array data
-0298             if any(arrayExist(I))
-0299                 %At least one gene was found in the array data
-0300                 if strcmpi(multipleGeneScoring,'best')
-0301                     rxnScores(i)=max(aScores(arrayMap(I(arrayExist(I)))));
-0302                 else
-0303                     rxnScores(i)=mean(aScores(arrayMap(I(arrayExist(I)))));
-0304                 end
-0305             end
-0306         end
-0307     end
-0308 end
-0309 end
-0310 
-0311 %This is because isinf and all returns 0x1 for empty set, which gives a
-0312 %concatenation error. Do like this instead of having many if statements
-0313 function y=myIsInf(x)
-0314 y=isinf(x);
-0315 if isempty(y)
-0316     y=[];
-0317 end
-0318 end
-0319 function y=myAll(x,dim)
-0320 y=all(x,dim);
-0321 if isempty(y)
-0322     y=[];
-0323 end
-0324 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/index.html b/doc/index.html deleted file mode 100644 index c9521aa81..000000000 --- a/doc/index.html +++ /dev/null @@ -1,81 +0,0 @@ - - - - Matlab Index - - - - - - - - - -

Matlab Index

-

Matlab Directories

- -

Matlab Files found in these Directories

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FSEOF emptyOrTextOrCellOfText getObjectiveString ravenCobraWrapper
INITStepDesc emptyOrTextScalar getPathwayDimensions readYAMLmodel
ManualINITTests expandModel getPhylDist removeBadRxns
SBMLFromExcel exportForGit getRxnsFromKEGG removeGenes
addExchangeRxns exportModel getRxnsFromMetaCyc removeIdentifierPrefix
addGenesRaven exportModelToSIF getRxnsInComp removeLowScoreGenes
addIdentifierPrefix exportToExcelFormat getToolboxVersion removeMets
addJavaPaths exportToTabDelimited getTransportRxns removeRavenFromPath
addMets extractMiriam getWSLpath removeReactions
addRavenToUserPath fillGaps getWoLFScores replaceMets
addRxns fillGapsLargeTests groupRxnScores reporterMetabolites
addRxnsGenesMets fillGapsSmallTests guessComposition rescaleModelForINIT
addSpontaneousRxns findGeneDeletions haveFlux reverseRxns
addTransport findRAVENroot hmmerTests runDynamicFBA
analyzeSampling fitParameters importExcelModel runINIT
blastPlusTests fitTasks importExportTests runPhenotypePhasePlane
buildEquation followChanged importModel runProductionEnvelope
canConsume followFluxes linkMetaCycKEGGRxns runRAVENtests
canProduce ftINIT loadSheet runRobustnessAnalysis
cdhitTests ftINITFillGaps loadWorkbook runSimpleOptKnock
changeGeneAssoc ftINITFillGapsForAllTasks mafftTests scoreComplexModel
changeGrRules ftINITFillGapsMILP makeFakeBlastStructure scoreModel
changeRxns ftINITInternalAlg makeSomething setColorToMapRxns
checkFileExistence gapReport mapCompartments setExchangeBounds
checkFunctionUniqueness generateNewIds mapPathwayRxnNames setOmicDataToRxns
checkInstallation getAllRxnsFromGenes markPathwayWithExpression setParam
checkModelStruct getAllSubGraphs markPathwayWithFluxes setRavenSolver
checkProduction getAllowedBounds mergeCompartments setTitle
checkRxn getBlast mergeLinear simplifyModel
checkSolution getBlastFromExcel mergeModels solveLP
checkTasks getColorCodes mergeModelsTests solveQP
checkTasksTests getDiamond miriamTests solverTests
cleanSheet getElementalBalance modelAbilitiesTests sortIdentifiers
closeModel getEnzymesFromMetaCyc modelConversionTests sortModel
colorPathway getEssentialRxns modelCurationTests standardizeGrRules
colorSubsystem getExchangeRxns modelSortingTests standardizeModelFieldOrder
combineMetaCycKEGGModels getExprForRxnScore optimizeProb startup
compareMultipleModels getExpressionStructure parallelPoolRAVEN tinitTests
compareRxnsGenesMetsComps getFluxZ parseFormulas trimPathway
constructEquations getFullPath parseHPA tutorial1
constructMultiFasta getGenesFromGrRules parseHPArna tutorial2
constructPathwayFromCelldesigner getGenesFromKEGG parseRxnEqu tutorial2_solutions
constructS getINITModel parseScores tutorial3
consumeSomething getINITSteps parseTaskList tutorial3_solutions
contractModel getIndexes permuteModel tutorial4
convertCharArray getKEGGModelForOrganism plotAdditionalInfo tutorial4_solutions
convertToIrrev getMD5Hash plotLabels tutorial5
copyToComps getMetaCycModelForOrganism predictLocalization tutorial6
deleteUnusedGenes getMetsFromKEGG prepINITModel updateDocumentation
diamondTests getMetsFromMetaCyc printFluxes writeSheet
dispEM getMetsInComp printModel writeYAMLmodel
drawMap getMinNrFluxes printModelStats
drawPathway getModelFromHomology printOrange
editMiriam getModelFromKEGG qMOMA
emptyOrLogicalScalar getModelFromMetaCyc randomSampling
- - -
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/installation/addRavenToUserPath.html b/doc/installation/addRavenToUserPath.html deleted file mode 100644 index aeef3805d..000000000 --- a/doc/installation/addRavenToUserPath.html +++ /dev/null @@ -1,98 +0,0 @@ - - - - Description of addRavenToUserPath - - - - - - - - - -
Home > installation > addRavenToUserPath.m
- - - -

addRavenToUserPath -

- -

PURPOSE ^

-
This function writes a startup.m file in the userpath, adding RAVEN (and
- -

SYNOPSIS ^

-
function addRavenToUserPath(overwrite)
- -

DESCRIPTION ^

-
 This function writes a startup.m file in the userpath, adding RAVEN (and
- all subdirectories) to the path each time Matlab is started.
- This function is useful if the user has no rights to save paths to the
- pathdef.m file in the matlabroot, for instance due to a lack of admin
- rights. As the startup.m file in the userpath automatically runs with
- each Matlab start, the paths are automatically loaded.
-
-   overwrite       logical, whether startup.m in the userpath should
-                   overwritten (otherwise the RAVEN paths are appended)
-                   (optional, default true)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function addRavenToUserPath(overwrite)
-0002 % This function writes a startup.m file in the userpath, adding RAVEN (and
-0003 % all subdirectories) to the path each time Matlab is started.
-0004 % This function is useful if the user has no rights to save paths to the
-0005 % pathdef.m file in the matlabroot, for instance due to a lack of admin
-0006 % rights. As the startup.m file in the userpath automatically runs with
-0007 % each Matlab start, the paths are automatically loaded.
-0008 %
-0009 %   overwrite       logical, whether startup.m in the userpath should
-0010 %                   overwritten (otherwise the RAVEN paths are appended)
-0011 %                   (optional, default true)
-0012 
-0013 if nargin<1
-0014     overwrite=true;
-0015 end
-0016 
-0017 % Get current RAVEN directory
-0018 ravenDir=findRAVENroot();
-0019 
-0020 % Lists all subdirectories
-0021 subpath=regexp(genpath(ravenDir),pathsep,'split');
-0022 % Remove .git and doc folders
-0023 pathsToKeep=cellfun(@(x) isempty(strfind(x,'.git')),subpath) & cellfun(@(x) isempty(strfind(x,'doc')),subpath);
-0024 % Only keep useful paths
-0025 subpath = subpath(pathsToKeep);
-0026 subpath = subpath(1:end-1); % Remove last entry, is empty field
-0027 
-0028 % Write startup.m file
-0029 if overwrite
-0030     fid=fopen(fullfile(userpath,'startup.m'),'w');
-0031     fprintf(fid,'%sn','%%% RAVEN path');
-0032 else
-0033     fid=fopen(fullfile(userpath,'startup.m'),'a');
-0034     fprintf(fid,'n%sn','%%% RAVEN path');
-0035 end
-0036 fprintf(fid,'%sn',strcat('addpath(''',subpath{1},''',...'));
-0037 for i=2(length(subpath)-1)
-0038     fprintf(fid,'t%sn',strcat('''',subpath{i},''',...'));
-0039 end
-0040 fprintf(fid,'t%s',strcat('''',subpath{length(subpath)},''');'));
-0041 fclose(fid);
-0042 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/installation/checkFunctionUniqueness.html b/doc/installation/checkFunctionUniqueness.html deleted file mode 100644 index 5b55f77af..000000000 --- a/doc/installation/checkFunctionUniqueness.html +++ /dev/null @@ -1,161 +0,0 @@ - - - - Description of checkFunctionUniqueness - - - - - - - - - -
Home > installation > checkFunctionUniqueness.m
- - - -

checkFunctionUniqueness -

- -

PURPOSE ^

-
checkFunctionUniqueness
- -

SYNOPSIS ^

-
function status = checkFunctionUniqueness(altDirs)
- -

DESCRIPTION ^

-
 checkFunctionUniqueness
-   Checks whether RAVEN toolbox functions are unique across other
-   toolboxes or user-created functions accessible in Matlab pathlist.
-
- Input:
-   altDirs     cell array of alternative directories with functions,
-               should only be specified if this function is used for other
-               purposes, NOT when looking for RAVEN toolbox functions.
-
- Output:
-   status      true if all functions are unique, otherwise false
-
- Usage: checkFunctionUniqueness()
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function status = checkFunctionUniqueness(altDirs)
-0002 % checkFunctionUniqueness
-0003 %   Checks whether RAVEN toolbox functions are unique across other
-0004 %   toolboxes or user-created functions accessible in Matlab pathlist.
-0005 %
-0006 % Input:
-0007 %   altDirs     cell array of alternative directories with functions,
-0008 %               should only be specified if this function is used for other
-0009 %               purposes, NOT when looking for RAVEN toolbox functions.
-0010 %
-0011 % Output:
-0012 %   status      true if all functions are unique, otherwise false
-0013 %
-0014 % Usage: checkFunctionUniqueness()
-0015 
-0016 if nargin<1
-0017     %Get the RAVEN path
-0018     ravenDir=findRAVENroot();
-0019     
-0020     %Now getting all RAVEN functions recursively;
-0021     temp_res1=dir([ravenDir '/*/*.m']);
-0022     temp_res2=dir([ravenDir '/*/*/*.m']);
-0023     
-0024     ravenFunctions={temp_res1.name,temp_res2.name}';
-0025 else
-0026     if ispc
-0027         splitChar = ';';
-0028     else
-0029         splitChar = ':';
-0030     end
-0031     altDirs = strsplit(altDirs,splitChar)';
-0032     ravenFunctions={};
-0033     for i=1:numel(altDirs)
-0034         temp_res=dir(fullfile(char(altDirs(i)),'*.m'));
-0035         ravenFunctions = [ravenFunctions, temp_res.name];
-0036     end
-0037     ravenFunctions=ravenFunctions';
-0038     ravenDir=altDirs;
-0039 end
-0040 
-0041 %startup.m is not a normal function, any startup.m in the path should run
-0042 %during startup, so duplicate use of this name is fine
-0043 ravenFunctions=ravenFunctions(~ismember(ravenFunctions,'startup.m'));
-0044 
-0045 %Getting all the paths added to Matlab
-0046 if ispc
-0047     matlabPaths=regexp(path, ';', 'split')';
-0048 elseif isunix
-0049     matlabPaths=regexp(path, ':', 'split')';
-0050 end
-0051 
-0052 overlapPath={};
-0053 overlapFunctions={};
-0054 multiRaven=false;
-0055 multiFunction=false;
-0056 
-0057 for i=1:numel(matlabPaths)
-0058     if ~startsWith(matlabPaths{i},ravenDir)
-0059         temp_res=dir([matlabPaths{i} '/*.m']);
-0060         if ~isempty(temp_res)
-0061             pathFunctions={temp_res.name}';
-0062         else
-0063             pathFunctions='';
-0064         end
-0065         if ~isempty(pathFunctions) && ~any(ismember('Contents.m',pathFunctions))
-0066             if any(ismember(ravenFunctions,pathFunctions))
-0067                 if sum(ismember(ravenFunctions,pathFunctions))>(numel(ravenFunctions)/4)
-0068                     multiRaven=true;
-0069                 else
-0070                     multiFunction=true;
-0071                     overlapPath = [overlapPath, matlabPaths(i)];
-0072                     overlapFunctions = [overlapFunctions, {ravenFunctions(ismember(ravenFunctions,pathFunctions))}];
-0073                 end
-0074             end
-0075         end
-0076     end
-0077 end
-0078 
-0079 if multiRaven==true || multiFunction == true
-0080         if nargout > 0
-0081             status = false;
-0082         else
-0083             fprintf('Fail\n')
-0084         end
-0085     if multiRaven==true && nargin < 1
-0086         error(['Multiple RAVEN versions detected in MATLAB path. Remove all ',...
-0087                'RAVEN directories from the MATLAB path with removeRavenFromPath(), ',...
-0088                'or manually remove them. Afterwards, re-run checkInstallation']);
-0089     elseif multiFunction == true
-0090         for i=1:numel(overlapPath)
-0091             fprintf(['   Duplicate functions in ',regexprep(overlapPath{i},'(\\)','\\$1'),'\n']);
-0092             fprintf(['     ' strjoin(overlapFunctions{i},'\n     ') '\n']);
-0093         end
-0094     fprintf('   Resolve conflicting functions to avoid unexpected behaviour\n');
-0095     end
-0096 else
-0097     if nargout > 0
-0098         status = true;
-0099     else
-0100         fprintf('Pass\n')
-0101     end
-0102 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/installation/checkInstallation.html b/doc/installation/checkInstallation.html deleted file mode 100644 index 4034591ce..000000000 --- a/doc/installation/checkInstallation.html +++ /dev/null @@ -1,481 +0,0 @@ - - - - Description of checkInstallation - - - - - - - - - -
Home > installation > checkInstallation.m
- - - -

checkInstallation -

- -

PURPOSE ^

-
checkInstallation
- -

SYNOPSIS ^

-
function [currVer, installType] = checkInstallation(developMode,checkBinaries)
- -

DESCRIPTION ^

-
 checkInstallation
-   The purpose of this function is to check if all necessary functions are
-   installed and working. It also checks whether there are any functions
-   with overlapping names between RAVEN and other toolboxes or
-   user-defined functions, which are accessible from MATLAB pathlist
-
- Input: 
-   developMode     logical indicating development mode, which includes
-                   testing of binaries that are required to update KEGG
-                   HMMs (optional, default false). If 'versionOnly' is
-                   specified, only the version is reported as currVer, no
-                   further installation or tests are performed.
-   checkBinaries   logical whether non-developMode binaries should be
-                   checked for functionality. If false, it overwrites
-                   developMode. Default true.
-
- Output:
-   currVer         current RAVEN version
-   installType     how RAVEN is installed
-                   0:  via git (as .git folder is found)
-                   1:  as MATLAB Add-On
-                   2:  neither of the above, direct download of ZIP file
-                   This matches the installations mentioned in the wiki:
-                   https://github.com/SysBioChalmers/RAVEN/wiki/Installation
-                   0 = advanced / 1 = easy / 2 = medium
-
- Usage: [currVer, installType] = checkInstallation(developMode)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 function [currVer, installType] = checkInstallation(developMode,checkBinaries)
-0002 % checkInstallation
-0003 %   The purpose of this function is to check if all necessary functions are
-0004 %   installed and working. It also checks whether there are any functions
-0005 %   with overlapping names between RAVEN and other toolboxes or
-0006 %   user-defined functions, which are accessible from MATLAB pathlist
-0007 %
-0008 % Input:
-0009 %   developMode     logical indicating development mode, which includes
-0010 %                   testing of binaries that are required to update KEGG
-0011 %                   HMMs (optional, default false). If 'versionOnly' is
-0012 %                   specified, only the version is reported as currVer, no
-0013 %                   further installation or tests are performed.
-0014 %   checkBinaries   logical whether non-developMode binaries should be
-0015 %                   checked for functionality. If false, it overwrites
-0016 %                   developMode. Default true.
-0017 %
-0018 % Output:
-0019 %   currVer         current RAVEN version
-0020 %   installType     how RAVEN is installed
-0021 %                   0:  via git (as .git folder is found)
-0022 %                   1:  as MATLAB Add-On
-0023 %                   2:  neither of the above, direct download of ZIP file
-0024 %                   This matches the installations mentioned in the wiki:
-0025 %                   https://github.com/SysBioChalmers/RAVEN/wiki/Installation
-0026 %                   0 = advanced / 1 = easy / 2 = medium
-0027 %
-0028 % Usage: [currVer, installType] = checkInstallation(developMode)
-0029 
-0030 if nargin<1
-0031     developMode=false;
-0032 end
-0033 if nargin<2
-0034     checkBinaries=true;
-0035 end
-0036 if ischar(developMode) && strcmp(developMode,'versionOnly')
-0037     versionOnly = true;
-0038 else
-0039     versionOnly = false;
-0040 end
-0041 
-0042 %Get the RAVEN path
-0043 [ST, I]=dbstack('-completenames');
-0044 [ravenDir,~,~]=fileparts(fileparts(ST(I).file));
-0045 
-0046 installType = 2; % If neither git nor add-on, then ZIP was downloaded
-0047 addList = matlab.addons.installedAddons;
-0048 if isfolder(fullfile(ravenDir,'.git'))
-0049     installType = 0;
-0050 elseif any(strcmp(addList.Name,'RAVEN Toolbox'))
-0051     installType = 1;
-0052 end
-0053 
-0054 % Do not print first few lines if only version should be reported
-0055 if ~versionOnly
-0056     fprintf('\n*** THE RAVEN TOOLBOX ***\n\n');
-0057     %Print the RAVEN version if it is not the development version
-0058     fprintf(myStr(' > Installation type',40));
-0059     switch installType
-0060         case 0
-0061             fprintf('Advanced (via git)\n');
-0062         case 1
-0063             fprintf('Easy (as MATLAB Add-On)\n');
-0064         case 2
-0065             fprintf('Medium (as downloaded ZIP file)\n');
-0066     end
-0067     fprintf(myStr(' > Installing from location',40));
-0068     fprintf('%s\n',ravenDir)
-0069     fprintf(myStr(' > Checking RAVEN release',40));
-0070 end
-0071                        
-0072 if exist(fullfile(ravenDir,'version.txt'), 'file') == 2
-0073     currVer = fgetl(fopen(fullfile(ravenDir,'version.txt')));
-0074     fclose('all');
-0075     if ~versionOnly
-0076         fprintf([currVer '\n']);
-0077         try
-0078             newVer=strtrim(webread('https://raw.githubusercontent.com/SysBioChalmers/RAVEN/main/version.txt'));
-0079             newVerNum=str2double(strsplit(newVer,'.'));
-0080             currVerNum=str2double(strsplit(currVer,'.'));
-0081             for i=1:3
-0082                 if currVerNum(i)<newVerNum(i)
-0083                     fprintf(myStr('   > Latest RAVEN release available',40))
-0084                     printOrange([newVer,'\n'])
-0085                     switch installType
-0086                         case 0
-0087                             printOrange('     Run git pull in your favourite git client\n')
-0088                             printOrange('     to get the latest RAVEN release\n');
-0089                         case 1
-0090                             printOrange(myStr('     Instructions on how to upgrade',40))
-0091                             fprintf('<a href="https://github.com/SysBioChalmers/RAVEN/wiki/Installation#upgrade-raven-after-easy-installation">here</a>\n');
-0092                         case 2
-0093                             printOrange(myStr('     Instructions on how to upgrade',40))
-0094                             fprintf('<a href="https://github.com/SysBioChalmers/RAVEN/wiki/Installation#upgrade-raven-after-medium-installation">here</a>\n');                            
-0095                     end
-0096                     break
-0097                 elseif i==3
-0098                     fprintf('   > You are running the latest RAVEN release\n');
-0099                 end
-0100             end
-0101         catch
-0102             fprintf(myStr('   > Checking for latest RAVEN release',40))
-0103             printOrange('Fail\n');
-0104             printOrange('     Cannot reach GitHub for release info\n');
-0105         end
-0106     end
-0107 else
-0108     currVer = 'develop';
-0109     if ~versionOnly; fprintf('DEVELOPMENT\n'); end
-0110 end
-0111 if strcmp(developMode,'versionOnly')
-0112     return;
-0113 end
-0114 
-0115 fprintf(myStr(' > Checking MATLAB release',40))
-0116 fprintf([version('-release') '\n'])
-0117 fprintf(myStr(' > Checking system architecture',40))
-0118 fprintf([computer('arch'),'\n'])
-0119 
-0120 fprintf(myStr(' > Set RAVEN in MATLAB path',40))
-0121 subpath=regexp(genpath(ravenDir),pathsep,'split'); %List all subdirectories
-0122 pathsToKeep=cellfun(@(x) ~contains(x,'.git'),subpath) & cellfun(@(x) ~contains(x,'doc'),subpath);
-0123 try
-0124     addpath(strjoin(subpath(pathsToKeep),pathsep));
-0125     fprintf('Pass\n');
-0126     fprintf(myStr(' > Save MATLAB path',40))
-0127     try
-0128         savepath
-0129         fprintf('Pass\n')   
-0130     catch
-0131         printOrange('Fail\n')
-0132         fprintf(['   You might have to rerun checkInstallation again\n'...
-0133                  '   next time you start up MATLAB\n'])        
-0134     end
-0135 catch
-0136     printOrange('Fail\n')
-0137 end
-0138 fprintf(myStr(' > Store RAVEN path as MATLAB pref',40))
-0139 try
-0140     setpref('RAVEN','ravenPath',ravenDir);
-0141     fprintf('Pass\n');
-0142 catch
-0143     printOrange('Fail\n')
-0144 end
-0145 
-0146 if isunix
-0147     fprintf(myStr('   > Make binaries executable',40))
-0148     status = makeBinaryExecutable(ravenDir);
-0149     if status == 0
-0150         fprintf('Pass\n')
-0151     else
-0152         printOrange('Fail\n')
-0153     end
-0154 end
-0155 
-0156 %Check if it is possible to parse an Excel file
-0157 fprintf('\n=== Model import and export ===\n');
-0158 fprintf(myStr(' > Add Java paths for Excel format',40))
-0159 try
-0160     %Add the required classes to the static Java path if not already added
-0161     addJavaPaths();
-0162     fprintf('Pass\n')
-0163 catch
-0164     printOrange('Fail\n')
-0165 end
-0166 fprintf(myStr(' > Checking libSBML version',40))
-0167 try
-0168     evalc('importModel(fullfile(ravenDir,''tutorial'',''empty.xml''))');
-0169     try
-0170         libSBMLver=OutputSBML_RAVEN; % Only works in libSBML 5.17.0+
-0171         fprintf([libSBMLver.libSBML_version_string '\n']);
-0172     catch
-0173         printOrange('Fail\n')
-0174         fprintf('   An older libSBML version was found, update to version 5.17.0 or higher for a significant improvement of model import\n');
-0175     end
-0176 catch
-0177     printOrange('Fail\n')
-0178     fprintf('   Download libSBML from http://sbml.org/Software/libSBML/Downloading_libSBML and add to MATLAB path\n');
-0179 end
-0180 fprintf(' > Checking model import and export\n')
-0181 [~,res]=evalc("runtests('importExportTests.m');");
-0182 
-0183 fprintf(myStr('   > Import Excel format',40))
-0184 if res(1).Passed == 1
-0185     fprintf('Pass\n')
-0186 else
-0187     printOrange('Fail\n')
-0188     if any(strcmpi(addList.Name,'Text Analytics Toolbox'))
-0189         fprintf(['   Excel import/export is incompatible with MATLAB Text Analytics Toolbox.\n' ...
-0190                  '   Further instructions => https://github.com/SysBioChalmers/RAVEN/issues/55#issuecomment-1514369299\n'])
-0191     end
-0192 end
-0193 
-0194 fprintf(myStr('   > Export Excel format',40))
-0195 if res(4).Passed == 1
-0196     fprintf('Pass\n')
-0197 else
-0198     printOrange('Fail\n')
-0199 end
-0200 
-0201 fprintf(myStr('   > Import SBML format',40))
-0202 if res(2).Passed == 1
-0203     fprintf('Pass\n')
-0204 else
-0205     printOrange('Fail\n')
-0206 end
-0207 
-0208 fprintf(myStr('   > Export SBML format',40))
-0209 if res(5).Passed == 1
-0210     fprintf('Pass\n')
-0211 else
-0212     printOrange('Fail\n')
-0213 end
-0214 
-0215 fprintf(myStr('   > Import YAML format',40))
-0216 if res(3).Passed == 1
-0217     fprintf('Pass\n')
-0218 else
-0219     printOrange('Fail\n')
-0220 end
-0221 
-0222 fprintf(myStr('   > Export YAML format',40))
-0223 if res(6).Passed == 1
-0224     fprintf('Pass\n')
-0225 else
-0226     printOrange('Fail\n')
-0227 end
-0228 
-0229 fprintf('\n=== Model solvers ===\n');
-0230 
-0231 %Get current solver. Set it to 'none', if it is not set
-0232 fprintf(' > Checking for LP solvers\n')
-0233 [~,res]=evalc("runtests('solverTests.m');");
-0234 
-0235 fprintf(myStr('   > glpk',40))
-0236 if res(1).Passed == 1
-0237     fprintf('Pass\n')
-0238 else
-0239     printOrange('Fail\n')
-0240 end
-0241 
-0242 fprintf(myStr('   > gurobi',40))
-0243 if res(2).Passed == 1
-0244     fprintf('Pass\n')
-0245 else
-0246     printOrange('Fail\n')
-0247 end
-0248 
-0249 fprintf(myStr('   > scip',40))
-0250 if res(3).Passed == 1
-0251     fprintf('Pass\n')
-0252 else
-0253     printOrange('Fail\n')
-0254 end
-0255 
-0256 fprintf(myStr('   > cobra',40))
-0257 if res(4).Passed == 1
-0258     fprintf('Pass\n')
-0259 else
-0260     printOrange('Fail\n')
-0261 end
-0262 fprintf(myStr(' > Set RAVEN solver',40))
-0263 try
-0264     oldSolver=getpref('RAVEN','solver');
-0265     solverIdx=find(strcmp(oldSolver,{'glpk','gurobi','scip','cobra'}));
-0266 catch
-0267     solverIdx=0;
-0268 end
-0269 % Do not change old solver if functional
-0270 if solverIdx~=0 && res(solverIdx).Passed == 1
-0271     fprintf([oldSolver '\n'])
-0272 % Order of preference: gurobi > glpk > scip > cobra
-0273 elseif res(2).Passed == 1
-0274     fprintf('gurobi\n')
-0275     setRavenSolver('gurobi');
-0276 elseif res(1).Passed == 1
-0277     fprintf('glpk\n')
-0278     setRavenSolver('glpk');
-0279 elseif res(3).Passed == 1
-0280     fprintf('scip\n')
-0281     setRavenSolver('scip');    
-0282 elseif res(4).Passed == 1
-0283     fprintf('cobra\n')
-0284     setRavenSolver('cobra');
-0285 else
-0286     fprintf('None, no functional solvers\n')
-0287     fprintf('    The glpk should always be working, check your RAVEN installation to make sure all files are present\n')
-0288 end
-0289 
-0290 fprintf('\n=== Essential binary executables ===\n');
-0291 if ~checkBinaries
-0292     printOrange('    Skipping check of binary executables\n')
-0293 else
-0294     fprintf(myStr(' > Checking BLAST+',40))
-0295     [~,res]=evalc("runtests('blastPlusTests.m');");
-0296     res=interpretResults(res);
-0297     if res==false
-0298         fprintf('   This is essential to run getBlast()\n')
-0299     end
-0300 
-0301     fprintf(myStr(' > Checking DIAMOND',40))
-0302     [~,res]=evalc("runtests('diamondTests.m');");
-0303     res=interpretResults(res);
-0304     if res==false
-0305         fprintf('   This is essential to run the getDiamond()\n')
-0306     end
-0307 
-0308     fprintf(myStr(' > Checking HMMER',40))
-0309     [~,res]=evalc("runtests('hmmerTests.m')");
-0310     res=interpretResults(res);
-0311     if res==false
-0312         fprintf(['   This is essential to run getKEGGModelFromHomology()\n'...
-0313             '   when using a FASTA file as input\n'])
-0314         % On Windows, HMMER runs through Windows Subsystem for Linux
-0315         if ispc
-0316             [status,~]=system('wsl -e true');
-0317             if status~=0
-0318                 printOrange(['   WSL with a Linux distribution is not available, but HMMER\n'...
-0319                     '   requires it on Windows. Install it with "wsl --install" in\n'...
-0320                     '   a Command Prompt, restart, and rerun checkInstallation\n'])
-0321             end
-0322         end
-0323     end
-0324 
-0325     if developMode
-0326         fprintf('\n=== Development binary executables ===\n');
-0327         fprintf('NOTE: These binaries are only required when using KEGG FTP dump files in getKEGGModelForOrganism\n');
-0328 
-0329         fprintf(myStr(' > Checking CD-HIT',40))
-0330         [~,res]=evalc("runtests('cdhitTests.m');");
-0331         interpretResults(res);
-0332 
-0333         fprintf(myStr(' > Checking MAFFT',40))
-0334         [~,res]=evalc("runtests('mafftTests.m');");
-0335         interpretResults(res);
-0336     end
-0337 end
-0338 
-0339 fprintf('\n=== Compatibility ===\n');
-0340 fprintf(myStr(' > Checking function uniqueness',40))
-0341 checkFunctionUniqueness();
-0342 
-0343 fprintf('\n*** checkInstallation complete ***\n');
-0344 end
-0345 
-0346 function res = interpretResults(results)
-0347 if results.Failed==0 && results.Incomplete==0
-0348     fprintf('Pass\n');
-0349     res=true;
-0350 else
-0351     printOrange('Fail\n')
-0352     fprintf('   Download/compile the binary and rerun checkInstallation\n');
-0353     res=false;
-0354 end
-0355 end
-0356 
-0357 function str = myStr(InputStr,len)
-0358 str=InputStr;
-0359 lenDiff = len - length(str);
-0360 if lenDiff < 0
-0361     warning('String too long');
-0362 else
-0363     str = [str blanks(lenDiff)];
-0364 end
-0365 end
-0366 
-0367 function status = makeBinaryExecutable(ravenDir)
-0368 % This function is required to run when RAVEN is downloaded as MATLAB
-0369 % Add-On, in which case the file permissions are not correctly set
-0370 if ispc
-0371     status = 0; % No need to run on Windows
-0372     return;
-0373 end
-0374 binDir = fullfile(ravenDir,'software');
-0375 
-0376 binList = {fullfile(binDir,'blast+','blastp');                      fullfile(binDir,'blast+','blastp.mac');
-0377            fullfile(binDir,'blast+','makeblastdb');                 fullfile(binDir,'blast+','makeblastdb.mac');
-0378            fullfile(binDir,'cd-hit','cd-hit');                      fullfile(binDir,'cd-hit','cd-hit.mac');
-0379            fullfile(binDir,'diamond','diamond');                    fullfile(binDir,'diamond','diamond.mac');
-0380            fullfile(binDir,'hmmer','hmmbuild');                     fullfile(binDir,'hmmer','hmmbuild.mac');
-0381            fullfile(binDir,'hmmer','hmmsearch');                    fullfile(binDir,'hmmer','hmmsearch.mac');
-0382            fullfile(binDir,'GLPKmex','glpkcc.mexa64');              fullfile(binDir,'GLPKmex','glpkcc.mexglx');                 fullfile(binDir,'GLPKmex','glpkcc.mexmaci64');              fullfile(binDir,'GLPKmex','glpkcc.mexmaca64');
-0383            fullfile(binDir,'libSBML','TranslateSBML_RAVEN.mexa64'); fullfile(binDir,'libSBML','TranslateSBML_RAVEN.mexglx');    fullfile(binDir,'libSBML','TranslateSBML_RAVEN.mexmaci64');  fullfile(binDir,'libSBML','TranslateSBML_RAVEN.mexmaca64');
-0384            fullfile(binDir,'libSBML','OutputSBML_RAVEN.mexa64');    fullfile(binDir,'libSBML','OutputSBML_RAVEN.mexglx');       fullfile(binDir,'libSBML','OutputSBML_RAVEN.mexmaci64');     fullfile(binDir,'libSBML','OutputSBML_RAVEN.mexmaca64');
-0385            fullfile(binDir,'mafft','mafft-linux64','mafft.bat');
-0386            fullfile(binDir,'mafft','mafft-mac','mafft.bat');};
-0387 
-0388 for i=1:numel(binList)
-0389     [status,cmdout] = system(['chmod +x "' binList{i} '"']);
-0390     if status ~= 0
-0391         warning('Failed to make %s executable: %s ',binList{i},strip(cmdout))
-0392     end
-0393 end
-0394 end
-0395 
-0396 function printOrange(stringToPrint)
-0397 % printOrange
-0398 %   Duplicate of RAVEN/core/printOrange is also kept here, as this function
-0399 %   should be able to run before adding RAVEN to the MATLAB path.
-0400 try useDesktop = usejava('desktop'); catch, useDesktop = false; end
-0401 if useDesktop
-0402     fprintf(['[\b' stringToPrint,']\b'])
-0403 else
-0404     fprintf(stringToPrint)
-0405 end
-0406 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/installation/index.html b/doc/installation/index.html deleted file mode 100644 index 8eef48a3a..000000000 --- a/doc/installation/index.html +++ /dev/null @@ -1,29 +0,0 @@ - - - - Index for Directory installation - - - - - - - - - - -
< Master indexIndex for installation >
- -

Index for installation

- -

Matlab files in this directory:

- -
 addRavenToUserPathThis function writes a startup.m file in the userpath, adding RAVEN (and
 checkFunctionUniquenesscheckFunctionUniqueness
 checkInstallationcheckInstallation
 removeRavenFromPathremoveRavenFromPath
- - - - -
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/installation/removeRavenFromPath.html b/doc/installation/removeRavenFromPath.html deleted file mode 100644 index 1f81cf8ae..000000000 --- a/doc/installation/removeRavenFromPath.html +++ /dev/null @@ -1,97 +0,0 @@ - - - - Description of removeRavenFromPath - - - - - - - - - -
Home > installation > removeRavenFromPath.m
- - - -

removeRavenFromPath -

- -

PURPOSE ^

-
removeRavenFromPath
- -

SYNOPSIS ^

-
function removeRavenFromPath()
- -

DESCRIPTION ^

-
 removeRavenFromPath
-   This function removes all RAVEN directories and subdirectories from the
-   MATLAB path. This function only removes RAVEN from the MATLAB path, it
-   does not delete the RAVEN folder itself. If RAVEN was installed as
-   MATLAB Add-On, the user is prompted to instead uninstall RAVEN via the
-   Add-On Manager.
-
- Usage: removeRavenFromPath()
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function removeRavenFromPath()
-0002 % removeRavenFromPath
-0003 %   This function removes all RAVEN directories and subdirectories from the
-0004 %   MATLAB path. This function only removes RAVEN from the MATLAB path, it
-0005 %   does not delete the RAVEN folder itself. If RAVEN was installed as
-0006 %   MATLAB Add-On, the user is prompted to instead uninstall RAVEN via the
-0007 %   Add-On Manager.
-0008 %
-0009 % Usage: removeRavenFromPath()
-0010 
-0011 % Check for installation as Add-On
-0012 addList = matlab.addons.installedAddons;
-0013 if any(strcmp(addList.Name,'RAVEN Toolbox'))
-0014     error(['RAVEN is installed as MATLAB Add-On. You should uninstall RAVEN via '...
-0015         'the Add-On Manager instead. Once uninstalled, you may attempt to run '...
-0016         'removeRavenFromPath again to remove any potential remaining RAVEN installations.'])
-0017 end
-0018 
-0019 % Get current paths
-0020 currPath  = transpose(strsplit(path(),{';',':'}));
-0021 ravenPath = false(numel(currPath),1);
-0022 for i=1:numel(currPath)
-0023     dirCont = ls(currPath{i});
-0024     dirCont = cellstr(dirCont(3:end,:));
-0025     if any(contains(dirCont,{'ravenCobraWrapper.m','makeFakeBlastStructure.m','setRavenSolver.m'})) % A few (hopefully) unique RAVEN functions
-0026         ravenPath(i)=true;
-0027     end
-0028 end
-0029 
-0030 ravenPath = unique(regexprep(currPath(ravenPath),'(\\|\/)((external)|(struct_conversion)|(solver))',''));
-0031 addOnDir = contains(ravenPath,'MATLAB Add-Ons');
-0032 if any(addOnDir)
-0033     warning(['RAVEN is installed as MATLAB Add-On at the following directory, but MATLAB '...
-0034         'somehow does not recognize this installation. You are advised to manually delete '...
-0035         'the directory to remove any RAVEN remnants: ' ravenPath{addOnDir}]);
-0036 end
-0037 ravenSubDirs = currPath(startsWith(currPath,ravenPath));
-0038 % Remove from path
-0039 if ~isempty(ravenSubDirs)
-0040     rmpath(ravenSubDirs{:});
-0041     savepath;
-0042 end
-0043 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/io/SBMLFromExcel.html b/doc/io/SBMLFromExcel.html deleted file mode 100644 index 4565e9250..000000000 --- a/doc/io/SBMLFromExcel.html +++ /dev/null @@ -1,94 +0,0 @@ - - - - Description of SBMLFromExcel - - - - - - - - - -
Home > io > SBMLFromExcel.m
- - - -

SBMLFromExcel -

- -

PURPOSE ^

-
SBMLFromExcel
- -

SYNOPSIS ^

-
function SBMLFromExcel(fileName, outputFileName,toCOBRA,printWarnings)
- -

DESCRIPTION ^

-
 SBMLFromExcel
-   Converts a model in the Excel format to SBML
-
-   fileName        the Excel file
-   outputFileName  the SBML file
-   toCOBRA         true if the model should be saved in COBRA Toolbox
-                   format. Only limited support at the moment (optional,
-                   default false)
-   printWarnings   true if warnings about model issues should be reported
-                   (optional, default true)
-
-   For a detailed description of the file format, see the supplied manual.
-
- Usage: SBMLFromExcel(fileName,outputFileName,toCOBRA,printWarnings)
-
-   NOTE: This is just a wrapper function for importExcelModel, printModelStats
-   and exportModel. Use those functions directly for greater control.
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function SBMLFromExcel(fileName, outputFileName,toCOBRA,printWarnings)
-0002 % SBMLFromExcel
-0003 %   Converts a model in the Excel format to SBML
-0004 %
-0005 %   fileName        the Excel file
-0006 %   outputFileName  the SBML file
-0007 %   toCOBRA         true if the model should be saved in COBRA Toolbox
-0008 %                   format. Only limited support at the moment (optional,
-0009 %                   default false)
-0010 %   printWarnings   true if warnings about model issues should be reported
-0011 %                   (optional, default true)
-0012 %
-0013 %   For a detailed description of the file format, see the supplied manual.
-0014 %
-0015 % Usage: SBMLFromExcel(fileName,outputFileName,toCOBRA,printWarnings)
-0016 %
-0017 %   NOTE: This is just a wrapper function for importExcelModel, printModelStats
-0018 %   and exportModel. Use those functions directly for greater control.
-0019 fileName=char(fileName);
-0020 outputFileName=char(outputFileName);
-0021 if nargin<3
-0022     toCOBRA=false;
-0023 end
-0024 if nargin<4
-0025     printWarnings=true;
-0026 end
-0027 
-0028 model=importExcelModel(fileName,false,printWarnings);
-0029 printModelStats(model,printWarnings,false);
-0030 exportModel(model,outputFileName,toCOBRA,true);
-0031 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/io/addJavaPaths.html b/doc/io/addJavaPaths.html deleted file mode 100644 index 1235fed1f..000000000 --- a/doc/io/addJavaPaths.html +++ /dev/null @@ -1,76 +0,0 @@ - - - - Description of addJavaPaths - - - - - - - - - -
Home > io > addJavaPaths.m
- - - -

addJavaPaths -

- -

PURPOSE ^

-
addJavaPaths
- -

SYNOPSIS ^

-
function addJavaPaths()
- -

DESCRIPTION ^

-
 addJavaPaths
-   Adds the Apache POI classes to the static Java paths
-
- Usage: addJavaPaths()
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - - - -

SOURCE CODE ^

-
0001 % addJavaPaths
-0002 %   Adds the Apache POI classes to the static Java paths
-0003 %
-0004 % Usage: addJavaPaths()
-0005 
-0006 function addJavaPaths()
-0007 %Get the path to Apache POI
-0008 ravenPath=findRAVENroot();
-0009 poiPATH=fullfile(ravenPath,'software','apache-poi');
-0010 
-0011 toAdd={fullfile(poiPATH,'dom4j-1.6.1.jar');
-0012     fullfile(poiPATH,'poi-3.8-20120326.jar');
-0013     fullfile(poiPATH,'poi-ooxml-3.8-20120326.jar');
-0014     fullfile(poiPATH,'poi-ooxml-schemas-3.8-20120326.jar');
-0015     fullfile(poiPATH,'xmlbeans-2.3.0.jar');
-0016     fullfile(poiPATH,'stax-api-1.0.1.jar')};
-0017 
-0018 existingPaths=javaclasspath();
-0019 
-0020 %Add the paths that are not already present
-0021 for i=1:numel(toAdd)
-0022     if ~any(ismember(existingPaths,toAdd{i}))
-0023         javaaddpath(toAdd{i});
-0024     end
-0025 end
-0026 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/io/checkFileExistence.html b/doc/io/checkFileExistence.html deleted file mode 100644 index d17fbfcd7..000000000 --- a/doc/io/checkFileExistence.html +++ /dev/null @@ -1,152 +0,0 @@ - - - - Description of checkFileExistence - - - - - - - - - -
Home > io > checkFileExistence.m
- - - -

checkFileExistence -

- -

PURPOSE ^

-
checkFileExistence
- -

SYNOPSIS ^

-
function files=checkFileExistence(files,fullOrTemp,allowSpace,checkExist)
- -

DESCRIPTION ^

-
 checkFileExistence
-   Check whether files exist. If no full path is given a file should be
-   located in the current folder, which by default is appended to the
-   filename.
-
-   Input:
-   files           string or cell array of strings with path to file(s) or
-                   path or filename(s)
-   fullOrTemp      0: do not change path to file(s)
-                   1: return full path to file(s)
-                   2: copy file(s) to system default temporary folder and
-                      return full path
-                   (optional, default 0)
-   allowSpace      logical, whether 'space' character is allowed in the
-                   path (optional, default true)
-   checkExist      logical, whether file existence should really be
-                   checked, as this function can also be used to return
-                   the full path to a new file (optional, default true). Can
-                   only be set to false if fullOrTemp is set to 1.
-
-   Output:
-   files           string or cell array of strings with updated paths if
-                   fullOrTemp was set as 1 or 2, otherwise original paths
-                   are returned
-   
- Usage: files=checkFileExistence(files,fullOrTemp,allowSpace,checkExist)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function files=checkFileExistence(files,fullOrTemp,allowSpace,checkExist)
-0002 % checkFileExistence
-0003 %   Check whether files exist. If no full path is given a file should be
-0004 %   located in the current folder, which by default is appended to the
-0005 %   filename.
-0006 %
-0007 %   Input:
-0008 %   files           string or cell array of strings with path to file(s) or
-0009 %                   path or filename(s)
-0010 %   fullOrTemp      0: do not change path to file(s)
-0011 %                   1: return full path to file(s)
-0012 %                   2: copy file(s) to system default temporary folder and
-0013 %                      return full path
-0014 %                   (optional, default 0)
-0015 %   allowSpace      logical, whether 'space' character is allowed in the
-0016 %                   path (optional, default true)
-0017 %   checkExist      logical, whether file existence should really be
-0018 %                   checked, as this function can also be used to return
-0019 %                   the full path to a new file (optional, default true). Can
-0020 %                   only be set to false if fullOrTemp is set to 1.
-0021 %
-0022 %   Output:
-0023 %   files           string or cell array of strings with updated paths if
-0024 %                   fullOrTemp was set as 1 or 2, otherwise original paths
-0025 %                   are returned
-0026 %
-0027 % Usage: files=checkFileExistence(files,fullOrTemp,allowSpace,checkExist)
-0028 
-0029 if nargin<2
-0030     fullOrTemp = 0;
-0031 end
-0032 if nargin<3
-0033     allowSpace = true;
-0034 end
-0035 if nargin<4
-0036     checkExist = true;
-0037 end
-0038 files=convertCharArray(files);
-0039 if numel(files)==1
-0040     oneFile=true;
-0041 else
-0042     oneFile=false;
-0043 end
-0044 filesOriginal = files;
-0045 
-0046 %Make all full paths before check of file existence
-0047 if ispc % full path starts like "C:\"
-0048     inCurrDir = cellfun(@isempty,regexpi(files,'^[a-z]\:\\'));
-0049 else %isunix full path starts like "/"
-0050     inCurrDir = cellfun(@isempty,regexpi(files,'^\/'));
-0051 end
-0052 files(inCurrDir) = fullfile(cd,files(inCurrDir));
-0053 
-0054 %Check existence
-0055 if checkExist
-0056     for i=1:numel(files)
-0057         if ~isfile(files{i})
-0058             error('File "%s" cannot be found\n',files{i});
-0059         elseif allowSpace == false & strfind(files{i},' ')
-0060             error('File "%s" has an invalid space in the filename or path, please remove this before running this function\n',files{i});
-0061         end
-0062     end
-0063 end
-0064 
-0065 switch fullOrTemp
-0066     case 0
-0067         files = filesOriginal;
-0068     case 1
-0069         % files already contains full path
-0070     case 2
-0071         for i=1:numel(files)
-0072             tmpFile=tempname;
-0073             copyfile(files{i},tmpFile);
-0074             files{i}=tmpFile;
-0075         end
-0076 end
-0077 
-0078 if oneFile == true
-0079     files = files{1};
-0080 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/io/cleanSheet.html b/doc/io/cleanSheet.html deleted file mode 100644 index fd3918e9b..000000000 --- a/doc/io/cleanSheet.html +++ /dev/null @@ -1,170 +0,0 @@ - - - - Description of cleanSheet - - - - - - - - - -
Home > io > cleanSheet.m
- - - -

cleanSheet -

- -

PURPOSE ^

-
cleanSheet
- -

SYNOPSIS ^

-
function [raw,keptRows,keptCols]=cleanSheet(raw,removeComments,removeOnlyCap,removeNoCap,removeEmptyRows)
- -

DESCRIPTION ^

-
 cleanSheet
-   Cleans up an Excel sheet by removing empty rows/colums (and some other
-   checks)
-
-   raw             cell array with the data in the sheet
-   removeComments  true if commented lines (non-empty first cell in each
-                   row) should be removed (optional, default true)
-   removeOnlyCap   remove columns with captions but no other values (optional,
-                   default false)
-   removeNoCap     remove columns without captions (optional, default true)
-   removeEmptyRows remove rows with no non-empty cells (optional, default true)
-   
-   raw             cleaned version
-   keptRows        indexes of the kept rows in the original structure
-   keptCols        indexes of the kept columns in the original structure
-
- Usage: [raw,keptRows,keptCols]=cleanSheet(raw,removeComments,removeOnlyCap,...
-               removeNoCap,removeEmptyRows)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 % cleanSheet
-0002 %   Cleans up an Excel sheet by removing empty rows/colums (and some other
-0003 %   checks)
-0004 %
-0005 %   raw             cell array with the data in the sheet
-0006 %   removeComments  true if commented lines (non-empty first cell in each
-0007 %                   row) should be removed (optional, default true)
-0008 %   removeOnlyCap   remove columns with captions but no other values (optional,
-0009 %                   default false)
-0010 %   removeNoCap     remove columns without captions (optional, default true)
-0011 %   removeEmptyRows remove rows with no non-empty cells (optional, default true)
-0012 %
-0013 %   raw             cleaned version
-0014 %   keptRows        indexes of the kept rows in the original structure
-0015 %   keptCols        indexes of the kept columns in the original structure
-0016 %
-0017 % Usage: [raw,keptRows,keptCols]=cleanSheet(raw,removeComments,removeOnlyCap,...
-0018 %               removeNoCap,removeEmptyRows)
-0019 
-0020 function [raw,keptRows,keptCols]=cleanSheet(raw,removeComments,removeOnlyCap,removeNoCap,removeEmptyRows)
-0021 if nargin<2
-0022     removeComments=true;
-0023 end
-0024 if nargin<3
-0025     removeOnlyCap=false;
-0026 end
-0027 if nargin<4
-0028     removeNoCap=true;
-0029 end
-0030 if nargin<5
-0031     removeEmptyRows=true;
-0032 end
-0033 
-0034 keptRows=1:size(raw,1);
-0035 keptRows=keptRows(:);
-0036 keptCols=1:size(raw,2);
-0037 keptCols=keptCols(:);
-0038 
-0039 %First check that it's a cell array. If a sheet is completely empty, then
-0040 %raw=NaN
-0041 if iscell(raw)
-0042     %Clear cells which contain only white spaces or NaN. This could happen
-0043     %if you accidentally inserted a space for example. I don't know how NaN
-0044     %could occur after switching to Apache POI, but I clear it to be sure
-0045     whites=cellfun(@wrapperWS,raw);
-0046     raw(whites)={[]};
-0047     
-0048     %Find the rows that are not commented. This corresponds to the first
-0049     %row and the ones which are empty in the first column
-0050     if removeComments==true
-0051         keepers=cellfun(@isempty,raw(:,1));
-0052         keepers(1)=true;
-0053         raw=raw(keepers,:);
-0054         keptRows=keptRows(keepers);
-0055     end
-0056     
-0057     %Remove columns that don't have string headers. If you cut and paste a
-0058     %lot in the sheet there tends to be columns that are empty
-0059     if removeNoCap==true
-0060         I=cellfun(@isstr,raw(1,:));
-0061         raw=raw(:,I);
-0062         keptCols=keptCols(I);
-0063     end
-0064     
-0065     %Remove columns which are empty except for header
-0066     if removeOnlyCap==true
-0067         I=~all(cellfun(@isempty,raw(2:end,:)),1);
-0068         raw=raw(:,I);
-0069         keptCols=keptCols(I);
-0070     end
-0071     
-0072     %Check if there are any rows that are all empty. This could happen if
-0073     %it reads too far or if the user has inserted them for layout reasons.
-0074     %Remove any such rows
-0075     if removeEmptyRows==true
-0076         I=~all(cellfun(@isempty,raw),2);
-0077         raw=raw(I,:);
-0078         keptRows=keptRows(I);
-0079     end
-0080 else
-0081     raw={[]};
-0082 end
-0083 
-0084 %Checks if something is all white spaces or NaN
-0085     function I=wrapperWS(A)
-0086         if isnan(A)
-0087             I=true;
-0088         else
-0089             %isstrprop gives an error if boolean
-0090             if islogical(A)
-0091                 I=false;
-0092             else
-0093                 %I have to make this check, since otherwise it will pick up
-0094                 %on doubles for which the ASCII representation is a white
-0095                 %space character
-0096                 if isnumeric(A)
-0097                     I=false;
-0098                 else
-0099                     I=all(isstrprop(A,'wspace'));
-0100                 end
-0101             end
-0102         end
-0103     end
-0104 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/io/closeModel.html b/doc/io/closeModel.html deleted file mode 100644 index a8db94c9b..000000000 --- a/doc/io/closeModel.html +++ /dev/null @@ -1,115 +0,0 @@ - - - - Description of closeModel - - - - - - - - - -
Home > io > closeModel.m
- - - -

closeModel -

- -

PURPOSE ^

-
closeModel
- -

SYNOPSIS ^

-
function closedModel=closeModel(model)
- -

DESCRIPTION ^

-
 closeModel
-   Adds boundary metabolites and their participation in exchange
-   reactions.
-
-   model                 a model structure
-
-   closedModel           an updated closedModel structure
-
- Usage: closedModel=closeModel(model)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function closedModel=closeModel(model)
-0002 % closeModel
-0003 %   Adds boundary metabolites and their participation in exchange
-0004 %   reactions.
-0005 %
-0006 %   model                 a model structure
-0007 %
-0008 %   closedModel           an updated closedModel structure
-0009 %
-0010 % Usage: closedModel=closeModel(model)
-0011 
-0012 closedModel=model;
-0013 
-0014 closedModel.comps{numel(closedModel.comps)+1,1}='b';
-0015 closedModel.compNames{numel(closedModel.compNames)+1,1}='boundary';
-0016 if isfield(closedModel,'compMiriams')
-0017     closedModel.compMiriams{numel(closedModel.compMiriams)+1,1}=[];
-0018 end
-0019 closedModel.unconstrained=zeros(numel(closedModel.mets),1);
-0020 
-0021 for i=1:numel(closedModel.rxns)
-0022     if sum(abs(closedModel.S(:,i)))==1
-0023         closedModel.mets{numel(closedModel.mets)+1}=strcat(closedModel.mets{find(closedModel.S(:,i))},'_b');
-0024         if isfield(closedModel,'metNames')
-0025             closedModel.metNames{numel(closedModel.metNames)+1}=closedModel.metNames{find(closedModel.S(:,i))};
-0026         end
-0027         closedModel.metComps(numel(closedModel.metComps)+1)=numel(closedModel.comps);
-0028         if isfield(closedModel,'inchis')
-0029             closedModel.inchis{numel(closedModel.inchis)+1}=closedModel.inchis{find(closedModel.S(:,i))};
-0030         end
-0031         if isfield(closedModel,'metSmiles')
-0032             closedModel.metSmiles{numel(closedModel.metSmiles)+1}=closedModel.metSmiles{find(closedModel.S(:,i))};
-0033         end
-0034         if isfield(closedModel,'metFormulas')
-0035             closedModel.metFormulas{numel(closedModel.metFormulas)+1}=closedModel.metFormulas{find(closedModel.S(:,i))};
-0036         end
-0037         if isfield(closedModel,'metMiriams')
-0038             closedModel.metMiriams{numel(closedModel.metMiriams)+1}=closedModel.metMiriams{find(closedModel.S(:,i))};
-0039         end
-0040         if isfield(closedModel,'metFrom')
-0041             closedModel.metFrom{numel(closedModel.metFrom)+1}='';
-0042         end
-0043         if isfield(closedModel,'metCharges')
-0044             closedModel.metCharges(numel(closedModel.metCharges)+1)=closedModel.metCharges(find(closedModel.S(:,i)));
-0045         end
-0046         if isfield(closedModel,'metDeltaG')
-0047             closedModel.metDeltaG(numel(closedModel.metDeltaG)+1)=closedModel.metDeltaG(find(closedModel.S(:,i)));
-0048         end
-0049         closedModel.unconstrained(numel(closedModel.unconstrained)+1)=1;
-0050         closedModel.b(numel(closedModel.b)+1)=0;
-0051         closedModel.S=[closedModel.S;sparse(1,size(closedModel.S,2))];
-0052         if sum(closedModel.S(:,i))==1
-0053             closedModel.S(numel(closedModel.mets),i)=-1;
-0054         else
-0055             closedModel.S(numel(closedModel.mets),i)=1;
-0056         end
-0057     end
-0058 end
-0059 
-0060 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/io/exportForGit.html b/doc/io/exportForGit.html deleted file mode 100644 index 1a60e1be9..000000000 --- a/doc/io/exportForGit.html +++ /dev/null @@ -1,244 +0,0 @@ - - - - Description of exportForGit - - - - - - - - - -
Home > io > exportForGit.m
- - - -

exportForGit -

- -

PURPOSE ^

-
exportForGit
- -

SYNOPSIS ^

-
function out=exportForGit(model,prefix,path,formats,mainBranchFlag,subDirs,COBRAtext,neverPrefixIDs)
- -

DESCRIPTION ^

-
 exportForGit
-   Generates a directory structure and populates this with model files, ready
-   to be commited to a Git(Hub) maintained model repository. Writes the model
-   as SBML L3V1 FBCv2 (both XML and YAML), COBRA text, Matlab MAT-file
-   orthologies in KEGG
-
-   model               model structure in RAVEN format that should be
-   exported
-   prefix              prefix for all filenames (optional, default 'model')
-   path                path where the directory structure should be
-                       generated and populated with all files (optional,
-                       default to current working directory)
-   formats             cell array of strings specifying in what file
-                       formats the model should be exported (optional,
-                       default to all formats as {'mat', 'txt', 'xlsx',
-                       'xml', 'yml'})
-   mainBranchFlag      logical, if true, function will error if RAVEN (and
-                       COBRA if detected) is/are not on the main branch.
-                       (optional, default false)
-   subDirs             logical, whether model files for each file format
-                       should be written in its own subdirectory, with
-                       'model' as parent directory, in accordance to the
-                       standard-GEM repository format. If false, all files
-                       are stored in the same folder. (optional, default
-                       true)
-   COBRAtext           logical, whether the txt file should be in COBRA
-                       Toolbox format using metabolite IDs, instead of
-                       metabolite names and compartments. (optional,
-                       default false)
-   neverPrefixIDs      true if prefixes are never added to identifiers,
-                       even if start with e.g. digits. This might result
-                       in invalid SBML files (optional, default false)
-
- Usage: exportForGit(model,prefix,path,formats,mainBranchFlag,subDirs,COBRAtext,COBRAstyle)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function out=exportForGit(model,prefix,path,formats,mainBranchFlag,subDirs,COBRAtext,neverPrefixIDs)
-0002 % exportForGit
-0003 %   Generates a directory structure and populates this with model files, ready
-0004 %   to be commited to a Git(Hub) maintained model repository. Writes the model
-0005 %   as SBML L3V1 FBCv2 (both XML and YAML), COBRA text, Matlab MAT-file
-0006 %   orthologies in KEGG
-0007 %
-0008 %   model               model structure in RAVEN format that should be
-0009 %   exported
-0010 %   prefix              prefix for all filenames (optional, default 'model')
-0011 %   path                path where the directory structure should be
-0012 %                       generated and populated with all files (optional,
-0013 %                       default to current working directory)
-0014 %   formats             cell array of strings specifying in what file
-0015 %                       formats the model should be exported (optional,
-0016 %                       default to all formats as {'mat', 'txt', 'xlsx',
-0017 %                       'xml', 'yml'})
-0018 %   mainBranchFlag      logical, if true, function will error if RAVEN (and
-0019 %                       COBRA if detected) is/are not on the main branch.
-0020 %                       (optional, default false)
-0021 %   subDirs             logical, whether model files for each file format
-0022 %                       should be written in its own subdirectory, with
-0023 %                       'model' as parent directory, in accordance to the
-0024 %                       standard-GEM repository format. If false, all files
-0025 %                       are stored in the same folder. (optional, default
-0026 %                       true)
-0027 %   COBRAtext           logical, whether the txt file should be in COBRA
-0028 %                       Toolbox format using metabolite IDs, instead of
-0029 %                       metabolite names and compartments. (optional,
-0030 %                       default false)
-0031 %   neverPrefixIDs      true if prefixes are never added to identifiers,
-0032 %                       even if start with e.g. digits. This might result
-0033 %                       in invalid SBML files (optional, default false)
-0034 %
-0035 % Usage: exportForGit(model,prefix,path,formats,mainBranchFlag,subDirs,COBRAtext,COBRAstyle)
-0036 if nargin<8
-0037     neverPrefixIDs=false;
-0038 end
-0039 if nargin<7 || isempty(COBRAtext)
-0040     COBRAtext=false;
-0041 end
-0042 if nargin<6 || isempty(subDirs)
-0043     subDirs=true;
-0044 end
-0045 if nargin<5 || isempty(mainBranchFlag)
-0046     mainBranchFlag=false;
-0047 end
-0048 if nargin<4 || isempty(formats)
-0049     formats={'mat', 'txt', 'xlsx', 'xml', 'yml'};
-0050 else
-0051     formats=convertCharArray(formats);
-0052 end
-0053 if any(~ismember(formats, {'mat', 'txt', 'xlsx', 'xml', 'yml'}))
-0054     EM='Unknown file format defined. Only mat, txt, xlsx, xml and yml are allowed file formats.';
-0055     error(EM)
-0056 end
-0057 if nargin<3 || isempty(path)
-0058     path='.';
-0059 else
-0060     path=char(path);
-0061 end
-0062 if nargin<2 || isempty(prefix)
-0063     prefix='model';
-0064 else
-0065     prefix=char(prefix);
-0066 end
-0067 
-0068 %Sort reactions, metabolites and genes alphabetically
-0069 model=sortIdentifiers(model);
-0070 
-0071 %Get versions or commits of toolboxes:
-0072 RAVENver = getToolboxVersion('RAVEN','ravenCobraWrapper.m',mainBranchFlag);
-0073 if exist('initCobraToolbox.m','file')
-0074     COBRAver = getToolboxVersion('COBRA','initCobraToolbox.m',mainBranchFlag);
-0075 else
-0076     COBRAver = [];
-0077 end
-0078 %Retrieve libSBML version:
-0079 [ravenDir,prevDir]=findRAVENroot();
-0080 try % 5.17.0 and newer
-0081     libSBMLver=OutputSBML_RAVEN;
-0082     libSBMLver=libSBMLver.libSBML_version_string;
-0083 catch % before 5.17.0
-0084     fid = fopen('tempModelForLibSBMLversion.xml','w+');
-0085     fclose(fid);
-0086     evalc('[~,~,libSBMLver]=TranslateSBML_RAVEN(''tempModelForLibSBMLversion.xml'',0,0)');
-0087     libSBMLver=libSBMLver.libSBML_version_string;
-0088     delete('tempModelForLibSBMLversion.xml');
-0089 end
-0090 
-0091 % Make models folder, no warnings if folder already exists
-0092 if subDirs
-0093     path=fullfile(path,'model');
-0094     filePath=strcat(path,filesep,{'txt','yml','mat','xlsx','xml'});
-0095     [~,~,~]=mkdir(path);
-0096     for i = 1:length(formats)
-0097         [~,~,~]=mkdir(fullfile(path,formats{i}));
-0098     end
-0099 else
-0100     filePath=cell(1,5); filePath(:)={path};
-0101 end
-0102 
-0103 
-0104 % Write TXT format
-0105 if ismember('txt', formats)
-0106     fid=fopen(fullfile(filePath{1},strcat(prefix,'.txt')),'w');
-0107     if COBRAtext==true
-0108         eqns=constructEquations(model,model.rxns,false,false,false);
-0109         eqns=strrep(eqns,' => ','  -> ');
-0110         eqns=strrep(eqns,' <=> ','  <=> ');
-0111         eqns=regexprep(eqns,'> $','>');
-0112         grRules=regexprep(model.grRules,'\((?!\()','( ');
-0113         grRules=regexprep(grRules,'(?<!\))\)',' )');
-0114     else
-0115         eqns=constructEquations(model,model.rxns);
-0116         grRules=model.grRules;
-0117     end
-0118     fprintf(fid, 'Rxn name\tFormula\tGene-reaction association\tLB\tUB\tObjective\n');
-0119     for i = 1:numel(model.rxns)
-0120         fprintf(fid, '%s\t', model.rxns{i});
-0121         fprintf(fid, '%s \t', eqns{i});
-0122         fprintf(fid, '%s\t', grRules{i});
-0123         fprintf(fid, '%6.2f\t%6.2f\t%6.2f\n', model.lb(i), model.ub(i), model.c(i));
-0124     end
-0125     fclose(fid);
-0126 end
-0127 
-0128 % Write YML format
-0129 if ismember('yml', formats)
-0130     writeYAMLmodel(model,fullfile(filePath{2},strcat(prefix,'.yml')));
-0131 end
-0132 
-0133 % Write MAT format
-0134 if ismember('mat', formats)
-0135     save(fullfile(filePath{3},strcat(prefix,'.mat')),'model');
-0136 end
-0137 
-0138 % Write XLSX format
-0139 if ismember('xlsx', formats)
-0140     exportToExcelFormat(model,fullfile(filePath{4},strcat(prefix,'.xlsx')));
-0141 end
-0142 
-0143 % Write XML format
-0144 if ismember('xml', formats)
-0145         exportModel(model,fullfile(filePath{5},strcat(prefix,'.xml')),neverPrefixIDs);
-0146 end
-0147 
-0148 %Save file with versions:
-0149 fid = fopen(fullfile(path,'dependencies.txt'),'wt');
-0150 fprintf(fid,['MATLAB\t' version '\n']);
-0151 fprintf(fid,['libSBML\t' libSBMLver '\n']);
-0152 fprintf(fid,['RAVEN_toolbox\t' RAVENver '\n']);
-0153 if ~isempty(COBRAver)
-0154     fprintf(fid,['COBRA_toolbox\t' COBRAver '\n']);
-0155 end
-0156 if isfield(model,'modelVersion')
-0157     fields = fieldnames(model.modelVersion);
-0158     for i = 1:length(fields)
-0159         value = model.modelVersion.(fields{i});
-0160         fprintf(fid,[fields{i} '\t' num2str(value) '\n']);
-0161     end
-0162 end
-0163 fclose(fid);
-0164 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/io/exportModel.html b/doc/io/exportModel.html deleted file mode 100644 index eacffe43b..000000000 --- a/doc/io/exportModel.html +++ /dev/null @@ -1,868 +0,0 @@ - - - - Description of exportModel - - - - - - - - - -
Home > io > exportModel.m
- - - -

exportModel -

- -

PURPOSE ^

-
exportModel
- -

SYNOPSIS ^

-
function exportModel(model,fileName,neverPrefix,supressWarnings,sortIds)
- -

DESCRIPTION ^

-
 exportModel
-   Exports a constraint-based model to an SBML file (L3V1 FBCv2)
-
- Input:
-   model               a model structure
-   fileName            filename to export the model to. A dialog window
-                       will open if no file name is specified.
-   neverPrefix         true if prefixes are never added to identifiers,
-                       even if start with e.g. digits. This might result
-                       in invalid SBML files (optional, default false)
-   supressWarnings     true if warnings should be supressed. This might
-                       results in invalid SBML files, as no checks are
-                       performed (optional, default false)
-   sortIds             logical whether metabolites, reactions and genes
-                       should be sorted alphabetically by their
-                       identifiers (optional, default false)
-
- Usage: exportModel(model,fileName,neverPrefix,supressWarnings,sortIds)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 function exportModel(model,fileName,neverPrefix,supressWarnings,sortIds)
-0002 % exportModel
-0003 %   Exports a constraint-based model to an SBML file (L3V1 FBCv2)
-0004 %
-0005 % Input:
-0006 %   model               a model structure
-0007 %   fileName            filename to export the model to. A dialog window
-0008 %                       will open if no file name is specified.
-0009 %   neverPrefix         true if prefixes are never added to identifiers,
-0010 %                       even if start with e.g. digits. This might result
-0011 %                       in invalid SBML files (optional, default false)
-0012 %   supressWarnings     true if warnings should be supressed. This might
-0013 %                       results in invalid SBML files, as no checks are
-0014 %                       performed (optional, default false)
-0015 %   sortIds             logical whether metabolites, reactions and genes
-0016 %                       should be sorted alphabetically by their
-0017 %                       identifiers (optional, default false)
-0018 %
-0019 % Usage: exportModel(model,fileName,neverPrefix,supressWarnings,sortIds)
-0020 
-0021 if nargin<2 || isempty(fileName)
-0022     [fileName, pathName] = uiputfile({'*.xml;*.sbml'}, 'Select file for model export',[model.id '.xml']);
-0023     if fileName == 0
-0024         error('You should provide a file location')
-0025     else
-0026         fileName = fullfile(pathName,fileName);
-0027     end
-0028 end
-0029 fileName=char(fileName);
-0030 if nargin<3 || isempty(neverPrefix)
-0031     neverPrefix=false;
-0032 end
-0033 if nargin<4 || isempty(supressWarnings)
-0034     supressWarnings=false;
-0035 end
-0036 if nargin<5 || isempty(sortIds)
-0037     sortIds=false;
-0038 end
-0039 if sortIds==true
-0040     model=sortIdentifiers(model);
-0041 end
-0042 
-0043 if isfield(model,'ec')
-0044     warning("exportModel does not store information from the 'model.ec' structure. Use 'writeYAMLmodel(model)' to export all content from a GECKO model.")
-0045 end
-0046 
-0047 %If no subSystems are defined, then no need to use groups package
-0048 if isfield(model,'subSystems')
-0049     modelHasSubsystems=true;
-0050 else
-0051     modelHasSubsystems=false;
-0052 end
-0053 
-0054 %The default SBML format settings, which are used as input for appropriate
-0055 %libSBML functions to generate the blank SBML model structure before using
-0056 %exporting in with OutputSBML to xml file
-0057 sbmlLevel=3;
-0058 sbmlVersion=1;
-0059 sbmlPackages={'fbc'};
-0060 sbmlPackageVersions=2;
-0061 if modelHasSubsystems
-0062     sbmlPackages={sbmlPackages,'groups'};
-0063     sbmlPackageVersions=[sbmlPackageVersions,1];
-0064 end
-0065 
-0066 %Check if the "unconstrained" field is still present. This shows if
-0067 %exchange metabolites have been removed
-0068 if ~isfield(model,'unconstrained')
-0069     model.unconstrained=zeros(numel(model.mets),1);
-0070 end
-0071 
-0072 %If model id and name do not exist, make sure that default
-0073 %strings are included
-0074 if ~isfield(model,'id')
-0075     fprintf('WARNING: The model is missing the "id" field. Uses "blankID". \n');
-0076     model.id='blankID';
-0077 end
-0078 if ~isfield(model,'name')
-0079     fprintf('WARNING: The model is missing the "name" field. Uses "blankName". \n');
-0080     model.name='blankName';
-0081 end
-0082 
-0083 % Add prefixes if required
-0084 if ~neverPrefix
-0085     [model,hasChanged] = addIdentifierPrefix(model);
-0086     dispEM(['The following fields have one or more entries that do not start '...
-0087         'with a letter or _ (conflicting with SBML specifications). Prefixes '...
-0088         'are added to all entries in those fields:'],false,hasChanged)
-0089 end
-0090 
-0091 %Check the model structure
-0092 if supressWarnings==false
-0093     checkModelStruct(model);
-0094 end
-0095 
-0096 %Add several blank fields, if they do not exist already. This is to reduce
-0097 %the number of conditions below
-0098 if ~isfield(model,'compMiriams')
-0099     model.compMiriams=cell(numel(model.comps),1);
-0100 end
-0101 if ~isfield(model,'inchis')
-0102     model.inchis=cell(numel(model.mets),1);
-0103 end
-0104 if ~isfield(model,'metFormulas')
-0105     model.metFormulas=cell(numel(model.mets),1);
-0106 end
-0107 if ~isfield(model,'metMiriams')
-0108     model.metMiriams=cell(numel(model.mets),1);
-0109 end
-0110 if ~isfield(model,'geneMiriams') && isfield(model,'genes')
-0111     model.geneMiriams=cell(numel(model.genes),1);
-0112 end
-0113 if ~isfield(model,'geneShortNames') && isfield(model,'genes')
-0114     model.geneShortNames=cell(numel(model.genes),1);
-0115 end
-0116 if ~isfield(model,'proteins') && isfield(model,'genes')
-0117     model.proteins=cell(numel(model.genes),1);
-0118 end
-0119 if ~isfield(model,'subSystems')
-0120     model.subSystems=cell(numel(model.rxns),1);
-0121 end
-0122 if ~isfield(model,'eccodes')
-0123     model.eccodes=cell(numel(model.rxns),1);
-0124 end
-0125 if ~isfield(model,'rxnReferences')
-0126     model.rxnReferences=cell(numel(model.rxns),1);
-0127 end
-0128 if ~isfield(model,'rxnConfidenceScores')
-0129     model.rxnConfidenceScores=NaN(numel(model.rxns),1);
-0130 end
-0131 if ~isfield(model,'rxnNotes')
-0132     model.rxnNotes=cell(numel(model.rxns),1);
-0133 end
-0134 if ~isfield(model,'rxnMiriams')
-0135     model.rxnMiriams=cell(numel(model.rxns),1);
-0136 end
-0137 
-0138 if sbmlLevel<3
-0139     %Check if genes have associated compartments
-0140     if ~isfield(model,'geneComps') && isfield(model,'genes')
-0141         if supressWarnings==false
-0142             EM='There are no compartments specified for genes. All genes will be assigned to the first compartment. This is because the SBML structure requires all elements to be assigned to a compartment';
-0143             dispEM(EM,false);
-0144         end
-0145         model.geneComps=ones(numel(model.genes),1);
-0146     end
-0147 end
-0148 
-0149 %Convert ids to SBML-convenient format. This is to avoid the data loss when
-0150 %unsupported characters are included in ids. Here we are using part from
-0151 %convertSBMLID, originating from the COBRA Toolbox
-0152 model.rxns=regexprep(model.rxns,'([^0-9_a-zA-Z])','__${num2str($1+0)}__');
-0153 model.mets=regexprep(model.mets,'([^0-9_a-zA-Z])','__${num2str($1+0)}__');
-0154 model.comps=regexprep(model.comps,'([^0-9_a-zA-Z])','__${num2str($1+0)}__');
-0155 if isfield(model,'genes')
-0156     problemGenes=find(~cellfun('isempty',regexp(model.genes,'([^0-9_a-zA-Z])')));
-0157     originalGenes=model.genes(problemGenes);
-0158     replacedGenes=regexprep(model.genes(problemGenes),'([^0-9_a-zA-Z])','__${num2str($1+0)}__');
-0159     model.genes(problemGenes)=replacedGenes;
-0160     for i=1:numel(problemGenes)
-0161         model.grRules = regexprep(model.grRules, ['(^|\s|\()' originalGenes{i} '($|\s|\))'], ['$1' replacedGenes{i} '$2']);
-0162     end
-0163 end
-0164 
-0165 %Generate an empty SBML structure
-0166 modelSBML=getSBMLStructure(sbmlLevel,sbmlVersion,sbmlPackages,sbmlPackageVersions);
-0167 modelSBML.metaid=model.id;
-0168 modelSBML.id=regexprep(model.id,'([^0-9_a-zA-Z])','__${num2str($1+0)}__');
-0169 modelSBML.name=model.name;
-0170 
-0171 if isfield(model,'annotation')
-0172     if isfield(model.annotation,'note')
-0173         modelSBML.notes=['<notes><body xmlns="http://www.w3.org/1999/xhtml"><p>',regexprep(model.annotation.note,'<p>|</p>',''),'</p></body></notes>'];
-0174     end
-0175 else
-0176     modelSBML.notes='<notes><body xmlns="http://www.w3.org/1999/xhtml"><p>This file was generated using the exportModel function in RAVEN Toolbox 2 and OutputSBML in libSBML </p></body></notes>';
-0177 end
-0178 
-0179 if isfield(model,'annotation')
-0180     nameString='';
-0181     if isfield(model.annotation,'familyName')
-0182         if ~isempty(model.annotation.familyName)
-0183             nameString=['<vCard:Family>' model.annotation.familyName '</vCard:Family>'];
-0184         end
-0185     end
-0186     if isfield(model.annotation,'givenName')
-0187         if ~isempty(model.annotation.givenName)
-0188             nameString=[nameString '<vCard:Given>' model.annotation.givenName '</vCard:Given>'];
-0189         end
-0190     end
-0191     email='';
-0192     if isfield(model.annotation,'email')
-0193         if ~isempty(model.annotation.email)
-0194             email=['<vCard:EMAIL>' model.annotation.email '</vCard:EMAIL>'];
-0195         end
-0196     end
-0197     org='';
-0198     if isfield(model.annotation,'organization')
-0199         if ~isempty(model.annotation.organization)
-0200             org=['<vCard:ORG rdf:parseType="Resource"><vCard:Orgname>' model.annotation.organization '</vCard:Orgname></vCard:ORG>'];
-0201         end
-0202     end
-0203     if ~isempty(nameString) || ~isempty(email) || ~isempty(org) % Only fill .annotation if ownership data is provided
-0204         modelSBML.annotation=['<annotation><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#" xmlns:bqbiol="http://biomodels.net/biology-qualifiers/" xmlns:bqmodel="http://biomodels.net/model-qualifiers/"><rdf:Description rdf:about="#meta_' model.id '">'];
-0205         modelSBML.annotation=[modelSBML.annotation '<dc:creator><rdf:Bag><rdf:li rdf:parseType="Resource">'];
-0206         if ~isempty(nameString)
-0207             modelSBML.annotation=[modelSBML.annotation '<vCard:N rdf:parseType="Resource">' nameString '</vCard:N>'];
-0208         end
-0209         modelSBML.annotation=[modelSBML.annotation email org '</rdf:li></rdf:Bag></dc:creator>'];
-0210         modelSBML.annotation=[modelSBML.annotation '<dcterms:created rdf:parseType="Resource">'...
-0211             '<dcterms:W3CDTF>' datestr(now,'yyyy-mm-ddTHH:MM:SSZ') '</dcterms:W3CDTF></dcterms:created><dcterms:modified rdf:parseType="Resource">'...
-0212             '<dcterms:W3CDTF>' datestr(now,'yyyy-mm-ddTHH:MM:SSZ') '</dcterms:W3CDTF></dcterms:modified>'];
-0213         if isfield(model.annotation,'taxonomy')
-0214             modelSBML.annotation=[modelSBML.annotation '<bqbiol:is><rdf:Bag><rdf:li rdf:resource="https://identifiers.org/taxonomy/' regexprep(model.annotation.taxonomy,'taxonomy/','') '"/></rdf:Bag></bqbiol:is>'];
-0215         end
-0216         modelSBML.annotation=[modelSBML.annotation '</rdf:Description></rdf:RDF></annotation>'];
-0217     end
-0218 end
-0219 
-0220 %Prepare compartments
-0221 for i=1:numel(model.comps)
-0222     %Add the default values, as these will be the same in all entries
-0223     if i==1
-0224         if isfield(modelSBML.compartment, 'sboTerm')
-0225             modelSBML.compartment(i).sboTerm=290;
-0226         end
-0227         if isfield(modelSBML.compartment, 'spatialDimensions')
-0228             modelSBML.compartment(i).spatialDimensions=3;
-0229         end
-0230         if isfield(modelSBML.compartment, 'size')
-0231             modelSBML.compartment(i).size=1;
-0232         end
-0233         if isfield(modelSBML.compartment, 'constant')
-0234             modelSBML.compartment(i).constant=1;
-0235         end
-0236         if isfield(modelSBML.compartment, 'isSetSize')
-0237             modelSBML.compartment(i).isSetSize=1;
-0238         end
-0239         if isfield(modelSBML.compartment, 'isSetSpatialDimensions')
-0240             modelSBML.compartment(i).isSetSpatialDimensions=1;
-0241         end
-0242     end
-0243     %Copy the default values to the next entry as long as it is not the
-0244     %last one
-0245     if i<numel(model.comps)
-0246         modelSBML.compartment(i+1)=modelSBML.compartment(i);
-0247     end
-0248 
-0249     if isfield(modelSBML.compartment,'metaid')
-0250         modelSBML.compartment(i).metaid=model.comps{i};
-0251     end
-0252     %Prepare Miriam strings
-0253     if ~isempty(model.compMiriams{i})
-0254         [~,sbo_ind] = ismember('sbo',model.compMiriams{i}.name);
-0255         if sbo_ind > 0
-0256             modelSBML.compartment(i).sboTerm=str2double(regexprep(model.compMiriams{i}.value{sbo_ind},'SBO:','','ignorecase'));
-0257             % remove the SBO term from compMiriams so the information is
-0258             % not duplicated in the "annotation" field later on
-0259             model.compMiriams{i}.name(sbo_ind) = [];
-0260             model.compMiriams{i}.value(sbo_ind) = [];
-0261         end
-0262     end
-0263     if ~isempty(model.compMiriams{i}) && isfield(modelSBML.compartment(i),'annotation')
-0264         modelSBML.compartment(i).annotation=['<annotation><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#" xmlns:bqbiol="http://biomodels.net/biology-qualifiers/" xmlns:bqmodel="http://biomodels.net/model-qualifiers/"><rdf:Description rdf:about="#meta_' model.comps{i} '">'];
-0265         modelSBML.compartment(i).annotation=[modelSBML.compartment(i).annotation '<bqbiol:is><rdf:Bag>'];
-0266         modelSBML.compartment(i).annotation=[modelSBML.compartment(i).annotation getMiriam(model.compMiriams{i}) '</rdf:Bag></bqbiol:is></rdf:Description></rdf:RDF></annotation>'];
-0267     end
-0268     if isfield(modelSBML.compartment, 'name')
-0269         modelSBML.compartment(i).name=model.compNames{i};
-0270     end
-0271     if isfield(modelSBML.compartment, 'id')
-0272         modelSBML.compartment(i).id=model.comps{i};
-0273     end
-0274 
-0275 end
-0276 
-0277 %Begin writing species
-0278 for i=1:numel(model.mets)
-0279     %Add the default values, as these will be the same in all entries
-0280     if i==1
-0281         if isfield(modelSBML.species, 'sboTerm')
-0282             modelSBML.species(i).sboTerm=247;
-0283         end
-0284         if isfield(modelSBML.species, 'initialAmount')
-0285             modelSBML.species(i).initialAmount=1;
-0286         end
-0287         if isfield(modelSBML.species, 'initialConcentration')
-0288             modelSBML.species(i).initialConcentration=0;
-0289         end
-0290         if isfield(modelSBML.species, 'isSetInitialAmount')
-0291             modelSBML.species(i).isSetInitialAmount=1;
-0292         end
-0293         if isfield(modelSBML.species, 'isSetInitialConcentration')
-0294             modelSBML.species(i).isSetInitialConcentration=1;
-0295         end
-0296     end
-0297     %Copy the default values to the next entry as long as it is not the
-0298     %last one
-0299     if i<numel(model.mets)
-0300         modelSBML.species(i+1)=modelSBML.species(i);
-0301     end
-0302 
-0303     if isfield(modelSBML.species,'metaid')
-0304         modelSBML.species(i).metaid=model.mets{i};
-0305     end
-0306     if isfield(modelSBML.species, 'name')
-0307         modelSBML.species(i).name=model.metNames{i};
-0308     end
-0309     if isfield(modelSBML.species, 'id')
-0310         modelSBML.species(i).id=model.mets{i};
-0311     end
-0312     if isfield(modelSBML.species, 'compartment')
-0313         modelSBML.species(i).compartment=model.comps{model.metComps(i)};
-0314     end
-0315     if isfield(model,'unconstrained')
-0316         if model.unconstrained(i)
-0317             modelSBML.species(i).boundaryCondition=1;
-0318         end
-0319     end
-0320     if isfield(modelSBML.species, 'fbc_charge') && isfield(model,'metCharges')
-0321         if ~isnan(model.metCharges(i))
-0322             modelSBML.species(i).fbc_charge=model.metCharges(i);
-0323             modelSBML.species(i).isSetfbc_charge=1;
-0324         else
-0325             modelSBML.species(i).isSetfbc_charge=0;
-0326         end
-0327     end
-0328     if ~isempty(model.metMiriams{i})
-0329         [~,sbo_ind] = ismember('sbo',model.metMiriams{i}.name);
-0330         if sbo_ind > 0
-0331             modelSBML.species(i).sboTerm=str2double(regexprep(model.metMiriams{i}.value{sbo_ind},'SBO:','','ignorecase'));
-0332             % remove the SBO term from metMiriams so the information is
-0333             % not duplicated in the "annotation" field later on
-0334             model.metMiriams{i}.name(sbo_ind) = [];
-0335             model.metMiriams{i}.value(sbo_ind) = [];
-0336         end
-0337     end
-0338     if isfield(modelSBML.species,'annotation')
-0339         if ~isempty(model.metMiriams{i}) || ~isempty(model.metFormulas{i})
-0340             hasInchi=false;
-0341             if ~isempty(model.metFormulas{i})
-0342                 %Only export formula if there is no InChI. This is because
-0343                 %the metFormulas field is populated by InChIs if available
-0344                 if ~isempty(model.inchis{i})
-0345                     hasInchi=true;
-0346                 end
-0347                 if hasInchi==false
-0348                     modelSBML.species(i).fbc_chemicalFormula=model.metFormulas{i};
-0349                 end
-0350             end
-0351             if ~isempty(model.metMiriams{i}) || hasInchi==true
-0352                 modelSBML.species(i).annotation=['<annotation><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#" xmlns:bqbiol="http://biomodels.net/biology-qualifiers/" xmlns:bqmodel="http://biomodels.net/model-qualifiers/"><rdf:Description rdf:about="#meta_' model.mets{i} '">'];
-0353                 modelSBML.species(i).annotation=[modelSBML.species(i).annotation '<bqbiol:is><rdf:Bag>'];
-0354                 if ~isempty(model.metMiriams{i})
-0355                     modelSBML.species(i).annotation=[modelSBML.species(i).annotation getMiriam(model.metMiriams{i})];
-0356                 end
-0357                 if hasInchi==true
-0358                     modelSBML.species(i).annotation=[modelSBML.species(i).annotation '<rdf:li rdf:resource="https://identifiers.org/inchi/InChI=' regexprep(model.inchis{i},'^InChI=','') '"/>'];
-0359                     modelSBML.species(i).fbc_chemicalFormula=char(regexp(model.inchis{i}, '/(\w+)/', 'tokens', 'once'));
-0360                 end
-0361                 modelSBML.species(i).annotation=[modelSBML.species(i).annotation '</rdf:Bag></bqbiol:is></rdf:Description></rdf:RDF></annotation>'];
-0362             end
-0363         end
-0364     end
-0365 end
-0366 
-0367 if isfield(model,'genes')
-0368     for i=1:numel(model.genes)
-0369         %Add the default values, as these will be the same in all entries
-0370         if i==1
-0371             if isfield(modelSBML.fbc_geneProduct, 'sboTerm')
-0372                 modelSBML.fbc_geneProduct(i).sboTerm=243;
-0373             end
-0374         end
-0375         %Copy the default values to the next index as long as it is not the
-0376         %last one
-0377         if i<numel(model.genes)
-0378             modelSBML.fbc_geneProduct(i+1)=modelSBML.fbc_geneProduct(i);
-0379         end
-0380 
-0381         if isfield(modelSBML.fbc_geneProduct,'metaid')
-0382             modelSBML.fbc_geneProduct(i).metaid=model.genes{i};
-0383         end
-0384         if ~isempty(model.geneMiriams{i})
-0385             [~,sbo_ind] = ismember('sbo',model.geneMiriams{i}.name);
-0386             if sbo_ind > 0
-0387                 modelSBML.fbc_geneProduct(i).sboTerm=str2double(regexprep(model.geneMiriams{i}.value{sbo_ind},'SBO:','','ignorecase'));
-0388                 % remove the SBO term from compMiriams so the information is
-0389                 % not duplicated in the "annotation" field later on
-0390                 model.geneMiriams{i}.name(sbo_ind) = [];
-0391                 model.geneMiriams{i}.value(sbo_ind) = [];
-0392             end
-0393         end
-0394         if ~isempty(model.geneMiriams{i}) && isfield(modelSBML.fbc_geneProduct(i),'annotation')
-0395             modelSBML.fbc_geneProduct(i).annotation=['<annotation><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#" xmlns:bqbiol="http://biomodels.net/biology-qualifiers/" xmlns:bqmodel="http://biomodels.net/model-qualifiers/"><rdf:Description rdf:about="#meta_' model.genes{i} '">'];
-0396             modelSBML.fbc_geneProduct(i).annotation=[modelSBML.fbc_geneProduct(i).annotation '<bqbiol:is><rdf:Bag>'];
-0397             modelSBML.fbc_geneProduct(i).annotation=[modelSBML.fbc_geneProduct(i).annotation getMiriam(model.geneMiriams{i}) '</rdf:Bag></bqbiol:is></rdf:Description></rdf:RDF></annotation>'];
-0398         end
-0399         if isfield(modelSBML.fbc_geneProduct, 'fbc_id')
-0400             modelSBML.fbc_geneProduct(i).fbc_id=model.genes{i};
-0401         end
-0402         if isfield(modelSBML.fbc_geneProduct, 'fbc_label') && isfield(model,'geneShortNames')
-0403             if isempty(model.geneShortNames{i})
-0404                 modelSBML.fbc_geneProduct(i).fbc_label=model.genes{i};
-0405             else
-0406                 modelSBML.fbc_geneProduct(i).fbc_label=model.geneShortNames{i};
-0407             end
-0408         end
-0409         if isfield(modelSBML.fbc_geneProduct, 'fbc_name') && isfield(model,'proteins')
-0410             if ~isempty(model.proteins{i})
-0411                 modelSBML.fbc_geneProduct(i).fbc_name=model.proteins{i};
-0412             end
-0413         end
-0414     end
-0415 end
-0416 
-0417 %Generate a list of unique fbc_bound names
-0418 totalValues=[model.lb; model.ub];
-0419 totalNames=cell(size(totalValues,1),1);
-0420 
-0421 listUniqueValues=unique(totalValues);
-0422 
-0423 for i=1:length(listUniqueValues)
-0424     listUniqueNames{i,1}=['FB',num2str(i),'N',num2str(abs(round(listUniqueValues(i))))]; % create unique flux bound IDs.
-0425     ind=find(ismember(totalValues,listUniqueValues(i)));
-0426     totalNames(ind)=listUniqueNames(i,1);
-0427 end
-0428 
-0429 for i=1:length(listUniqueNames)
-0430     %Add the default values, as these will be the same in all entries
-0431     if i==1
-0432         if isfield(modelSBML.parameter, 'constant')
-0433             modelSBML.parameter(i).constant=1;
-0434         end
-0435         if isfield(modelSBML.parameter, 'isSetValue')
-0436             modelSBML.parameter(i).isSetValue=1;
-0437         end
-0438     end
-0439     %Copy the default values to the next index as long as it is not the
-0440     %last one
-0441     if i<numel(listUniqueNames)
-0442         modelSBML.parameter(i+1)=modelSBML.parameter(i);
-0443     end
-0444     modelSBML.parameter(i).id=listUniqueNames{i};
-0445     modelSBML.parameter(i).value=listUniqueValues(i);
-0446 end
-0447 
-0448 for i=1:numel(model.rxns)
-0449     %Add the default values, as these will be the same in all entries
-0450     if i==1
-0451         if isfield(modelSBML.reaction, 'sboTerm')
-0452             modelSBML.reaction(i).sboTerm=176;
-0453         end
-0454         if isfield(modelSBML.reaction, 'isSetFast')
-0455             modelSBML.reaction(i).isSetFast=1;
-0456         end
-0457     end
-0458     %Copy the default values to the next index as long as it is not the
-0459     %last one
-0460     if i<numel(model.rxns)
-0461         modelSBML.reaction(i+1)=modelSBML.reaction(i);
-0462     end
-0463 
-0464     if isfield(modelSBML.reaction,'metaid')
-0465         modelSBML.reaction(i).metaid=model.rxns{i};
-0466     end
-0467 
-0468     %Export notes information
-0469     if (~isnan(model.rxnConfidenceScores(i)) || ~isempty(model.rxnReferences{i}) || ~isempty(model.rxnNotes{i}))
-0470         modelSBML.reaction(i).notes='<notes><body xmlns="http://www.w3.org/1999/xhtml">';
-0471         if ~isnan(model.rxnConfidenceScores(i))
-0472             modelSBML.reaction(i).notes=[modelSBML.reaction(i).notes '<p>Confidence Level: ' num2str(model.rxnConfidenceScores(i)) '</p>'];
-0473         end
-0474         if ~isempty(model.rxnReferences{i})
-0475             modelSBML.reaction(i).notes=[modelSBML.reaction(i).notes '<p>AUTHORS: ' model.rxnReferences{i} '</p>'];
-0476         end
-0477         if ~isempty(model.rxnNotes{i})
-0478             modelSBML.reaction(i).notes=[modelSBML.reaction(i).notes '<p>NOTES: ' model.rxnNotes{i} '</p>'];
-0479         end
-0480         modelSBML.reaction(i).notes=[modelSBML.reaction(i).notes '</body></notes>'];
-0481     end
-0482 
-0483     % Export SBO terms from rxnMiriams
-0484     if ~isempty(model.rxnMiriams{i})
-0485         [~,sbo_ind] = ismember('sbo',model.rxnMiriams{i}.name);
-0486         if sbo_ind > 0
-0487             modelSBML.reaction(i).sboTerm=str2double(regexprep(model.rxnMiriams{i}.value{sbo_ind},'SBO:','','ignorecase'));
-0488             % remove the SBO term from rxnMiriams so the information is not
-0489             % duplicated in the "annotation" field later on
-0490             model.rxnMiriams{i}.name(sbo_ind) = [];
-0491             model.rxnMiriams{i}.value(sbo_ind) = [];
-0492         end
-0493     end
-0494 
-0495     %Export annotation information from rxnMiriams
-0496     if (~isempty(model.rxnMiriams{i}) && isfield(modelSBML.reaction(i),'annotation')) || ~isempty(model.eccodes{i})
-0497         modelSBML.reaction(i).annotation=['<annotation><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#" xmlns:bqbiol="http://biomodels.net/biology-qualifiers/" xmlns:bqmodel="http://biomodels.net/model-qualifiers/"><rdf:Description rdf:about="#meta_' model.rxns{i} '">'];
-0498         modelSBML.reaction(i).annotation=[modelSBML.reaction(i).annotation '<bqbiol:is><rdf:Bag>'];
-0499         if ~isempty(model.eccodes{i})
-0500             eccodes=regexp(model.eccodes{i},';','split');
-0501             for j=1:numel(eccodes)
-0502                 modelSBML.reaction(i).annotation=[modelSBML.reaction(i).annotation  '<rdf:li rdf:resource="https://identifiers.org/ec-code/' regexprep(eccodes{j},'ec-code/|EC','') '"/>'];
-0503             end
-0504         end
-0505         modelSBML.reaction(i).annotation=[modelSBML.reaction(i).annotation getMiriam(model.rxnMiriams{i}) '</rdf:Bag></bqbiol:is></rdf:Description></rdf:RDF></annotation>'];
-0506     end
-0507 
-0508     if isfield(modelSBML.reaction, 'name')
-0509         modelSBML.reaction(i).name=model.rxnNames{i};
-0510     end
-0511     if isfield(modelSBML.reaction, 'id')
-0512         modelSBML.reaction(i).id=model.rxns{i};
-0513     end
-0514 
-0515     %Add the information about reactants and products
-0516     involvedMets=addReactantsProducts(model,modelSBML,i);
-0517     for j=1:numel(involvedMets.reactant)
-0518         if j<numel(involvedMets.reactant)
-0519             modelSBML.reaction(i).reactant(j+1)=modelSBML.reaction(i).reactant(j);
-0520         end
-0521         modelSBML.reaction(i).reactant(j).species=involvedMets.reactant(j).species;
-0522         modelSBML.reaction(i).reactant(j).stoichiometry=involvedMets.reactant(j).stoichiometry;
-0523         modelSBML.reaction(i).reactant(j).isSetStoichiometry=involvedMets.reactant(j).isSetStoichiometry;
-0524         modelSBML.reaction(i).reactant(j).constant=involvedMets.reactant(j).constant;
-0525     end
-0526     if numel(involvedMets.reactant)==0
-0527         modelSBML.reaction(i).reactant='';
-0528     end
-0529     for j=1:numel(involvedMets.product)
-0530         if j<numel(involvedMets.product)
-0531             modelSBML.reaction(i).product(j+1)=modelSBML.reaction(i).product(j);
-0532         end
-0533         modelSBML.reaction(i).product(j).species=involvedMets.product(j).species;
-0534         modelSBML.reaction(i).product(j).stoichiometry=involvedMets.product(j).stoichiometry;
-0535         modelSBML.reaction(i).product(j).isSetStoichiometry=involvedMets.product(j).isSetStoichiometry;
-0536         modelSBML.reaction(i).product(j).constant=involvedMets.product(j).constant;
-0537     end
-0538     if numel(involvedMets.product)==0
-0539         modelSBML.reaction(i).product='';
-0540     end
-0541     %Export reversibility information. Reactions are irreversible by
-0542     %default
-0543     if model.rev(i)==1
-0544         modelSBML.reaction(i).reversible=1;
-0545     end
-0546     if isfield(model, 'rxnComps')
-0547         modelSBML.reaction(i).compartment=model.comps{model.rxnComps(i)};
-0548     end
-0549     if isfield(model, 'grRules')
-0550         modelSBML.reaction(i).fbc_geneProductAssociation.fbc_association.fbc_association=model.grRules{i};
-0551     end
-0552     modelSBML.reaction(i).fbc_lowerFluxBound=totalNames{i};
-0553     modelSBML.reaction(i).fbc_upperFluxBound=totalNames{length(model.lb)+i};
-0554 end
-0555 
-0556 %Prepare subSystems
-0557 if modelHasSubsystems
-0558     modelSBML.groups_group.groups_kind = 'partonomy';
-0559     modelSBML.groups_group.sboTerm     = 633;
-0560     grpTemplate = modelSBML.groups_group;
-0561 
-0562     % === 1) Normalize: make every entry a cell array of chars (vectorized) ===
-0563     isChar = cellfun(@ischar, model.subSystems);
-0564     model.subSystems(isChar)  = cellfun(@(s){s}, model.subSystems(isChar),  'UniformOutput', false);
-0565     model.subSystems(cellfun(@isempty, model.subSystems)) = {{}};
-0566 
-0567     % If some entries contain string scalars by mistake, coerce them. Also
-0568     % force each entry to a column cell array, so that reactions with
-0569     % different numbers of subsystems can be concatenated below (otherwise
-0570     % mixing e.g. 1x1 and 1x2 entries breaks vertcat):
-0571     model.subSystems = cellfun(@(c) reshape(cellfun(@char, c, 'UniformOutput', false), [], 1), model.subSystems, 'UniformOutput', false);
-0572 
-0573     % === 2) Flatten once: names and their reaction indices (vectorized) ===
-0574     flatNames = vertcat(model.subSystems{:});                    % Mx1 cellstr of all subsystem labels
-0575     if isempty(flatNames)
-0576         % Nothing to do: no subsystems present
-0577         return
-0578     end
-0579 
-0580     counts   = cellfun(@numel, model.subSystems);         % reactions -> how many subsystems
-0581     % For each reaction r, repeat r exactly counts(r) times
-0582     flatIdx  = arrayfun(@(r,c) repmat(r, c, 1), (1:numel(model.subSystems)).', counts, 'UniformOutput', false);
-0583     flatIdx  = vertcat(flatIdx{:});           % M×1 vector of reaction indices
-0584 
-0585     % === 3) Group in one shot: unique subsystems + members per subsystem ===
-0586     [subSystems, ~, g] = unique(flatNames, 'stable');          % stable preserves first appearance
-0587     membersIdx = accumarray(g, flatIdx, [], @(v){v});          % cell: one vector of r-idx per group
-0588     nSubs = numel(subSystems);
-0589 
-0590     % === 4) Preallocate and build SBML groups (single simple loop) ===
-0591     modelSBML.groups_group(1:nSubs) = grpTemplate;
-0592     groupIDs = "group" + (1:nSubs);
-0593 
-0594     if isfield(grpTemplate,'groups_member')
-0595         memTemplate = grpTemplate.groups_member;
-0596     else
-0597         memTemplate = struct('groups_idRef','');
-0598     end
-0599 
-0600     for i = 1:nSubs
-0601         rIdx       = membersIdx{i};
-0602         groupRXNs  = model.rxns(rIdx);
-0603         cgroup     = grpTemplate;
-0604 
-0605         % Preallocate and fill members
-0606         nM = numel(groupRXNs);
-0607         if nM > 0
-0608             cgroup.groups_member(1:nM) = memTemplate;
-0609             [cgroup.groups_member.groups_idRef] = deal(groupRXNs{:});
-0610         else
-0611             cgroup.groups_member = repmat(memTemplate, 0, 1);
-0612         end
-0613 
-0614         cgroup.groups_id   = char(groupIDs(i));     % keep as char for SBML compatibility
-0615         cgroup.groups_name = subSystems{i};
-0616         modelSBML.groups_group(i) = cgroup;
-0617     end
-0618 end
-0619 
-0620 
-0621 %Prepare fbc_objective subfield
-0622 
-0623 modelSBML.fbc_objective.fbc_type='maximize';
-0624 modelSBML.fbc_objective.fbc_id='obj';
-0625 
-0626 ind=find(model.c);
-0627 
-0628 if isempty(ind)
-0629     modelSBML.fbc_objective.fbc_fluxObjective.fbc_coefficient=0;
-0630 else
-0631     for i=1:length(ind)
-0632         %Copy the default values to the next index as long as it is not the
-0633         %last one
-0634         if i<numel(ind)
-0635             modelSBML.reaction(i+1)=modelSBML.reaction(i);
-0636         end
-0637         values=model.c(model.c~=0);
-0638         modelSBML.fbc_objective(i).fbc_fluxObjective.fbc_reaction=modelSBML.reaction(ind(i)).id;
-0639         modelSBML.fbc_objective(i).fbc_fluxObjective.fbc_coefficient=values(i);
-0640         modelSBML.fbc_objective(i).fbc_fluxObjective.isSetfbc_coefficient=1;
-0641     end
-0642 end
-0643 
-0644 modelSBML.fbc_activeObjective=modelSBML.fbc_objective.fbc_id;
-0645 
-0646 fbcStr=['http://www.sbml.org/sbml/level', num2str(sbmlLevel), '/version', num2str(sbmlVersion), '/fbc/version',num2str(sbmlPackageVersions(1))];
-0647 if modelHasSubsystems
-0648     groupStr=['http://www.sbml.org/sbml/level', num2str(sbmlLevel), '/version', num2str(sbmlVersion), '/groups/version',num2str(sbmlPackageVersions(2))];
-0649     modelSBML.namespaces=struct('prefix',{'','fbc','groups'},...
-0650         'uri',{['http://www.sbml.org/sbml/level', num2str(sbmlLevel), '/version', num2str(sbmlVersion), '/core'],...
-0651         fbcStr,groupStr});
-0652 else
-0653     modelSBML.namespaces=struct('prefix',{'','fbc'},...
-0654         'uri',{['http://www.sbml.org/sbml/level', num2str(sbmlLevel), '/version', num2str(sbmlVersion), '/core'],...
-0655         fbcStr});
-0656 end
-0657 
-0658 if sbmlPackageVersions(1) == 2
-0659     modelSBML.fbc_strict=1;
-0660     modelSBML.isSetfbc_strict = 1;
-0661 end
-0662 
-0663 modelSBML.rule=[];
-0664 modelSBML.constraint=[];
-0665 
-0666 [ravenDir,prevDir]=findRAVENroot();
-0667 fileName=checkFileExistence(fileName,1,true,false);
-0668 
-0669 OutputSBML_RAVEN(modelSBML,fileName,1,0,[1,0]);
-0670 end
-0671 
-0672 
-0673 function modelSBML=getSBMLStructure(sbmlLevel,sbmlVersion,sbmlPackages,sbmlPackageVersions)
-0674 %Returns the blank SBML model structure by using appropriate libSBML
-0675 %functions. This creates structure by considering three levels
-0676 
-0677 sbmlFieldNames=getStructureFieldnames('model',sbmlLevel,sbmlVersion,sbmlPackages,sbmlPackageVersions);
-0678 sbmlDefaultValues=getDefaultValues('model',sbmlLevel,sbmlVersion,sbmlPackages,sbmlPackageVersions);
-0679 
-0680 for i=1:numel(sbmlFieldNames)
-0681     modelSBML.(sbmlFieldNames{1,i})=sbmlDefaultValues{1,i};
-0682     sbmlSubfieldNames=getStructureFieldnames(sbmlFieldNames{1,i},sbmlLevel,sbmlVersion,sbmlPackages,sbmlPackageVersions);
-0683     sbmlSubfieldValues=getDefaultValues(sbmlFieldNames{1,i},sbmlLevel,sbmlVersion,sbmlPackages,sbmlPackageVersions);
-0684     if ~strcmp(sbmlFieldNames{1,i},'event') && ~strcmp(sbmlFieldNames{1,i},'functionDefinition') && ~strcmp(sbmlFieldNames{1,i},'initialAssignment')
-0685         for j=1:numel(sbmlSubfieldNames)
-0686             modelSBML.(sbmlFieldNames{1,i}).(sbmlSubfieldNames{1,j})=sbmlSubfieldValues{1,j};
-0687             sbmlSubsubfieldNames=getStructureFieldnames(sbmlSubfieldNames{1,j},sbmlLevel,sbmlVersion,sbmlPackages,sbmlPackageVersions);
-0688             sbmlSubsubfieldValues=getDefaultValues(sbmlSubfieldNames{1,j},sbmlLevel,sbmlVersion,sbmlPackages,sbmlPackageVersions);
-0689             if ~strcmp(sbmlSubfieldNames{1,j},'modifier') && ~strcmp(sbmlSubfieldNames{1,j},'kineticLaw')
-0690                 for k=1:numel(sbmlSubsubfieldNames)
-0691                     %'compartment' and 'species' fields are not supposed to
-0692                     %have their standalone structures if they are subfields
-0693                     %or subsubfields
-0694                     if ~strcmp(sbmlSubfieldNames{1,j},'compartment') && ~strcmp(sbmlSubfieldNames{1,j},'species')
-0695                         modelSBML.(sbmlFieldNames{1,i}).(sbmlSubfieldNames{1,j}).(sbmlSubsubfieldNames{1,k})=sbmlSubsubfieldValues{1,k};
-0696                     end
-0697                     %If it is fbc_association in the third level, we need
-0698                     %to establish the fourth level, since libSBML requires
-0699                     %it
-0700                     if strcmp(sbmlSubsubfieldNames{1,k},'fbc_association')
-0701                         fbc_associationFieldNames=getStructureFieldnames('fbc_association',sbmlLevel,sbmlVersion,sbmlPackages,sbmlPackageVersions);
-0702                         fbc_associationFieldValues=getDefaultValues('fbc_association',sbmlLevel,sbmlVersion,sbmlPackages,sbmlPackageVersions);
-0703                         for l=1:numel(fbc_associationFieldNames)
-0704                             modelSBML.(sbmlFieldNames{1,i}).(sbmlSubfieldNames{1,j}).(sbmlSubsubfieldNames{1,k}).(fbc_associationFieldNames{1,l})=fbc_associationFieldValues{1,l};
-0705                         end
-0706                     end
-0707                 end
-0708             end
-0709         end
-0710     end
-0711     if ~isstruct(modelSBML.(sbmlFieldNames{1,i}))
-0712         modelSBML.(sbmlFieldNames{1,i})=sbmlDefaultValues{1,i};
-0713     end
-0714 end
-0715 
-0716 modelSBML.unitDefinition.id='mmol_per_gDW_per_hr';
-0717 
-0718 unitFieldNames=getStructureFieldnames('unit',sbmlLevel,sbmlVersion,sbmlPackages,sbmlPackageVersions);
-0719 unitDefaultValues=getDefaultValues('unit',sbmlLevel,sbmlVersion,sbmlPackages,sbmlPackageVersions);
-0720 
-0721 kinds={'mole','gram','second'};
-0722 exponents=[1 -1 -1];
-0723 scales=[-3 0 0];
-0724 multipliers=[1 1 1*60*60];
-0725 
-0726 for i=1:numel(unitFieldNames)
-0727     modelSBML.unitDefinition.unit(1).(unitFieldNames{1,i})=unitDefaultValues{1,i};
-0728     for j=1:3
-0729         modelSBML.unitDefinition.unit(j).(unitFieldNames{1,i})=unitDefaultValues{1,i};
-0730         if strcmp(unitFieldNames{1,i},'kind')
-0731             modelSBML.unitDefinition.unit(j).(unitFieldNames{1,i})=kinds{j};
-0732         elseif strcmp(unitFieldNames{1,i},'exponent')
-0733             modelSBML.unitDefinition.unit(j).(unitFieldNames{1,i})=exponents(j);
-0734         elseif strcmp(unitFieldNames{1,i},'scale')
-0735             modelSBML.unitDefinition.unit(j).(unitFieldNames{1,i})=scales(j);
-0736         elseif strcmp(unitFieldNames{1,i},'multiplier')
-0737             modelSBML.unitDefinition.unit(j).(unitFieldNames{1,i})=multipliers(j);
-0738         end
-0739     end
-0740 end
-0741 end
-0742 
-0743 function miriamString=getMiriam(miriamStruct)
-0744 %Returns a string with list elements for a miriam structure ('<rdf:li
-0745 %rdf:resource="https://identifiers.org/go/GO:0005739"/>' for example). This
-0746 %is just to speed up things since this is done many times during the
-0747 %exporting
-0748 
-0749 miriamString='';
-0750 if isfield(miriamStruct,'name')
-0751     for i=1:numel(miriamStruct.name)
-0752         miriamString=[miriamString '<rdf:li rdf:resource="https://identifiers.org/' miriamStruct.name{i} '/' miriamStruct.value{i} '"/>'];
-0753     end
-0754 end
-0755 end
-0756 
-0757 function [tmp_Rxn]=addReactantsProducts(model,sbmlModel,i)
-0758 %This function provides reactants and products for particular reaction. The
-0759 %function was 'borrowed' from writeSBML in COBRA toolbox, lines 663-679
-0760 
-0761 met_idx = find(model.S(:, i));
-0762 tmp_Rxn.product=[];
-0763 tmp_Rxn.reactant=[];
-0764 for j_met=1:size(met_idx,1)
-0765     tmp_idx = met_idx(j_met,1);
-0766     sbml_tmp_species_ref.species = sbmlModel.species(tmp_idx).id;
-0767     met_stoich = model.S(tmp_idx, i);
-0768     sbml_tmp_species_ref.stoichiometry = abs(met_stoich);
-0769     sbml_tmp_species_ref.isSetStoichiometry=1;
-0770     sbml_tmp_species_ref.constant=1;
-0771     if (met_stoich > 0)
-0772         tmp_Rxn.product = [ tmp_Rxn.product, sbml_tmp_species_ref ];
-0773     else
-0774         tmp_Rxn.reactant = [ tmp_Rxn.reactant, sbml_tmp_species_ref];
-0775     end
-0776 end
-0777 end
-0778 
-0779 function vecT = columnVector(vec)
-0780 % Code below taken from COBRA Toolbox under GNU General Public License v3.0
-0781 % license file in readme/GPL.MD.
-0782 %
-0783 % Converts a vector to a column vector
-0784 %
-0785 % USAGE:
-0786 %
-0787 %   vecT = columnVector(vec)
-0788 %
-0789 % INPUT:
-0790 %   vec:     a vector
-0791 %
-0792 % OUTPUT:
-0793 %   vecT:    a column vector
-0794 
-0795 [n, m] = size(vec);
-0796 
-0797 if n < m
-0798     vecT = vec';
-0799 else
-0800     vecT = vec;
-0801 end
-0802 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/io/exportModelToSIF.html b/doc/io/exportModelToSIF.html deleted file mode 100644 index 191c50388..000000000 --- a/doc/io/exportModelToSIF.html +++ /dev/null @@ -1,148 +0,0 @@ - - - - Description of exportModelToSIF - - - - - - - - - -
Home > io > exportModelToSIF.m
- - - -

exportModelToSIF -

- -

PURPOSE ^

-
exportModelToSIF
- -

SYNOPSIS ^

-
function exportModelToSIF(model,fileName,graphType,rxnLabels,metLabels)
- -

DESCRIPTION ^

-
 exportModelToSIF
-   Exports a constraint-based model to a SIF file
-
-   model         a model structure
-   fileName      the filename  to export the model to
-   graphType     the type of graph to export to (optional, default 'rc')
-                 'rc'  reaction-compound
-                 'rr'  reaction-reaction
-                 'cc'  compound-compound
-   rxnLabels     cell array with labels for reactions (optional, default
-                 model.rxns)
-   metLabels     cell array with labels for metabolites (optional, default
-                 model.mets)
-
- Usage: exportModelToSIF(model,fileName,graphType,rxnLabels,metLabels)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function exportModelToSIF(model,fileName,graphType,rxnLabels,metLabels)
-0002 % exportModelToSIF
-0003 %   Exports a constraint-based model to a SIF file
-0004 %
-0005 %   model         a model structure
-0006 %   fileName      the filename  to export the model to
-0007 %   graphType     the type of graph to export to (optional, default 'rc')
-0008 %                 'rc'  reaction-compound
-0009 %                 'rr'  reaction-reaction
-0010 %                 'cc'  compound-compound
-0011 %   rxnLabels     cell array with labels for reactions (optional, default
-0012 %                 model.rxns)
-0013 %   metLabels     cell array with labels for metabolites (optional, default
-0014 %                 model.mets)
-0015 %
-0016 % Usage: exportModelToSIF(model,fileName,graphType,rxnLabels,metLabels)
-0017 fileName=char(fileName);
-0018 if nargin<3
-0019     graphType='rc';
-0020 else
-0021     graphType=char(graphType);
-0022 end
-0023 
-0024 if nargin<4 || isempty(rxnLabels)
-0025     rxnLabels=model.rxns;
-0026 else
-0027     rxnLabels=convertCharArray(rxnLabels);
-0028 end
-0029 if nargin<5 || isempty(metLabels)
-0030     metLabels=model.mets;
-0031 else
-0032     metLabels=convertCharArray(metLabels);
-0033 end
-0034 
-0035 if ~strcmpi(graphType,'rc') && ~strcmpi(graphType,'rr') && ~strcmpi(graphType,'cc')
-0036     EM='The graph type is incorrect';
-0037     dispEM(EM);
-0038 end
-0039 
-0040 if numel(rxnLabels)~=numel(unique(rxnLabels))
-0041     EM='Not all reaction labels are unique';
-0042     dispEM(EM,false);
-0043 end
-0044 if numel(metLabels)~=numel(unique(metLabels))
-0045     EM='Not all metabolite labels are unique';
-0046     dispEM(EM,false);
-0047 end
-0048 
-0049 if strcmpi(graphType,'rc')
-0050     G=model.S;
-0051     A=rxnLabels;
-0052     B=metLabels;
-0053 end
-0054 if strcmpi(graphType,'rr')
-0055     G=model.S'*model.S;
-0056     A=rxnLabels;
-0057     B=rxnLabels;
-0058 end
-0059 if strcmpi(graphType,'cc')
-0060     %A metabolite is linked to all products of the reactions that it
-0061     %participates in If G=model.S*model.S' then all connections will be
-0062     %double, which looks weird
-0063     irrevModel=convertToIrrev(model);
-0064     G=sparse(numel(model.mets),numel(model.mets));
-0065     for i=1:numel(model.mets)
-0066         I=irrevModel.S(i,:)<0; %Get the reactions in which it is a substrate
-0067         [J, ~]=find(irrevModel.S(:,I)>0);
-0068         G(J,i)=1;
-0069     end
-0070     A=metLabels;
-0071     B=metLabels;
-0072 end
-0073 
-0074 fid=fopen(fileName,'w');
-0075 
-0076 for i=1:size(G,2)
-0077     I=G(:,i)~=0;
-0078     nodes=setdiff(B(I),A(i)); %Don't include connection to itself
-0079     if ~isempty(nodes)
-0080         nNodes=numel(nodes);
-0081         nodes(1:nNodes-1)=strcat(nodes(1:nNodes-1),{'\t'});
-0082         fullString=[nodes{:}];
-0083         fprintf(fid,[A{i} '\t' graphType '\t' fullString '\n']);
-0084     end
-0085 end
-0086 fclose(fid);
-0087 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/io/exportToExcelFormat.html b/doc/io/exportToExcelFormat.html deleted file mode 100644 index 72adbf32a..000000000 --- a/doc/io/exportToExcelFormat.html +++ /dev/null @@ -1,459 +0,0 @@ - - - - Description of exportToExcelFormat - - - - - - - - - -
Home > io > exportToExcelFormat.m
- - - -

exportToExcelFormat -

- -

PURPOSE ^

-
exportToExcelFormat
- -

SYNOPSIS ^

-
function exportToExcelFormat(model,fileName,sortIds)
- -

DESCRIPTION ^

-
 exportToExcelFormat
-   Exports a model structure to the Microsoft Excel model format
-
- Input:
-   model       a model structure
-   fileName    file name of the Excel file. Only xlsx format is supported.
-               In order to preserve backward compatibility this could also
-               be only a path, in which case the model is exported to a
-               set of tab-delimited text files via exportToTabDelimited.
-               A dialog window will open if fileName is empty.
-   sortIds     logical whether metabolites, reactions and genes should be
-               sorted alphabetically by their identifiers (optional,
-               default false)
-
- Usage: exportToExcelFormat(model, fileName, sortIds)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function exportToExcelFormat(model,fileName,sortIds)
-0002 % exportToExcelFormat
-0003 %   Exports a model structure to the Microsoft Excel model format
-0004 %
-0005 % Input:
-0006 %   model       a model structure
-0007 %   fileName    file name of the Excel file. Only xlsx format is supported.
-0008 %               In order to preserve backward compatibility this could also
-0009 %               be only a path, in which case the model is exported to a
-0010 %               set of tab-delimited text files via exportToTabDelimited.
-0011 %               A dialog window will open if fileName is empty.
-0012 %   sortIds     logical whether metabolites, reactions and genes should be
-0013 %               sorted alphabetically by their identifiers (optional,
-0014 %               default false)
-0015 %
-0016 % Usage: exportToExcelFormat(model, fileName, sortIds)
-0017 
-0018 if nargin<2 || isempty(fileName)
-0019     [fileName, pathName] = uiputfile('*.xlsx', 'Select file for model export',[model.id '.xlsx']);
-0020     if fileName == 0
-0021         error('You should provide a file location')
-0022     else
-0023         fileName = fullfile(pathName,fileName);
-0024     end
-0025 end
-0026 fileName=char(fileName);
-0027 if nargin<3
-0028     sortIds=false;
-0029 end
-0030 if sortIds==true
-0031     model=sortIdentifiers(model);
-0032 end
-0033 
-0034 checkModelStruct(model);
-0035 
-0036 addList = matlab.addons.installedAddons;
-0037 if any(strcmpi(addList.Name,'Text Analytics Toolbox'))
-0038     error(['exportToExcelFormat is incompatible with MATLAB Text Analytics Toolbox. ' ...
-0039            'Further instructions => https://github.com/SysBioChalmers/RAVEN/issues/55#issuecomment-1514369299'])
-0040 end
-0041 
-0042 [~, A, B]=fileparts(fileName);
-0043 
-0044 %If a path was used call on exportToTabDelimited instead
-0045 if ~any(A) || ~any(B)
-0046     exportToTabDelimited(model,fileName);
-0047     return;
-0048 end
-0049 
-0050 if ~strcmpi(B,'.xlsx')
-0051     EM='As of RAVEN version 1.9, only export to xlsx format is supported';
-0052     dispEM(EM);
-0053 end
-0054 
-0055 import java.io.File;
-0056 import java.io.FileOutputStream;
-0057 import java.io.IOException;
-0058 
-0059 %Remove the output file if it already exists
-0060 if isfile(fileName)
-0061     delete(fileName);
-0062 end
-0063 
-0064 %Load an empty workbook
-0065 wb=loadWorkbook(fileName,true);
-0066 
-0067 %Construct equations
-0068 model.equations=constructEquations(model,model.rxns,true);
-0069 
-0070 %Check if it should print genes
-0071 if isfield(model,'grRules')
-0072     rules=model.grRules;
-0073 else
-0074     rules=[];
-0075 end
-0076 
-0077 %Check if the model has default upper/lower bounds. This determines if
-0078 %those values should be printed or not
-0079 hasDefaultLB=false;
-0080 hasDefaultUB=false;
-0081 if isfield(model,'annotation')
-0082     if isfield(model.annotation,'defaultLB')
-0083         hasDefaultLB=true;
-0084     end
-0085     if isfield(model.annotation,'defaultUB')
-0086         hasDefaultUB=true;
-0087     end
-0088 end
-0089 
-0090 %Add the RXNS sheet
-0091 
-0092 %Create the header row
-0093 headers={'#';'ID';'NAME';'EQUATION';'EC-NUMBER';'GENE ASSOCIATION';'LOWER BOUND';'UPPER BOUND';'OBJECTIVE';'COMPARTMENT';'MIRIAM';'SUBSYSTEM';'REPLACEMENT ID';'NOTE';'REFERENCE';'CONFIDENCE SCORE'};
-0094 
-0095 %Add empty comments
-0096 emptyColumn=cell(numel(model.rxns),1);
-0097 rxnSheet=emptyColumn;
-0098 
-0099 %Add the model fields
-0100 rxnSheet=[rxnSheet model.rxns];
-0101 
-0102 if isfield(model,'rxnNames')
-0103     rxnSheet=[rxnSheet model.rxnNames];
-0104 else
-0105     rxnSheet=[rxnSheet emptyColumn];
-0106 end
-0107 
-0108 rxnSheet=[rxnSheet model.equations];
-0109 
-0110 if isfield(model,'eccodes')
-0111     rxnSheet=[rxnSheet model.eccodes];
-0112 else
-0113     rxnSheet=[rxnSheet emptyColumn];
-0114 end
-0115 
-0116 if ~isempty(rules)
-0117     rxnSheet=[rxnSheet rules];
-0118 else
-0119     rxnSheet=[rxnSheet emptyColumn];
-0120 end
-0121 
-0122 lb=emptyColumn;
-0123 ub=emptyColumn;
-0124 objective=emptyColumn;
-0125 rxnMiriams=emptyColumn;
-0126 
-0127 for i=1:numel(model.rxns)
-0128     if isfield(model,'lb')
-0129         if hasDefaultLB==true
-0130             if model.rev(i)==1
-0131                 %If reversible, print only if different than defaultLB
-0132                 if model.lb(i) ~= model.annotation.defaultLB
-0133                     lb{i}=model.lb(i);
-0134                 end
-0135             else
-0136                 %If irreversible, print only for non-zero values
-0137                 if model.lb(i)~=0
-0138                     lb{i}=model.lb(i);
-0139                 end
-0140             end
-0141         else
-0142             lb{i}=model.lb(i);
-0143         end
-0144     end
-0145     
-0146     if isfield(model,'ub')
-0147         if hasDefaultUB==true
-0148             if model.ub(i) ~= model.annotation.defaultUB
-0149                 ub{i}=model.ub(i);
-0150             end
-0151         else
-0152             ub{i}=model.ub(i);
-0153         end
-0154     end
-0155     
-0156     if isfield(model,'c')
-0157         if model.c(i)~=0
-0158             objective{i}=model.c(i);
-0159         end
-0160     end
-0161     
-0162     if isfield(model,'rxnMiriams')
-0163         if ~isempty(model.rxnMiriams{i})
-0164             toPrint=[];
-0165             for j=1:numel(model.rxnMiriams{i}.name)
-0166                 toPrint=[toPrint strtrim(model.rxnMiriams{i}.name{j}) '/' strtrim(model.rxnMiriams{i}.value{j}) ';'];
-0167             end
-0168             rxnMiriams{i}=toPrint(1:end-1);
-0169         end
-0170     end
-0171 end
-0172 
-0173 rxnSheet=[rxnSheet lb];
-0174 rxnSheet=[rxnSheet ub];
-0175 rxnSheet=[rxnSheet objective];
-0176 
-0177 if isfield(model,'rxnComps')
-0178     rxnSheet=[rxnSheet model.comps(model.rxnComps)];
-0179 else
-0180     rxnSheet=[rxnSheet emptyColumn];
-0181 end
-0182 
-0183 rxnSheet=[rxnSheet rxnMiriams];
-0184 
-0185 subsystems='';
-0186 if isfield(model,'subSystems')
-0187     for i=1:numel(model.subSystems)
-0188         if ~iscell(model.subSystems{i})
-0189             model.subSystems{i} = {model.subSystems{i}};
-0190         end    
-0191         if ~isempty(model.subSystems{i,1})
-0192             subsystems{i,1}=strjoin(model.subSystems{i,1},';');
-0193         else
-0194             subsystems{i,1}='';
-0195         end
-0196     end
-0197     rxnSheet=[rxnSheet subsystems];
-0198 else
-0199     rxnSheet=[rxnSheet emptyColumn];
-0200 end
-0201 
-0202 %For REPLACEMENT ID which isn't in the model
-0203 rxnSheet=[rxnSheet emptyColumn];
-0204 
-0205 if isfield(model,'rxnNotes')
-0206     rxnSheet=[rxnSheet model.rxnNotes];
-0207 else
-0208     rxnSheet=[rxnSheet emptyColumn];
-0209 end
-0210 
-0211 if isfield(model,'rxnReferences')
-0212     rxnSheet=[rxnSheet model.rxnReferences];
-0213 else
-0214     rxnSheet=[rxnSheet emptyColumn];
-0215 end
-0216 
-0217 if isfield(model,'rxnConfidenceScores')
-0218     rxnSheet=[rxnSheet num2cell(model.rxnConfidenceScores)];
-0219 else
-0220     rxnSheet=[rxnSheet emptyColumn];
-0221 end
-0222 
-0223 wb=writeSheet(wb,'RXNS',0,headers,[],rxnSheet);
-0224 
-0225 headers={'#';'ID';'NAME';'UNCONSTRAINED';'MIRIAM';'COMPOSITION';'InChI';'COMPARTMENT';'REPLACEMENT ID';'CHARGE'};
-0226 
-0227 metSheet=cell(numel(model.mets),numel(headers));
-0228 
-0229 for i=1:numel(model.mets)
-0230     metSheet{i,2}=[model.metNames{i} '[' model.comps{model.metComps(i)} ']'];
-0231     
-0232     if isfield(model,'metNames')
-0233         metSheet(i,3)=model.metNames(i);
-0234     end
-0235     
-0236     if isfield(model,'unconstrained')
-0237         if model.unconstrained(i)~=0
-0238             metSheet{i,4}=true;
-0239         end
-0240     end
-0241     
-0242     if isfield(model,'metMiriams')
-0243         if ~isempty(model.metMiriams{i})
-0244             toPrint=[];
-0245             for j=1:numel(model.metMiriams{i}.name)
-0246                 toPrint=[toPrint strtrim(model.metMiriams{i}.name{j}) '/' strtrim(model.metMiriams{i}.value{j}) ';'];
-0247             end
-0248             metSheet{i,5}=toPrint(1:end-1);
-0249         end
-0250     end
-0251     
-0252     % Making sure that only these metFormulas are exported, which don't
-0253     % have InChI strings
-0254     if isfield(model,'metFormulas')
-0255         if isfield(model,'inchis')
-0256             if isempty(model.inchis{i})
-0257                 metSheet(i,6)=model.metFormulas(i);
-0258             end
-0259         else
-0260             metSheet(i,6)=model.metFormulas(i);
-0261         end
-0262     end
-0263     
-0264     if isfield(model,'inchis')
-0265         metSheet(i,7)=model.inchis(i);
-0266     end
-0267     
-0268     if isfield(model,'metComps')
-0269         metSheet(i,8)=model.comps(model.metComps(i));
-0270     end
-0271     
-0272     metSheet(i,9)=model.mets(i);
-0273     
-0274     if isfield(model,'metCharges')
-0275         metSheet{i,10}=model.metCharges(i);
-0276     end
-0277 end
-0278 
-0279 wb=writeSheet(wb,'METS',1,headers,[],metSheet);
-0280 
-0281 %Add the COMPS sheet
-0282 
-0283 %Create the header row
-0284 headers={'#';'ABBREVIATION';'NAME';'INSIDE';'MIRIAM'};
-0285 
-0286 compSheet=cell(numel(model.comps),numel(headers));
-0287 
-0288 for i=1:numel(model.comps)
-0289     compSheet(i,2)=model.comps(i);
-0290     
-0291     if isfield(model,'compNames')
-0292         compSheet(i,3)=model.compNames(i);
-0293     end
-0294     
-0295     if isfield(model,'compOutside')
-0296         compSheet(i,4)=model.compOutside(i);
-0297     end
-0298     
-0299     if isfield(model,'compMiriams')
-0300         if ~isempty(model.compMiriams{i})
-0301             toPrint=[];
-0302             for j=1:numel(model.compMiriams{i}.name)
-0303                 toPrint=[toPrint strtrim(model.compMiriams{i}.name{j}) '/' strtrim(model.compMiriams{i}.value{j}) ';'];
-0304             end
-0305             compSheet{i,5}=toPrint(1:end-1);
-0306         end
-0307     end
-0308 end
-0309 
-0310 wb=writeSheet(wb,'COMPS',2,headers,[],compSheet);
-0311 
-0312 %Add the GENES sheet
-0313 if isfield(model,'genes')
-0314     %Create the header row
-0315     headers={'#';'NAME';'MIRIAM';'SHORT NAME';'COMPARTMENT'};
-0316     
-0317     geneSheet=cell(numel(model.genes),numel(headers));
-0318     
-0319     for i=1:numel(model.genes)
-0320         geneSheet(i,2)=model.genes(i);
-0321         
-0322         if isfield(model,'geneMiriams')
-0323             if ~isempty(model.geneMiriams{i})
-0324                 toPrint=[];
-0325                 for j=1:numel(model.geneMiriams{i}.name)
-0326                     toPrint=[toPrint strtrim(model.geneMiriams{i}.name{j}) '/' strtrim(model.geneMiriams{i}.value{j}) ';'];
-0327                 end
-0328                 geneSheet{i,3}=toPrint(1:end-1);
-0329             end
-0330         end
-0331         if isfield(model,'geneShortNames')
-0332             geneSheet(i,4)=model.geneShortNames(i);
-0333         end
-0334         if isfield(model,'geneComps')
-0335             geneSheet(i,5)=model.comps(model.geneComps(i));
-0336         end
-0337     end
-0338     
-0339     wb=writeSheet(wb,'GENES',3,headers,[],geneSheet);
-0340 end
-0341 
-0342 %Add the MODEL sheet
-0343 
-0344 %Create the header row
-0345 headers={'#';'ID';'NAME';'TAXONOMY';'DEFAULT LOWER';'DEFAULT UPPER';'CONTACT GIVEN NAME';'CONTACT FAMILY NAME';'CONTACT EMAIL';'ORGANIZATION';'NOTES'};
-0346 
-0347 modelSheet=cell(1,numel(headers));
-0348 
-0349 if ~isfield(model,'annotation')
-0350     model.annotation = [];
-0351 end
-0352 
-0353 if isfield(model,'id')
-0354     modelSheet{1,2}=model.id;
-0355 else
-0356     modelSheet{1,2}='blankID';
-0357 end
-0358 if isfield(model,'name')
-0359     modelSheet{1,3}=model.name;
-0360 else
-0361     modelSheet{1,3}='blankName';
-0362 end
-0363 if isfield(model.annotation,'taxonomy')
-0364     modelSheet{1,4}=model.annotation.taxonomy;
-0365 end
-0366 if isfield(model.annotation,'defaultLB')
-0367     modelSheet{1,5}=model.annotation.defaultLB;
-0368 end
-0369 if isfield(model.annotation,'defaultUB')
-0370     modelSheet{1,6}=model.annotation.defaultUB;
-0371 end
-0372 if isfield(model.annotation,'givenName')
-0373     modelSheet{1,7}=model.annotation.givenName;
-0374 end
-0375 if isfield(model.annotation,'familyName')
-0376     modelSheet{1,8}=model.annotation.familyName;
-0377 end
-0378 if isfield(model.annotation,'email')
-0379     modelSheet{1,9}=model.annotation.email;
-0380 end
-0381 if isfield(model.annotation,'organization')
-0382     modelSheet{1,10}=model.annotation.organization;
-0383 end
-0384 if isfield(model.annotation,'note')
-0385     modelSheet{1,11}=model.annotation.note;
-0386 end
-0387 
-0388 if isfield(model,'genes')
-0389     wb=writeSheet(wb,'MODEL',4,headers,[],modelSheet);
-0390 else
-0391     wb=writeSheet(wb,'MODEL',3,headers,[],modelSheet);
-0392 end
-0393 
-0394 %Open the output stream
-0395 out = FileOutputStream(fileName);
-0396 wb.write(out);
-0397 out.close();
-0398 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/io/exportToTabDelimited.html b/doc/io/exportToTabDelimited.html deleted file mode 100644 index 11fe1e429..000000000 --- a/doc/io/exportToTabDelimited.html +++ /dev/null @@ -1,407 +0,0 @@ - - - - Description of exportToTabDelimited - - - - - - - - - -
Home > io > exportToTabDelimited.m
- - - -

exportToTabDelimited -

- -

PURPOSE ^

-
exportToTabDelimited
- -

SYNOPSIS ^

-
function exportToTabDelimited(model,path,sortIds)
- -

DESCRIPTION ^

-
 exportToTabDelimited
-   Exports a model structure to a set of tab-delimited text files
-
-   model    a model structure
-   path    the path to export to. The resulting text files will be saved
-           under the names excelRxns.txt, excelMets.txt, excelGenes.txt,
-           excelModel.txt, and excelComps.txt
-   sortIds logical whether metabolites, reactions and genes should be
-           sorted alphabetically by their identifiers (optional, default false)
-
-   NOTE: This functionality was previously a part of exportToExcelFormat.
-         The naming of the resulting text files is to preserve backward
-         compatibility
-
-   NOTE: No checks are made regarding the correctness of the model. Use
-         checkModelStruct to identify problems in the model structure
-
- Usage: exportToTabDelimited(model,path,sortIds)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function exportToTabDelimited(model,path,sortIds)
-0002 % exportToTabDelimited
-0003 %   Exports a model structure to a set of tab-delimited text files
-0004 %
-0005 %   model    a model structure
-0006 %   path    the path to export to. The resulting text files will be saved
-0007 %           under the names excelRxns.txt, excelMets.txt, excelGenes.txt,
-0008 %           excelModel.txt, and excelComps.txt
-0009 %   sortIds logical whether metabolites, reactions and genes should be
-0010 %           sorted alphabetically by their identifiers (optional, default false)
-0011 %
-0012 %   NOTE: This functionality was previously a part of exportToExcelFormat.
-0013 %         The naming of the resulting text files is to preserve backward
-0014 %         compatibility
-0015 %
-0016 %   NOTE: No checks are made regarding the correctness of the model. Use
-0017 %         checkModelStruct to identify problems in the model structure
-0018 %
-0019 % Usage: exportToTabDelimited(model,path,sortIds)
-0020 
-0021 if nargin<2
-0022     path='./';
-0023 end
-0024 if nargin<3
-0025     sortIds=false;
-0026 end
-0027 if sortIds==true
-0028     model=sortIdentifiers(model);
-0029 end
-0030 
-0031 %If the folder doesn't exist then create it
-0032 if ~isfolder(path)
-0033     mkdir(path);
-0034 end
-0035 
-0036 %Remove the files if they already exist
-0037 if isfile(fullfile(path,'excelRxns.txt'))
-0038     delete(fullfile(path,'excelRxns.txt'));
-0039 end
-0040 if isfile(fullfile(path,'excelMets.txt'))
-0041     delete(fullfile(path,'excelMets.txt'));
-0042 end
-0043 if isfile(fullfile(path,'excelGenes.txt'))
-0044     delete(fullfile(path,'excelGenes.txt'));
-0045 end
-0046 if isfile(fullfile(path,'excelModel.txt'))
-0047     delete(fullfile(path,'excelModel.txt'));
-0048 end
-0049 if isfile(fullfile(path,'excelComps.txt'))
-0050     delete(fullfile(path,'excelComps.txt'));
-0051 end
-0052 
-0053 %Construct equations
-0054 model.equations=constructEquations(model,model.rxns,true);
-0055 
-0056 %Open for printing the rxn sheet
-0057 rxnFile=fopen(fullfile(path,'excelRxns.txt'),'wt');
-0058 
-0059 %Print header
-0060 fprintf(rxnFile,'#\tID\tNAME\tEQUATION\tEC-NUMBER\tGENE ASSOCIATION\tLOWER BOUND\tUPPER BOUND\tOBJECTIVE\tCOMPARTMENT\tMIRIAM\tSUBSYSTEM\tREPLACEMENT ID\tNOTE\tREFERENCE\tCONFIDENCE SCORE\n');
-0061 
-0062 %Loop through the reactions
-0063 for i=1:numel(model.rxns)
-0064     fprintf(rxnFile,['\t' model.rxns{i} '\t' model.rxnNames{i} '\t' model.equations{i} '\t']);
-0065     
-0066     if isfield(model,'eccodes')
-0067         fprintf(rxnFile,[model.eccodes{i} '\t']);
-0068     else
-0069         fprintf(rxnFile,'\t');
-0070     end
-0071     
-0072     if isfield(model,'grRules')
-0073         fprintf(rxnFile,[model.grRules{i} '\t']);
-0074     else
-0075         fprintf(rxnFile,'\t');
-0076     end
-0077     
-0078     %Print bounds and objectives
-0079     fprintf(rxnFile,[num2str(model.lb(i)) '\t' num2str(model.ub(i)) '\t']);
-0080     
-0081     if model.c(i)~=0
-0082         fprintf(rxnFile,[num2str(model.c(i)) '\t' ]);
-0083     else
-0084         fprintf(rxnFile,'\t');
-0085     end
-0086     
-0087     if isfield(model,'rxnComps')
-0088         fprintf(rxnFile,[model.comps{model.rxnComps(i)} '\t']);
-0089     else
-0090         fprintf(rxnFile,'\t');
-0091     end
-0092     
-0093     if isfield(model,'rxnMiriams')
-0094         if ~isempty(model.rxnMiriams{i})
-0095             toPrint=[];
-0096             for j=1:numel(model.rxnMiriams{i}.name)
-0097                 toPrint=[toPrint strtrim(model.rxnMiriams{i}.name{j}) '/' strtrim(model.rxnMiriams{i}.value{j}) ';'];
-0098             end
-0099             fprintf(rxnFile,[toPrint(1:end-1) '\t']);
-0100         else
-0101             fprintf(rxnFile,'\t');
-0102         end
-0103     else
-0104         fprintf(rxnFile,'\t');
-0105     end
-0106     
-0107     if isfield(model,'subSystems')
-0108         if ~isempty(model.subSystems{i})
-0109             if ~iscell(model.subSystems{i})
-0110                 model.subSystems{i} = {model.subSystems{i}};
-0111             end    
-0112             fprintf(rxnFile,[strjoin(model.subSystems{i,1},';') '\t']);
-0113         else
-0114             fprintf(rxnFile,'\t');
-0115         end
-0116     end
-0117     
-0118     %Print replacement IDs
-0119     fprintf(rxnFile,'\t');
-0120     
-0121     if isfield(model,'rxnNotes')
-0122         fprintf(rxnFile,[model.rxnNotes{i} '\t']);
-0123     else
-0124         fprintf(rxnFile,'\t');
-0125     end
-0126     
-0127     if isfield(model,'rxnReferences')
-0128         fprintf(rxnFile,[model.rxnReferences{i} '\t']);
-0129     else
-0130         fprintf(rxnFile,'\t');
-0131     end
-0132     
-0133     if isfield(model,'rxnConfidenceScores')
-0134         fprintf(rxnFile,[num2str(model.rxnConfidenceScores(i)) '\t' ]);
-0135     else
-0136         fprintf(rxnFile,'\t');
-0137     end
-0138     
-0139     fprintf(rxnFile,'\n');
-0140 end
-0141 
-0142 fclose(rxnFile);
-0143 
-0144 %Open for printing the metabolites sheet
-0145 metFile=fopen(fullfile(path,'excelMets.txt'),'wt');
-0146 
-0147 %Print header
-0148 fprintf(metFile,'#\tID\tNAME\tUNCONSTRAINED\tMIRIAM\tCOMPOSITION\tInChI\tCOMPARTMENT\tREPLACEMENT ID\tMETS FIELD\tCHARGE\n');
-0149 
-0150 %Loop through the metabolites
-0151 for i=1:numel(model.mets)
-0152     fprintf(metFile,['\t' model.metNames{i} '[' model.comps{model.metComps(i)} ']\t' model.metNames{i} '\t']);
-0153     
-0154     if isfield(model,'unconstrained')
-0155         if model.unconstrained(i)~=0
-0156             fprintf(metFile,'TRUE\t');
-0157         else
-0158             fprintf(metFile,'\t');
-0159         end
-0160     else
-0161         fprintf(metFile,'\t');
-0162     end
-0163     
-0164     if isfield(model,'metMiriams')
-0165         if ~isempty(model.metMiriams{i})
-0166             toPrint=[];
-0167             for j=1:numel(model.metMiriams{i}.name)
-0168                 toPrint=[toPrint strtrim(model.metMiriams{i}.name{j}) '/' strtrim(model.metMiriams{i}.value{j}) ';'];
-0169             end
-0170             fprintf(rxnFile,[toPrint(1:end-1) '\t']);
-0171         else
-0172             fprintf(metFile,'\t');
-0173         end
-0174     else
-0175         fprintf(metFile,'\t');
-0176     end
-0177     
-0178     if isfield(model,'metFormulas')
-0179         fprintf(metFile,[model.metFormulas{i} '\t']);
-0180     else
-0181         fprintf(metFile,'\t');
-0182     end
-0183     
-0184     if isfield(model,'inchis')
-0185         fprintf(metFile,[model.inchis{i} '\t']);
-0186     else
-0187         fprintf(metFile,'\t');
-0188     end
-0189     
-0190     fprintf(metFile,[model.comps{model.metComps(i)} '\t']);
-0191     
-0192     %There can be no replacement IDs in the structure, but it has to be
-0193     %something to give working met IDs.
-0194     fprintf(metFile,['m' int2str(i) '\t']);
-0195     
-0196     %Print the model.mets field. The reason for not putting this as
-0197     %replacement ID is that it's not guaranteed to be a valid SBML id.
-0198     fprintf(metFile,[model.mets{i} '\t']);
-0199     
-0200     if isfield(model,'metCharges')
-0201         fprintf(metFile,[num2str(model.metCharges(i)) '\t']);
-0202     else
-0203         fprintf(metFile,'\t');
-0204     end
-0205     
-0206     fprintf(metFile,'\n');
-0207 end
-0208 
-0209 fclose(metFile);
-0210 
-0211 if isfield(model,'genes')
-0212     %Open for printing the genes sheet
-0213     geneFile=fopen(fullfile(path,'excelGenes.txt'),'wt');
-0214     
-0215     %Print header
-0216     fprintf(geneFile,'#\tNAME\tMIRIAM\tSHORT NAME\tCOMPARTMENT\n');
-0217     
-0218     %Loop through the genes
-0219     for i=1:numel(model.genes)
-0220         fprintf(geneFile,['\t' model.genes{i} '\t']);
-0221         
-0222         if isfield(model,'geneMiriams')
-0223             if ~isempty(model.geneMiriams{i})
-0224                 toPrint=[];
-0225                 for j=1:numel(model.geneMiriams{i}.name)
-0226                     toPrint=[toPrint strtrim(model.geneMiriams{i}.name{j}) '/' strtrim(model.geneMiriams{i}.value{j}) ';'];
-0227                 end
-0228                 fprintf(geneFile,[toPrint(1:end-1) '\t']);
-0229             else
-0230                 fprintf(geneFile,'\t');
-0231             end
-0232         else
-0233             fprintf(geneFile,'\t');
-0234         end
-0235         
-0236         if isfield(model,'geneShortNames')
-0237             fprintf(geneFile,[model.geneShortNames{i} '\t']);
-0238         else
-0239             fprintf(geneFile,'\t');
-0240         end
-0241         
-0242         if isfield(model,'geneComps')
-0243             fprintf(geneFile,[model.comps{model.geneComps(i)} '\t']);
-0244         else
-0245             fprintf(geneFile,'\t');
-0246         end
-0247         
-0248         fprintf(geneFile,'\n');
-0249     end
-0250     fclose(geneFile);
-0251 end
-0252 
-0253 if isfield(model,'id')
-0254     %Open for printing the model sheet
-0255     modelFile=fopen(fullfile(path,'excelModel.txt'),'wt');
-0256     
-0257     %Print header
-0258     fprintf(geneFile,'#\tID\tNAME\tDEFAULT LOWER\tDEFAULT UPPER\tCONTACT GIVEN NAME\tCONTACT FAMILY NAME\tCONTACT EMAIL\tORGANIZATION\tTAXONOMY\tNOTES\n');
-0259     
-0260     %Print model ID and name. It is assumed that the default lower/upper
-0261     %bound correspond to min/max of the bounds
-0262     toPrint=['\t' model.id '\t' model.name '\t'];
-0263     if isfield(model,'annotation')
-0264         if isfield(model.annotation,'defaultLB')
-0265             toPrint=[toPrint num2str(model.annotation.defaultLB) '\t'];
-0266         else
-0267             toPrint=[toPrint num2str(min(model.lb)) '\t'];
-0268         end
-0269         if isfield(model.annotation,'defaultUB')
-0270             toPrint=[toPrint num2str(model.annotation.defaultUB) '\t'];
-0271         else
-0272             toPrint=[toPrint num2str(max(model.ub)) '\t'];
-0273         end
-0274         if isfield(model.annotation,'givenName')
-0275             toPrint=[toPrint model.annotation.givenName '\t'];
-0276         else
-0277             toPrint=[toPrint '\t'];
-0278         end
-0279         if isfield(model.annotation,'familyName')
-0280             toPrint=[toPrint model.annotation.familyName '\t'];
-0281         else
-0282             toPrint=[toPrint '\t'];
-0283         end
-0284         if isfield(model.annotation,'email')
-0285             toPrint=[toPrint model.annotation.email '\t'];
-0286         else
-0287             toPrint=[toPrint '\t'];
-0288         end
-0289         if isfield(model.annotation,'organization')
-0290             toPrint=[toPrint model.annotation.organization '\t'];
-0291         else
-0292             toPrint=[toPrint '\t'];
-0293         end
-0294         if isfield(model.annotation,'taxonomy')
-0295             toPrint=[toPrint model.annotation.taxonomy '\t'];
-0296         else
-0297             toPrint=[toPrint '\t'];
-0298         end
-0299         if isfield(model.annotation,'note')
-0300             toPrint=[toPrint model.annotation.note '\t'];
-0301         else
-0302             toPrint=[toPrint '\t'];
-0303         end
-0304     else
-0305         toPrint=[toPrint num2str(min(model.lb)) '\t' num2str(max(model.ub)) '\t\t\t\t\t\t\n'];
-0306     end
-0307     fprintf(modelFile,toPrint);
-0308     fclose(modelFile);
-0309 end
-0310 
-0311 if isfield(model,'comps')
-0312     %Open for printing the model sheet
-0313     compsFile=fopen(fullfile(path,'excelComps.txt'),'wt');
-0314     
-0315     %Print header
-0316     fprintf(compsFile,'#\tABBREVIATION\tNAME\tINSIDE\tMIRIAM\n');
-0317     
-0318     for i=1:numel(model.comps)
-0319         toPrint=['\t' model.comps{i} '\t' model.compNames{i} '\t'];
-0320         if isfield(model,'compOutside')
-0321             toPrint=[toPrint model.compOutside{i} '\t'];
-0322         else
-0323             toPrint=[toPrint '\t'];
-0324         end
-0325         if isfield(model,'compMiriams')
-0326             if ~isempty(model.compMiriams{i})
-0327                 for j=1:numel(model.compMiriams{i}.name)
-0328                     toPrint=[toPrint strtrim(model.compMiriams{i}.name{j}) '/' strtrim(model.compMiriams{i}.value{j}) ';'];
-0329                 end
-0330                 toPrint(end)=[];
-0331                 toPrint=[toPrint '\t'];
-0332             else
-0333                 toPrint=[toPrint '\t'];
-0334             end
-0335         else
-0336             toPrint=[toPrint '\t'];
-0337         end
-0338         toPrint=[toPrint '\n'];
-0339         fprintf(compsFile,toPrint);
-0340     end
-0341     fclose(compsFile);
-0342 end
-0343 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/io/getFullPath.html b/doc/io/getFullPath.html deleted file mode 100644 index 63e4a39b0..000000000 --- a/doc/io/getFullPath.html +++ /dev/null @@ -1,439 +0,0 @@ - - - - Description of getFullPath - - - - - - - - - -
Home > io > getFullPath.m
- - - -

getFullPath -

- -

PURPOSE ^

-
getFullPath - Get absolute canonical path of a file or folder
- -

SYNOPSIS ^

-
function File = getFullPath(File, Style)
- -

DESCRIPTION ^

-
 getFullPath - Get absolute canonical path of a file or folder
- Absolute path names are safer than relative paths, when e.g. a GUI or TIMER
- callback changes the current directory. Only canonical paths without "." and
- ".." can be recognized uniquely.
- Long path names (>259 characters) require a magic initial key "\\?\" to be
- handled by Windows API functions, e.g. for Matlab's FOPEN, DIR and EXIST.
-
- FullName = getFullPath(Name, Style)
- INPUT:
-   Name:  String or cell string, absolute or relative name of a file or
-          folder. The path need not exist. Unicode strings, UNC paths and long
-          names are supported.
-   Style: Style of the output as string, optional, default: 'auto'.
-          'auto': Add '\\?\' or '\\?\UNC\' for long names on demand.
-          'lean': Magic string is not added.
-          'fat':  Magic string is added for short names also.
-          The Style is ignored when not running under Windows.
-
- OUTPUT:
-   FullName: Absolute canonical path name as string or cell string.
-          For empty strings the current directory is replied.
-          '\\?\' or '\\?\UNC' is added on demand.
-
- NOTE: The M- and the MEX-version create the same results, the faster MEX
-   function works under Windows only.
-   Some functions of the Windows-API still do not support long file names.
-   E.g. the Recycler and the Windows Explorer fail even with the magic '\\?\'
-   prefix. Some functions of Matlab accept 260 characters (value of MAX_PATH),
-   some at 259 already. Don't blame me.
-   The 'fat' style is useful e.g. when Matlab's DIR command is called for a
-   folder with les than 260 characters, but together with the file name this
-   limit is exceeded. Then "dir(getFullPath([folder, '\*.*], 'fat'))" helps.
-
- EXAMPLES:
-   cd(tempdir);                    % Assumed as 'C:\Temp' here
-   getFullPath('File.Ext')         % 'C:\Temp\File.Ext'
-   getFullPath('..\File.Ext')      % 'C:\File.Ext'
-   getFullPath('..\..\File.Ext')   % 'C:\File.Ext'
-   getFullPath('.\File.Ext')       % 'C:\Temp\File.Ext'
-   getFullPath('*.txt')            % 'C:\Temp\*.txt'
-   getFullPath('..')               % 'C:\'
-   getFullPath('..\..\..')         % 'C:\'
-   getFullPath('Folder\')          % 'C:\Temp\Folder\'
-   getFullPath('D:\A\..\B')        % 'D:\B'
-   getFullPath('\\Server\Folder\Sub\..\File.ext')
-                                   % '\\Server\Folder\File.ext'
-   getFullPath({'..', 'new'})      % {'C:\', 'C:\Temp\new'}
-   getFullPath('.', 'fat')         % '\\?\C:\Temp\File.Ext'
-
- COMPILE:
-   Automatic: InstallMex getFullPath.c uTest_getFullPath
-   Manual:    mex -O getFullPath.c
-   Download:  http://www.n-simon.de/mex
- Run the unit-test uTest_getFullPath after compiling.
-
- Tested: Matlab 6.5, 7.7, 7.8, 7.13, WinXP/32, Win7/64
-         Compiler: LCC2.4/3.8, BCC5.5, OWC1.8, MSVC2008/2010
- Assumed Compatibility: higher Matlab versions
- Author: Jan Simon, Heidelberg, (C) 2009-2013 matlab.THISYEAR(a)nMINUSsimon.de
-
- See also: CD, FULLFILE, FILEPARTS.
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
  • getFullPath getFullPath - Get absolute canonical path of a file or folder
-This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function File = getFullPath(File, Style)
-0002 % getFullPath - Get absolute canonical path of a file or folder
-0003 % Absolute path names are safer than relative paths, when e.g. a GUI or TIMER
-0004 % callback changes the current directory. Only canonical paths without "." and
-0005 % ".." can be recognized uniquely.
-0006 % Long path names (>259 characters) require a magic initial key "\\?\" to be
-0007 % handled by Windows API functions, e.g. for Matlab's FOPEN, DIR and EXIST.
-0008 %
-0009 % FullName = getFullPath(Name, Style)
-0010 % INPUT:
-0011 %   Name:  String or cell string, absolute or relative name of a file or
-0012 %          folder. The path need not exist. Unicode strings, UNC paths and long
-0013 %          names are supported.
-0014 %   Style: Style of the output as string, optional, default: 'auto'.
-0015 %          'auto': Add '\\?\' or '\\?\UNC\' for long names on demand.
-0016 %          'lean': Magic string is not added.
-0017 %          'fat':  Magic string is added for short names also.
-0018 %          The Style is ignored when not running under Windows.
-0019 %
-0020 % OUTPUT:
-0021 %   FullName: Absolute canonical path name as string or cell string.
-0022 %          For empty strings the current directory is replied.
-0023 %          '\\?\' or '\\?\UNC' is added on demand.
-0024 %
-0025 % NOTE: The M- and the MEX-version create the same results, the faster MEX
-0026 %   function works under Windows only.
-0027 %   Some functions of the Windows-API still do not support long file names.
-0028 %   E.g. the Recycler and the Windows Explorer fail even with the magic '\\?\'
-0029 %   prefix. Some functions of Matlab accept 260 characters (value of MAX_PATH),
-0030 %   some at 259 already. Don't blame me.
-0031 %   The 'fat' style is useful e.g. when Matlab's DIR command is called for a
-0032 %   folder with les than 260 characters, but together with the file name this
-0033 %   limit is exceeded. Then "dir(getFullPath([folder, '\*.*], 'fat'))" helps.
-0034 %
-0035 % EXAMPLES:
-0036 %   cd(tempdir);                    % Assumed as 'C:\Temp' here
-0037 %   getFullPath('File.Ext')         % 'C:\Temp\File.Ext'
-0038 %   getFullPath('..\File.Ext')      % 'C:\File.Ext'
-0039 %   getFullPath('..\..\File.Ext')   % 'C:\File.Ext'
-0040 %   getFullPath('.\File.Ext')       % 'C:\Temp\File.Ext'
-0041 %   getFullPath('*.txt')            % 'C:\Temp\*.txt'
-0042 %   getFullPath('..')               % 'C:\'
-0043 %   getFullPath('..\..\..')         % 'C:\'
-0044 %   getFullPath('Folder\')          % 'C:\Temp\Folder\'
-0045 %   getFullPath('D:\A\..\B')        % 'D:\B'
-0046 %   getFullPath('\\Server\Folder\Sub\..\File.ext')
-0047 %                                   % '\\Server\Folder\File.ext'
-0048 %   getFullPath({'..', 'new'})      % {'C:\', 'C:\Temp\new'}
-0049 %   getFullPath('.', 'fat')         % '\\?\C:\Temp\File.Ext'
-0050 %
-0051 % COMPILE:
-0052 %   Automatic: InstallMex getFullPath.c uTest_getFullPath
-0053 %   Manual:    mex -O getFullPath.c
-0054 %   Download:  http://www.n-simon.de/mex
-0055 % Run the unit-test uTest_getFullPath after compiling.
-0056 %
-0057 % Tested: Matlab 6.5, 7.7, 7.8, 7.13, WinXP/32, Win7/64
-0058 %         Compiler: LCC2.4/3.8, BCC5.5, OWC1.8, MSVC2008/2010
-0059 % Assumed Compatibility: higher Matlab versions
-0060 % Author: Jan Simon, Heidelberg, (C) 2009-2013 matlab.THISYEAR(a)nMINUSsimon.de
-0061 %
-0062 % See also: CD, FULLFILE, FILEPARTS.
-0063 
-0064 % $JRev: R-G V:032 Sum:7Xd/JS0+yfax Date:15-Jan-2013 01:06:12 $
-0065 % $License: BSD (use/copy/change/redistribute on own risk, mention the author) $
-0066 % $UnitTest: uTest_getFullPath $
-0067 % $File: Tools\GLFile\getFullPath.m $
-0068 % History:
-0069 % 001: 20-Apr-2010 22:28, Successor of Rel2AbsPath.
-0070 % 010: 27-Jul-2008 21:59, Consider leading separator in M-version also.
-0071 % 011: 24-Jan-2011 12:11, Cell strings, '~File' under linux.
-0072 %      Check of input types in the M-version.
-0073 % 015: 31-Mar-2011 10:48, BUGFIX: Accept [] as input as in the Mex version.
-0074 %      Thanks to Jiro Doke, who found this bug by running the test function for
-0075 %      the M-version.
-0076 % 020: 18-Oct-2011 00:57, BUGFIX: Linux version created bad results.
-0077 %      Thanks to Daniel.
-0078 % 024: 10-Dec-2011 14:00, Care for long names under Windows in M-version.
-0079 %      Improved the unittest function for Linux. Thanks to Paul Sexton.
-0080 % 025: 09-Aug-2012 14:00, In MEX: Paths starting with "\\" can be non-UNC.
-0081 %      The former version treated "\\?\C:\<longpath>\file" as UNC path and
-0082 %      replied "\\?\UNC\?\C:\<longpath>\file".
-0083 % 032: 12-Jan-2013 21:16, 'auto', 'lean' and 'fat' style.
-0084 
-0085 % Initialize: ==================================================================
-0086 % Do the work: =================================================================
-0087 
-0088 % #############################################
-0089 % ### USE THE MUCH FASTER MEX ON WINDOWS!!! ###
-0090 % #############################################
-0091 
-0092 % Difference between M- and Mex-version:
-0093 % - Mex does not work under MacOS/Unix.
-0094 % - Mex calls Windows API function getFullPath.
-0095 % - Mex is much faster.
-0096 
-0097 % Magix prefix for long Windows names:
-0098 if nargin < 2
-0099     Style = 'auto';
-0100 end
-0101 
-0102 % Handle cell strings: NOTE: It is faster to create a function
-0103 % @cell\getFullPath.m under Linux, but under Windows this would shadow the
-0104 % fast C-Mex.
-0105 if isa(File, 'cell')
-0106     for iC = 1:numel(File)
-0107         File{iC} = getFullPath(File{iC}, Style);
-0108     end
-0109     return;
-0110 end
-0111 
-0112 % Check this once only:
-0113 isWIN    = strncmpi(computer, 'PC', 2);
-0114 MAX_PATH = 260;
-0115 
-0116 % Warn once per session (disable this under Linux/MacOS):
-0117 persistent hasDataRead
-0118 if isempty(hasDataRead)
-0119     % Test this once only - there is no relation to the existence of
-0120     % DATAREAD!
-0121     %if isWIN
-0122     %   Show a warning, if the slower Matlab version is used - commented,
-0123     %   because this is not a problem and it might be even useful when the
-0124     %   MEX-folder is not inlcuded in the path yet.
-0125     %   warning('JSimon:getFullPath:NoMex', ...
-0126     %      ['getFullPath: Using slow Matlab-version instead of fast Mex.',
-0127     %      ...
-0128     %       char(10), 'Compile: InstallMex getFullPath.c']);
-0129     %end
-0130     
-0131     % DATAREAD is deprecated in 2011b, but still available. In Matlab 6.5,
-0132     % REGEXP does not know the 'split' command, therefore DATAREAD is
-0133     % preferred:
-0134     hasDataRead = ~isempty(which('dataread'));
-0135 end
-0136 
-0137 if isempty(File)  % Accept empty matrix as input:
-0138     if ischar(File) || isnumeric(File)
-0139         File = cd;
-0140         return;
-0141     else
-0142         error(['JSimon:', mfilename, ':BadTypeInput1'], ...
-0143             ['*** ', mfilename, ': Input must be a string or cell string']);
-0144     end
-0145 end
-0146 
-0147 if ischar(File) == 0  % Non-empty inputs must be strings
-0148     error(['JSimon:', mfilename, ':BadTypeInput1'], ...
-0149         ['*** ', mfilename, ': Input must be a string or cell string']);
-0150 end
-0151 
-0152 if isWIN  % Windows: --------------------------------------------------------
-0153     FSep = '\';
-0154     File = strrep(File, '/', FSep);
-0155     
-0156     % Remove the magic key on demand, it is appended finally again:
-0157     if strncmp(File, '\\?\', 4)
-0158         if strncmpi(File, '\\?\UNC\', 8)
-0159             File = ['\', File(7:length(File))];  % Two leading backslashes!
-0160         else
-0161             File = File(5:length(File));
-0162         end
-0163     end
-0164     
-0165     isUNC   = strncmp(File, '\\', 2);
-0166     FileLen = length(File);
-0167     if isUNC == 0                        % File is not a UNC path
-0168         % Leading file separator means relative to current drive or base
-0169         % folder:
-0170         ThePath = cd;
-0171         if File(1) == FSep
-0172             if strncmp(ThePath, '\\', 2)   % Current directory is a UNC path
-0173                 sepInd  = strfind(ThePath, '\');
-0174                 ThePath = ThePath(1:sepInd(4));
-0175             else
-0176                 ThePath = ThePath(1:3);     % Drive letter only
-0177             end
-0178         end
-0179         
-0180         if FileLen < 2 || File(2) ~= ':'  % Does not start with drive letter
-0181             if ThePath(length(ThePath)) ~= FSep
-0182                 if File(1) ~= FSep
-0183                     File = [ThePath, FSep, File];
-0184                 else                        % File starts with separator:
-0185                     File = [ThePath, File];
-0186                 end
-0187             else                           % Current path ends with separator:
-0188                 if File(1) ~= FSep
-0189                     File = [ThePath, File];
-0190                 else                        % File starts with separator:
-0191                     ThePath(length(ThePath)) = [];
-0192                     File = [ThePath, File];
-0193                 end
-0194             end
-0195             
-0196         elseif FileLen == 2 && File(2) == ':'   % "C:" current directory on C!
-0197             % "C:" is the current directory on the C-disk, even if the
-0198             % current directory is on another disk! This was ignored in
-0199             % Matlab 6.5, but modern versions considers this strange
-0200             % behaviour.
-0201             if strncmpi(ThePath, File, 2)
-0202                 File = ThePath;
-0203             else
-0204                 try
-0205                     File = cd(cd(File));
-0206                 catch    % No MException to support Matlab6.5...
-0207                     if exist(File, 'dir')  % No idea what could cause an error then!
-0208                         rethrow(lasterror);
-0209                     else  % Reply "K:\" for not existing disk:
-0210                         File = [File, FSep];
-0211                     end
-0212                 end
-0213             end
-0214         end
-0215     end
-0216     
-0217 else         % Linux, MacOS: ---------------------------------------------------
-0218     FSep = '/';
-0219     File = strrep(File, '\', FSep);
-0220     
-0221     if strcmp(File, '~') || strncmp(File, '~/', 2)  % Home directory:
-0222         HomeDir = getenv('HOME');
-0223         if ~isempty(HomeDir)
-0224             File(1) = [];
-0225             File    = [HomeDir, File];
-0226         end
-0227         
-0228     elseif strncmpi(File, FSep, 1) == 0
-0229         % Append relative path to current folder:
-0230         ThePath = cd;
-0231         if ThePath(length(ThePath)) == FSep
-0232             File = [ThePath, File];
-0233         else
-0234             File = [ThePath, FSep, File];
-0235         end
-0236     end
-0237 end
-0238 
-0239 % Care for "\." and "\.." - no efficient algorithm, but the fast Mex is
-0240 % recommended at all!
-0241 if ~isempty(strfind(File, [FSep, '.']))
-0242     if isWIN
-0243         if strncmp(File, '\\', 2)  % UNC path
-0244             index = strfind(File, '\');
-0245             if length(index) < 4    % UNC path without separator after the folder:
-0246                 return;
-0247             end
-0248             Drive            = File(1:index(4));
-0249             File(1:index(4)) = [];
-0250         else
-0251             Drive     = File(1:3);
-0252             File(1:3) = [];
-0253         end
-0254     else  % Unix, MacOS:
-0255         isUNC   = false;
-0256         Drive   = FSep;
-0257         File(1) = [];
-0258     end
-0259     
-0260     hasTrailFSep = (File(length(File)) == FSep);
-0261     if hasTrailFSep
-0262         File(length(File)) = [];
-0263     end
-0264     
-0265     if hasDataRead
-0266         if isWIN  % Need "\\" as separator:
-0267             C = dataread('string', File, '%s', 'delimiter', '\\');  %#ok<REMFF1>
-0268         else
-0269             C = dataread('string', File, '%s', 'delimiter', FSep);  %#ok<REMFF1>
-0270         end
-0271     else  % Use the slower REGEXP, when DATAREAD is not available anymore:
-0272         C = regexp(File, FSep, 'split');
-0273     end
-0274     
-0275     % Remove '\.\' directly without side effects:
-0276     C(strcmp(C, '.')) = [];
-0277     
-0278     % Remove '\..' with the parent recursively:
-0279     R = 1:length(C);
-0280     for dd = reshape(find(strcmp(C, '..')), 1, [])
-0281         index    = find(R == dd);
-0282         R(index) = [];
-0283         if index > 1
-0284             R(index - 1) = [];
-0285         end
-0286     end
-0287     
-0288     if isempty(R)
-0289         File = Drive;
-0290         if isUNC && ~hasTrailFSep
-0291             File(length(File)) = [];
-0292         end
-0293         
-0294     elseif isWIN
-0295         % If you have CStr2String, use the faster:
-0296         %   File = CStr2String(C(R), FSep, hasTrailFSep);
-0297         File = sprintf('%s\\', C{R});
-0298         if hasTrailFSep
-0299             File = [Drive, File];
-0300         else
-0301             File = [Drive, File(1:length(File) - 1)];
-0302         end
-0303         
-0304     else  % Unix:
-0305         File = [Drive, sprintf('%s/', C{R})];
-0306         if ~hasTrailFSep
-0307             File(length(File)) = [];
-0308         end
-0309     end
-0310 end
-0311 
-0312 % "Very" long names under Windows:
-0313 if isWIN
-0314     if ~ischar(Style)
-0315         error(['JSimon:', mfilename, ':BadTypeInput2'], ...
-0316             ['*** ', mfilename, ': Input must be a string or cell string']);
-0317     end
-0318     
-0319     if (strncmpi(Style, 'a', 1) && length(File) >= MAX_PATH) || ...
-0320             strncmpi(Style, 'f', 1)
-0321         % Do not use [isUNC] here, because this concerns the input, which
-0322         % can '.\File', while the current directory is an UNC path.
-0323         if strncmp(File, '\\', 2)  % UNC path
-0324             File = ['\\?\UNC', File(2:end)];
-0325         else
-0326             File = ['\\?\', File];
-0327         end
-0328     end
-0329 end
-0330 
-0331 % return;
-0332 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/io/getMD5Hash.html b/doc/io/getMD5Hash.html deleted file mode 100644 index ee3b856b2..000000000 --- a/doc/io/getMD5Hash.html +++ /dev/null @@ -1,118 +0,0 @@ - - - - Description of getMD5Hash - - - - - - - - - -
Home > io > getMD5Hash.m
- - - -

getMD5Hash -

- -

PURPOSE ^

-
getMD5Hash
- -

SYNOPSIS ^

-
function md5Hash=getMD5Hash(inputFile,binEnd)
- -

DESCRIPTION ^

-
 getMD5Hash
-   Calculates MD5 hash for a file
-
-   Input:
-   inputFile       string with the path to file for which MD5 hash should
-                   be calculated
-   binEnd          string that shows the operating system running in the
-                   client's computer. Use ".exe" for Windows, ".mac" for
-                   macOS or leave it blank for Linux (""). (optional, by
-                   default the function automatically detects the client's
-                   operating system)
-
-   Output:
-   md5Hash         string containing an MD5 hash for inputFile
-   
- Usage: md5Hash=getMD5Hash(inputFile,binEnd)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function md5Hash=getMD5Hash(inputFile,binEnd)
-0002 % getMD5Hash
-0003 %   Calculates MD5 hash for a file
-0004 %
-0005 %   Input:
-0006 %   inputFile       string with the path to file for which MD5 hash should
-0007 %                   be calculated
-0008 %   binEnd          string that shows the operating system running in the
-0009 %                   client's computer. Use ".exe" for Windows, ".mac" for
-0010 %                   macOS or leave it blank for Linux (""). (optional, by
-0011 %                   default the function automatically detects the client's
-0012 %                   operating system)
-0013 %
-0014 %   Output:
-0015 %   md5Hash         string containing an MD5 hash for inputFile
-0016 %
-0017 % Usage: md5Hash=getMD5Hash(inputFile,binEnd)
-0018 inputFile=char(inputFile);
-0019 
-0020 if nargin<2
-0021     if isunix
-0022         if ismac
-0023             binEnd='.mac';
-0024         else
-0025             binEnd='';
-0026         end
-0027     elseif ispc
-0028         binEnd='.exe';
-0029     else
-0030         error('Unknown OS, exiting.')
-0031     end
-0032 else
-0033     binEnd=char(binEnd);
-0034 end
-0035 
-0036 %Check if binEnd is valid
-0037 if ~any(strcmp(binEnd,{'.mac','','.exe'}))
-0038    error('Unknown OS, exiting.')
-0039 end
-0040 
-0041 %Check file existence
-0042 inputFile=checkFileExistence(inputFile);
-0043 
-0044 %Get string containing an MD5 hash
-0045 switch binEnd
-0046     case '.mac'
-0047         [~, md5HashMessage]=system(['md5 "' inputFile '"']);
-0048     case ''
-0049         [~, md5HashMessage]=system(['md5sum "' inputFile '"']);
-0050     case '.exe'
-0051         [~, md5HashMessage]=system(['certutil -hashfile "' inputFile '" MD5"']);
-0052 end
-0053 
-0054 %Extract MD5 hash from a string
-0055 md5Hash = char(regexp(md5HashMessage,'[a-f0-9]{32}','match'));
-0056 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/io/getToolboxVersion.html b/doc/io/getToolboxVersion.html deleted file mode 100644 index 54e1744bc..000000000 --- a/doc/io/getToolboxVersion.html +++ /dev/null @@ -1,146 +0,0 @@ - - - - Description of getToolboxVersion - - - - - - - - - -
Home > io > getToolboxVersion.m
- - - -

getToolboxVersion -

- -

PURPOSE ^

-
getToolboxVersion
- -

SYNOPSIS ^

-
function version = getToolboxVersion(toolbox,fileID,mainBranchFlag)
- -

DESCRIPTION ^

-
 getToolboxVersion
-   Returns the version of a given toolbox, or if not available the latest
-   commit hash (7 characters).
-
-   toolbox         string with the toolbox name (e.g. "RAVEN")
-   fileID          string with the name of a file that is only found in
-                   the corresponding toolbox (e.g. "ravenCobraWrapper.m").
-   mainBranchFlag  logical, if true, function will error if the toolbox is
-                   not on the main branch (optional, default false).
-
-   version         string containing either the toolbox version or latest
-                   commit hash (7 characters).
-
- Usage: version = getToolboxVersion(toolbox,fileID,mainBranchFlag)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 function version = getToolboxVersion(toolbox,fileID,mainBranchFlag)
-0002 % getToolboxVersion
-0003 %   Returns the version of a given toolbox, or if not available the latest
-0004 %   commit hash (7 characters).
-0005 %
-0006 %   toolbox         string with the toolbox name (e.g. "RAVEN")
-0007 %   fileID          string with the name of a file that is only found in
-0008 %                   the corresponding toolbox (e.g. "ravenCobraWrapper.m").
-0009 %   mainBranchFlag  logical, if true, function will error if the toolbox is
-0010 %                   not on the main branch (optional, default false).
-0011 %
-0012 %   version         string containing either the toolbox version or latest
-0013 %                   commit hash (7 characters).
-0014 %
-0015 % Usage: version = getToolboxVersion(toolbox,fileID,mainBranchFlag)
-0016 toolbox=char(toolbox);
-0017 fileID=char(fileID);
-0018 
-0019 if nargin<3
-0020     mainBranchFlag = false;
-0021 end
-0022 
-0023 currentPath = pwd;
-0024 version     = '';
-0025 
-0026 %Try to find root of toolbox:
-0027 try
-0028     toolboxPath = which(fileID);                %full file path
-0029     slashPos    = getSlashPos(toolboxPath);
-0030     toolboxPath = toolboxPath(1:slashPos(end)); %folder path
-0031     %Go up until the root is found:
-0032     D = dir(toolboxPath);
-0033     while ~ismember({'.git'},{D.name})
-0034         slashPos    = getSlashPos(toolboxPath);
-0035         toolboxPath = toolboxPath(1:slashPos(end-1));
-0036         D           = dir(toolboxPath);
-0037     end
-0038     cd(toolboxPath);
-0039 catch
-0040     disp([toolbox ' toolbox cannot be found'])
-0041     version = 'unknown';
-0042 end
-0043 %Check if in main:
-0044 if mainBranchFlag
-0045     [~,currentBranch] = system('git rev-parse --abbrev-ref HEAD');
-0046     currentBranch = strtrim(currentBranch);
-0047     if any([strcmp(currentBranch, "main"), strcmp(currentBranch, "master")])
-0048         cd(currentPath);
-0049         error(['ERROR: ' toolbox ' not in main (or master) branch. Check-out this branch of ' toolbox ' before submitting model for Git.'])
-0050     end
-0051 end
-0052 %Try to find version file of the toolbox:
-0053 if isempty(version)
-0054     try
-0055         fid     = fopen([toolboxPath 'version.txt'],'r');
-0056         version = fscanf(fid,'%s');
-0057         fclose(fid);
-0058     catch
-0059         %If no file available, look up the tag:
-0060         try
-0061             [~,version] = system('git describe --tags');
-0062             version = strtrim(version);
-0063             [~,commit] = system('git log -n 1 --format=%H');
-0064             commit = commit(1:7);
-0065             %If no tag available or commit is part of tag, get commit instead:
-0066             if ~isempty(strfind(version,'fatal')) || ~isempty(strfind(version,commit))
-0067                 version = ['commit ' commit];
-0068             else
-0069                 version = strrep(version,'v','');
-0070             end
-0071         catch
-0072             version = 'unknown';
-0073         end
-0074     end
-0075 end
-0076 cd(currentPath);
-0077 end
-0078 
-0079 function slashPos = getSlashPos(path)
-0080 slashPos = strfind(path,'\');       %Windows
-0081 if isempty(slashPos)
-0082     slashPos = strfind(path,'/');   %MAC/Linux
-0083 end
-0084 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/io/importExcelModel.html b/doc/io/importExcelModel.html deleted file mode 100644 index 0366309c8..000000000 --- a/doc/io/importExcelModel.html +++ /dev/null @@ -1,1051 +0,0 @@ - - - - Description of importExcelModel - - - - - - - - - -
Home > io > importExcelModel.m
- - - -

importExcelModel -

- -

PURPOSE ^

-
importExcelModel
- -

SYNOPSIS ^

-
function model=importExcelModel(fileName,removeExcMets,printWarnings,ignoreErrors)
- -

DESCRIPTION ^

-
 importExcelModel
-   Imports a constraint-based model from a Excel file
-
-   fileName      a Microsoft Excel file to import
-   removeExcMets true if exchange metabolites should be removed. This is
-                 needed to be able to run simulations, but it could also
-                 be done using simplifyModel at a later stage (optional,
-                 default true)
-   printWarnings true if warnings should be printed (optional, default true)
-   ignoreErrors  true if errors should be ignored. See below for details
-                 (optional, default false)
-
-   model
-       annotation       
-           taxonomy     String with the NCBI Taxonomy ID, as valid
-                        identifiers.org annotation
-           defaultLB     Double    with the default lower bound values for reactions
-           defaultUB     Double    with the default upper bound values for reactions
-           givenName     String    with the name of the main model author
-           familyName     String    with the surname of the main model author
-           email        String    with the e-mail address of the main model author
-           organization String    with the organization of the main model author
-           note         String    with additional comments about the model
-       name      name of model
-       id               model ID
-       rxns             reaction ids
-       mets             metabolite ids
-       S                stoichiometric matrix
-       lb               lower bounds
-       ub               upper bounds
-       rev              reversibility vector
-       c                objective coefficients
-       b                equality constraints for the metabolite equations
-       comps            compartment ids
-       compNames        compartment names
-       compOutside      the id (as in comps) for the compartment
-                        surrounding each of the compartments
-       compMiriams      structure with MIRIAM information about the
-                        compartments
-       rxnNames         reaction name
-       rxnComps         compartments for reactions
-       grRules          reaction to gene rules in text form
-       rxnGeneMat       reaction-to-gene mapping in sparse matrix form
-       subSystems       subsystem name for each reaction
-       eccodes          EC-codes for the reactions
-       rxnMiriams       structure with MIRIAM information about the reactions
-       rxnNotes         reaction notes
-       rxnReferences    reaction references
-       rxnConfidenceScores reaction confidence scores
-       genes            list of all genes
-       geneComps        compartments for genes
-       geneMiriams      structure with MIRIAM information about the genes
-       geneShortNames   gene alternative names (e.g. ERG10)
-       metNames         metabolite name
-       metComps         compartments for metabolites
-       inchis           InChI-codes for metabolites
-       metFormulas      metabolite chemical formula
-       metMiriams       structure with MIRIAM information about the metabolites
-       metCharges       metabolite charge
-       unconstrained    true if the metabolite is an exchange metabolite
-
-   Loads models in the RAVEN Toolbox Excel format. A number of consistency
-   checks are performed in order to ensure that the model is valid. These
-   can be ignored by putting ignoreErrors to true. However, this is highly
-   advised against, as it can result in errors in simulations or other
-   functionalities. The RAVEN Toolbox is made to function only on consistent
-   models, and the only checks performed are when the model is imported.
-
-   NOTE: Most errors are checked for by checkModelStruct, but some
-   are checked for in this function as well. Those are ones which relate
-   to missing model elements and so on, and which would make it impossible
-   to construct the model structure. Those errors cannot be ignored by
-   setting ignoreErrors to true.
-
- Usage: model=importExcelModel(fileName,removeExcMets,printWarnings,ignoreErrors)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 function model=importExcelModel(fileName,removeExcMets,printWarnings,ignoreErrors)
-0002 % importExcelModel
-0003 %   Imports a constraint-based model from a Excel file
-0004 %
-0005 %   fileName      a Microsoft Excel file to import
-0006 %   removeExcMets true if exchange metabolites should be removed. This is
-0007 %                 needed to be able to run simulations, but it could also
-0008 %                 be done using simplifyModel at a later stage (optional,
-0009 %                 default true)
-0010 %   printWarnings true if warnings should be printed (optional, default true)
-0011 %   ignoreErrors  true if errors should be ignored. See below for details
-0012 %                 (optional, default false)
-0013 %
-0014 %   model
-0015 %       annotation
-0016 %           taxonomy     String with the NCBI Taxonomy ID, as valid
-0017 %                        identifiers.org annotation
-0018 %           defaultLB     Double    with the default lower bound values for reactions
-0019 %           defaultUB     Double    with the default upper bound values for reactions
-0020 %           givenName     String    with the name of the main model author
-0021 %           familyName     String    with the surname of the main model author
-0022 %           email        String    with the e-mail address of the main model author
-0023 %           organization String    with the organization of the main model author
-0024 %           note         String    with additional comments about the model
-0025 %       name      name of model
-0026 %       id               model ID
-0027 %       rxns             reaction ids
-0028 %       mets             metabolite ids
-0029 %       S                stoichiometric matrix
-0030 %       lb               lower bounds
-0031 %       ub               upper bounds
-0032 %       rev              reversibility vector
-0033 %       c                objective coefficients
-0034 %       b                equality constraints for the metabolite equations
-0035 %       comps            compartment ids
-0036 %       compNames        compartment names
-0037 %       compOutside      the id (as in comps) for the compartment
-0038 %                        surrounding each of the compartments
-0039 %       compMiriams      structure with MIRIAM information about the
-0040 %                        compartments
-0041 %       rxnNames         reaction name
-0042 %       rxnComps         compartments for reactions
-0043 %       grRules          reaction to gene rules in text form
-0044 %       rxnGeneMat       reaction-to-gene mapping in sparse matrix form
-0045 %       subSystems       subsystem name for each reaction
-0046 %       eccodes          EC-codes for the reactions
-0047 %       rxnMiriams       structure with MIRIAM information about the reactions
-0048 %       rxnNotes         reaction notes
-0049 %       rxnReferences    reaction references
-0050 %       rxnConfidenceScores reaction confidence scores
-0051 %       genes            list of all genes
-0052 %       geneComps        compartments for genes
-0053 %       geneMiriams      structure with MIRIAM information about the genes
-0054 %       geneShortNames   gene alternative names (e.g. ERG10)
-0055 %       metNames         metabolite name
-0056 %       metComps         compartments for metabolites
-0057 %       inchis           InChI-codes for metabolites
-0058 %       metFormulas      metabolite chemical formula
-0059 %       metMiriams       structure with MIRIAM information about the metabolites
-0060 %       metCharges       metabolite charge
-0061 %       unconstrained    true if the metabolite is an exchange metabolite
-0062 %
-0063 %   Loads models in the RAVEN Toolbox Excel format. A number of consistency
-0064 %   checks are performed in order to ensure that the model is valid. These
-0065 %   can be ignored by putting ignoreErrors to true. However, this is highly
-0066 %   advised against, as it can result in errors in simulations or other
-0067 %   functionalities. The RAVEN Toolbox is made to function only on consistent
-0068 %   models, and the only checks performed are when the model is imported.
-0069 %
-0070 %   NOTE: Most errors are checked for by checkModelStruct, but some
-0071 %   are checked for in this function as well. Those are ones which relate
-0072 %   to missing model elements and so on, and which would make it impossible
-0073 %   to construct the model structure. Those errors cannot be ignored by
-0074 %   setting ignoreErrors to true.
-0075 %
-0076 % Usage: model=importExcelModel(fileName,removeExcMets,printWarnings,ignoreErrors)
-0077 fileName=char(fileName);
-0078 
-0079 if nargin<2
-0080     removeExcMets=true;
-0081 end
-0082 if nargin<3
-0083     printWarnings=true;
-0084 end
-0085 if nargin<4
-0086     ignoreErrors=false;
-0087 end
-0088 
-0089 if ~isfile(fileName)
-0090     error('Excel file %s cannot be found',string(fileName));
-0091 end
-0092 
-0093 %This is to match the order of the fields to those you get from importing
-0094 %from SBML
-0095 model=[];
-0096 model.id=[];
-0097 model.name=[];
-0098 model.annotation=[];
-0099 %Default bounds if not defined
-0100 model.annotation.defaultLB=-1000;
-0101 model.annotation.defaultUB=1000;
-0102 model.rxns={};
-0103 model.mets={};
-0104 model.S=[];
-0105 model.lb=[];
-0106 model.ub=[];
-0107 model.rev=[];
-0108 model.c=[];
-0109 model.b=[];
-0110 model.comps={};
-0111 model.compNames={};
-0112 model.compOutside={};
-0113 model.compMiriams={};
-0114 model.rxnNames={};
-0115 model.rxnComps={}; %Will be double later
-0116 model.grRules={};
-0117 model.rxnGeneMat=[];
-0118 model.subSystems={};
-0119 model.eccodes={};
-0120 model.rxnMiriams={};
-0121 model.rxnNotes={};
-0122 model.rxnReferences={};
-0123 model.rxnConfidenceScores={}; %Will be double later
-0124 model.genes={};
-0125 model.geneComps={}; %Will be double later
-0126 model.geneMiriams={};
-0127 model.geneShortNames={};
-0128 model.metNames={};
-0129 model.metComps=[];
-0130 model.inchis={};
-0131 model.metFormulas={};
-0132 model.metMiriams={};
-0133 model.metCharges={}; %Will be double later
-0134 model.unconstrained=[];
-0135 
-0136 workbook=loadWorkbook(fileName);
-0137 
-0138 [raw, flag]=loadSheet(workbook,'MODEL');
-0139 
-0140 if flag<0
-0141     if printWarnings==true
-0142         EM='Could not load the MODEL sheet';
-0143         dispEM(EM,false);
-0144     end
-0145     model.id='UNKNOWN';
-0146     model.name='No model details available';
-0147 else
-0148     raw=cleanSheet(raw);
-0149     
-0150     %It is assumed that the first line is labels and that the second one is
-0151     %info
-0152     raw(1,:)=upper(raw(1,:));
-0153     raw(1,:)=strrep(raw(1,:),'MODELID','ID');
-0154     raw(1,:)=strrep(raw(1,:),'MODELNAME','NAME');
-0155     raw(1,:)=strrep(raw(1,:),'DESCRIPTION','NAME');
-0156     
-0157     %Loop through the labels
-0158     for i=1:numel(raw(1,:))
-0159         switch raw{1,i}
-0160             case 'ID'
-0161                 if any(raw{2,i})
-0162                     model.id=toStr(raw{2,i}); %Should be string already
-0163                 else
-0164                     EM='No model ID supplied';
-0165                     dispEM(EM);
-0166                 end
-0167             case 'NAME'
-0168                 if any(raw{2,i})
-0169                     model.name=toStr(raw{2,i}); %Should be string already
-0170                 else
-0171                     EM='No model name supplied';
-0172                     dispEM(EM);
-0173                 end
-0174             case 'DEFAULT LOWER'
-0175                 if ~isempty(raw{2,i})
-0176                     try
-0177                         model.annotation.defaultLB=toDouble(raw{2,i},NaN);
-0178                     catch
-0179                         EM='DEFAULT LOWER must be numeric';
-0180                         dispEM(EM);
-0181                     end
-0182                 else
-0183                     if printWarnings==true
-0184                         fprintf('NOTE: DEFAULT LOWER not supplied. Uses -1000\n');
-0185                     end
-0186                     model.annotation.defaultLB=-1000;
-0187                 end
-0188             case 'DEFAULT UPPER'
-0189                 if ~isempty(raw{2,i})
-0190                     try
-0191                         model.annotation.defaultUB=toDouble(raw{2,i},NaN);
-0192                     catch
-0193                         EM='DEFAULT UPPER must be numeric';
-0194                         dispEM(EM);
-0195                     end
-0196                 else
-0197                     if printWarnings==true
-0198                         fprintf('NOTE: DEFAULT UPPER not supplied. Uses 1000\n');
-0199                     end
-0200                     model.annotation.defaultUB=1000;
-0201                 end
-0202             case 'TAXONOMY'
-0203                 if any(raw{2,i})
-0204                     model.annotation.taxonomy=toStr(raw{2,i}); %Should be string already
-0205                 end
-0206             case 'CONTACT GIVEN NAME'
-0207                 if any(raw{2,i})
-0208                     model.annotation.givenName=toStr(raw{2,i}); %Should be string already
-0209                 end
-0210             case 'CONTACT FAMILY NAME'
-0211                 if any(raw{2,i})
-0212                     model.annotation.familyName=toStr(raw{2,i}); %Should be string already
-0213                 end
-0214             case 'CONTACT EMAIL'
-0215                 if any(raw{2,i})
-0216                     model.annotation.email=toStr(raw{2,i}); %Should be string already
-0217                 end
-0218             case 'ORGANIZATION'
-0219                 if any(raw{2,i})
-0220                     model.annotation.organization=toStr(raw{2,i}); %Should be string already
-0221                 end
-0222             case 'NOTES'
-0223                 if any(raw{2,i})
-0224                     model.annotation.note=toStr(raw{2,i}); %Should be string already
-0225                 end
-0226         end
-0227     end
-0228 end
-0229 
-0230 %Get compartment information
-0231 [raw, flag]=loadSheet(workbook,'COMPS');
-0232 
-0233 if flag<0
-0234     if printWarnings==true
-0235         EM='Could not load the COMPS sheet. All elements will be assigned to a compartment "s" for "System"';
-0236         dispEM(EM,false);
-0237     end
-0238     model.comps={'s'};
-0239     model.compNames={'System'};
-0240 else
-0241     raw=cleanSheet(raw);
-0242     
-0243     %Map to new captions
-0244     raw(1,:)=upper(raw(1,:));
-0245     raw(1,:)=strrep(raw(1,:),'COMPABBREV','ABBREVIATION');
-0246     raw(1,:)=strrep(raw(1,:),'COMPNAME','NAME');
-0247         
-0248     %Loop through the labels
-0249     for i=1:numel(raw(1,:))
-0250         switch raw{1,i}
-0251             case 'ABBREVIATION'
-0252                 model.comps=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
-0253             case 'NAME'
-0254                 model.compNames=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
-0255             case 'INSIDE'
-0256                 model.compOutside=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
-0257             case 'MIRIAM'
-0258                 model.compMiriams=raw(2:end,i);
-0259         end
-0260     end
-0261     
-0262     %Check that necessary fields are loaded
-0263     if isempty(model.comps)
-0264         EM='There must be a column named ABBREVIATION in the COMPS sheet';
-0265         dispEM(EM);
-0266     end
-0267     if isempty(model.compNames)
-0268         model.compNames=model.comps;
-0269         if printWarnings==true
-0270             EM='There is no column named NAME in the COMPS sheet. ABBREVIATION will be used as name';
-0271             dispEM(EM,false);
-0272         end
-0273     end
-0274     model.compMiriams=parseMiriam(model.compMiriams);
-0275 end
-0276 
-0277 %Get all the genes and info about them
-0278 [raw, flag]=loadSheet(workbook,'GENES');
-0279 
-0280 if flag<0
-0281     if printWarnings==true
-0282         EM='There is no spreadsheet named GENES';
-0283         dispEM(EM,false)
-0284     end
-0285 else
-0286     raw=cleanSheet(raw);
-0287     
-0288     %Map to new captions
-0289     raw(1,:)=upper(raw(1,:));
-0290     raw(1,:)=strrep(raw(1,:),'GENE NAME','NAME');
-0291         
-0292     %Loop through the labels
-0293     foundGenes=false;
-0294     for i=1:numel(raw(1,:))
-0295         switch raw{1,i}
-0296             case 'NAME'
-0297                 model.genes=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
-0298                 foundGenes=true;
-0299             case 'MIRIAM'
-0300                 model.geneMiriams=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
-0301             case 'SHORT NAME'
-0302                 model.geneShortNames=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
-0303             case 'COMPARTMENT'
-0304                 model.geneComps=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
-0305         end
-0306     end
-0307     
-0308     if foundGenes==false
-0309         EM='There must be a column named NAME in the GENES sheet';
-0310         dispEM(EM);
-0311     end
-0312     
-0313     %Its ok if all of them are empty
-0314     if all(cellfun(@isempty,model.geneComps))
-0315         model.geneComps=[];
-0316     end
-0317     
-0318     %Check that geneName contain only strings and no empty strings
-0319     if ~iscellstr(model.genes)
-0320         EM='All gene names have to be strings';
-0321         dispEM(EM);
-0322     else
-0323         if any(strcmp('',model.genes))
-0324             EM='There can be no empty strings in gene names';
-0325             dispEM(EM);
-0326         end
-0327     end
-0328     
-0329     %Check that geneComp contains only strings and no empty string
-0330     if ~isempty(model.geneComps)
-0331         if ~iscellstr(model.geneComps)
-0332             EM='All gene compartments have to be strings';
-0333             dispEM(EM);
-0334         else
-0335             if any(strcmp('',model.geneComps))
-0336                 EM='There can be no empty strings in gene compartments';
-0337                 dispEM(EM);
-0338             end
-0339         end
-0340         [I, model.geneComps]=ismember(model.geneComps,model.comps);
-0341         EM='The following genes have compartment abbreviations which could not be found:';
-0342         dispEM(EM,true,model.genes(~I));
-0343     end
-0344 end
-0345 
-0346 model.geneMiriams=parseMiriam(model.geneMiriams);
-0347 
-0348 %Loads the reaction data
-0349 [raw, flag]=loadSheet(workbook,'RXNS');
-0350 
-0351 if flag<0
-0352     EM='Could not load the RXNS sheet';
-0353     dispEM(EM);
-0354 end
-0355 
-0356 raw=cleanSheet(raw);
-0357 
-0358 %Map to new captions
-0359 raw(1,:)=upper(raw(1,:));
-0360 raw(1,:)=strrep(raw(1,:),'RXNID','ID');
-0361 
-0362 %Loop through the labels
-0363 equations={};
-0364 reactionReplacement={};
-0365 for i=1:numel(raw(1,:))
-0366     switch raw{1,i}
-0367         case 'ID'
-0368             model.rxns=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
-0369         case 'NAME'
-0370             model.rxnNames=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
-0371         case 'EQUATION'
-0372             equations=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
-0373         case 'EC-NUMBER'
-0374             model.eccodes=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
-0375         case 'GENE ASSOCIATION'
-0376             model.grRules=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
-0377         case 'LOWER BOUND'
-0378             try
-0379                 model.lb=cellfun(@(x) toDouble(x,NaN),raw(2:end,i));
-0380             catch
-0381                 EM='The lower bounds must be numerical values';
-0382                 dispEM(EM);
-0383             end
-0384         case 'UPPER BOUND'
-0385             try
-0386                 model.ub=cellfun(@(x) toDouble(x,NaN),raw(2:end,i));
-0387             catch
-0388                 EM='The upper bounds must be numerical values';
-0389                 dispEM(EM);
-0390             end
-0391         case 'OBJECTIVE'
-0392             try
-0393                 model.c=cellfun(@(x) toDouble(x,0),raw(2:end,i));
-0394             catch
-0395                 EM='The objective coefficients must be numerical values';
-0396                 dispEM(EM);
-0397             end
-0398         case 'COMPARTMENT'
-0399             model.rxnComps=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
-0400         case 'SUBSYSTEM'
-0401             subsystems=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
-0402         case 'REPLACEMENT ID'
-0403             reactionReplacement=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
-0404         case 'MIRIAM'
-0405             model.rxnMiriams=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
-0406         case 'NOTE'
-0407             model.rxnNotes=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
-0408         case 'REFERENCE'
-0409             model.rxnReferences=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
-0410         case 'CONFIDENCE SCORE'
-0411             model.rxnConfidenceScores=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
-0412     end
-0413 end
-0414 
-0415 if ~isempty(model.rxnConfidenceScores)
-0416     model.rxnConfidenceScores=str2double(model.rxnConfidenceScores);
-0417 end
-0418 for i=1:numel(subsystems)
-0419     model.subSystems{i,1}=cellstr(strsplit(subsystems{i,1},';'));
-0420 end
-0421 
-0422 %Check that all necessary reaction info has been loaded
-0423 if isempty(equations)
-0424     EM='There must be a column named EQUATION in the RXNS sheet';
-0425     dispEM(EM);
-0426 end
-0427 if isempty(model.rxns)
-0428     if printWarnings==true
-0429         EM='There is no column named ID in the RXNS sheet. The reactions will be named as "r1", "r2"...';
-0430         dispEM(EM,false);
-0431     end
-0432     I=num2cell((1:numel(equations))');
-0433     model.rxns=strcat('r',cellfun(@num2str,I,'UniformOutput',false));
-0434 end
-0435 
-0436 %Check if some other stuff is loaded and populate with default values
-0437 %otherwise
-0438 if isempty(model.rxnNames)
-0439     model.rxnNames=cell(numel(model.rxns),1);
-0440     model.rxnNames(:)={''};
-0441     if printWarnings==true
-0442         EM='There is no column named NAME in the RXNS sheet. Empty strings will be used as reaction names';
-0443         dispEM(EM,false);
-0444     end
-0445 end
-0446 if isempty(model.lb)
-0447     %This is not set here since the reversibility isn't known yet
-0448     model.lb=nan(numel(model.rxns),1);
-0449     if printWarnings==true
-0450         EM='There is no column named LOWER BOUND in the RXNS sheet. Default bounds will be used';
-0451         dispEM(EM,false);
-0452     end
-0453 end
-0454 if isempty(model.ub)
-0455     model.ub=nan(numel(model.rxns),1);
-0456     if printWarnings==true
-0457         EM='There is no column named UPPER BOUND in the RXNS sheet. Default bounds will be used';
-0458         dispEM(EM,false);
-0459     end
-0460 end
-0461 if isempty(model.c)
-0462     model.c=zeros(numel(model.rxns),1);
-0463     if printWarnings==true
-0464         EM='There is no column named OBJECTIVE in the RXNS sheet';
-0465         dispEM(EM,false);
-0466     end
-0467 end
-0468 
-0469 %Either all reactions must have a compartment string or none of them. Check
-0470 %if it's only empty and if so return it to []
-0471 if ~isempty(model.rxnComps)
-0472     if all(cellfun(@isempty,model.rxnComps))
-0473         model.rxnComps=[];
-0474     end
-0475 end
-0476 
-0477 %Construct the rxnMiriams structure
-0478 model.rxnMiriams=parseMiriam(model.rxnMiriams);
-0479 
-0480 %Replace the reaction IDs for those IDs that have a corresponding
-0481 %replacement name.
-0482 I=cellfun(@any,reactionReplacement);
-0483 model.rxns(I)=reactionReplacement(I);
-0484 
-0485 %Check that there are no empty strings in reactionIDs or equations
-0486 if any(strcmp('',model.rxns))
-0487     EM='There are empty reaction IDs';
-0488     dispEM(EM);
-0489 end
-0490 
-0491 if any(strcmp('',equations))
-0492     EM='There are empty equations';
-0493     dispEM(EM);
-0494 end
-0495 
-0496 if ~isempty(model.rxnComps)
-0497     if any(strcmp('',model.rxnComps))
-0498         EM='Either all reactions must have an associated compartment string or none of them';
-0499         dispEM(EM);
-0500     end
-0501 end
-0502 
-0503 if ~isempty(model.grRules)
-0504     tempRules=model.grRules;
-0505     for i=1:length(model.rxns)
-0506         %Check that all gene associations have a match in the gene list
-0507         if ~isempty(model.grRules{i})
-0508             tempRules{i}=regexprep(tempRules{i},' and | or ','>'); %New format: Genes are separated 'and' and 'or' strings with parentheses
-0509             tempRules{i}=regexprep(tempRules{i},'(',''); %New format: Genes are separated 'and' and 'or' strings with parentheses
-0510             tempRules{i}=regexprep(tempRules{i},')',''); %New format: Genes are separated 'and' and 'or' strings with parentheses
-0511             indexesNew=strfind(tempRules{i},'>'); %Old format: Genes are separated by ":" for AND and ";" for OR
-0512             indexes=strfind(tempRules{i},':'); %Old format: Genes are separated by ":" for AND and ";" for OR
-0513             indexes=unique([indexesNew indexes strfind(tempRules{i},';')]);
-0514             if isempty(indexes)
-0515                 %See if you have a match
-0516                 I=find(strcmp(tempRules{i},model.genes));
-0517                 if isempty(I)
-0518                     EM=['The gene association in reaction ' model.rxns{i} ' (' tempRules{i} ') is not present in the gene list'];
-0519                     dispEM(EM);
-0520                 end
-0521             else
-0522                 temp=[0 indexes numel(tempRules{i})+1];
-0523                 for j=1:numel(indexes)+1
-0524                     %The reaction has several associated genes
-0525                     geneName=tempRules{i}(temp(j)+1:temp(j+1)-1);
-0526                     I=find(strcmp(geneName,model.genes));
-0527                     if isempty(I)
-0528                         EM=['The gene association in reaction ' model.rxns{i} ' (' geneName ') is not present in the gene list'];
-0529                         dispEM(EM);
-0530                     end
-0531                 end
-0532             end
-0533             %In order to adhere to the COBRA standards it should be like
-0534             %this: -If only one gene then no parentheses -If only "and" or
-0535             %only "or" there should only be one set of parentheses -If both
-0536             %"and" and "or", then split on "or". This is not complete, but
-0537             %it's the type of relationship supported by the Excel
-0538             %formulation
-0539             aSign=strfind(model.grRules{i},':');
-0540             oSign=strfind(model.grRules{i},';');
-0541             if isempty(aSign) && isempty(oSign)
-0542                 model.grRules{i}=model.grRules{i};
-0543             else
-0544                 if isempty(aSign)
-0545                     model.grRules{i}=['(' strrep(model.grRules{i},';',' or ') ')'];
-0546                 else
-0547                     if isempty(oSign)
-0548                         model.grRules{i}=['(' strrep(model.grRules{i},':',' and ') ')'];
-0549                     else
-0550                         model.grRules{i}=['((' strrep(model.grRules{i},';',') or (') '))'];
-0551                         model.grRules{i}=strrep(model.grRules{i},':',' and ');
-0552                     end
-0553                 end
-0554             end
-0555         end
-0556     end
-0557 end
-0558 
-0559 %Check that the compartment for each reaction can be found
-0560 if ~isempty(model.rxnComps)
-0561     [I, model.rxnComps]=ismember(model.rxnComps,model.comps);
-0562     EM='The following reactions have compartment abbreviations which could not be found:';
-0563     dispEM(EM,true,model.rxns(~I));
-0564 end
-0565 
-0566 %Get all the metabolites and info about them
-0567 [raw, flag]=loadSheet(workbook,'METS');
-0568 
-0569 if flag<0
-0570     if printWarnings==true
-0571         EM='There is no spreadsheet named METS. The metabolites will be named "m1", "m2"... and assigned to the first compartment';
-0572         dispEM(EM,false);
-0573     end
-0574     %Parse the equations to find out how many metabolites there are
-0575     metsForParsing=parseRxnEqu(equations);
-0576     I=num2cell((1:numel(metsForParsing))');
-0577     model.mets=strcat('m',cellfun(@num2str,I,'UniformOutput',false));
-0578     model.metComps=ones(numel(model.mets),1);
-0579     model.unconstrained=zeros(numel(model.mets),1);
-0580     model.metNames=metsForParsing;
-0581 else
-0582     raw=cleanSheet(raw);
-0583     
-0584     %Map to new captions
-0585     raw(1,:)=upper(raw(1,:));
-0586     raw(1,:)=strrep(raw(1,:),'METID','ID');
-0587     raw(1,:)=strrep(raw(1,:),'METNAME','NAME');
-0588     
-0589     %Loop through the labels
-0590     metReplacement={};
-0591     for i=1:numel(raw(1,:))
-0592         switch raw{1,i}
-0593             case 'ID'
-0594                 model.mets=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
-0595             case 'NAME'
-0596                 model.metNames=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
-0597             case 'UNCONSTRAINED'
-0598                 model.unconstrained=cellfun(@boolToDouble,raw(2:end,i));
-0599                 %NaN is returned if the values couldn't be parsed
-0600                 EM='The UNCONSTRAINED property for the following metabolites must be "true"/"false", 1/0, TRUE/FALSE or not set:';
-0601                 dispEM(EM,true,model.mets(isnan(model.unconstrained)));
-0602             case 'MIRIAM'
-0603                 model.metMiriams=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
-0604             case 'COMPOSITION'
-0605                 model.metFormulas=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
-0606             case 'INCHI'
-0607                 model.inchis=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
-0608             case 'COMPARTMENT'
-0609                 model.metComps=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
-0610                 
-0611                 %Check that all metabolites have compartments defined
-0612                 if any(strcmp('',model.metComps))
-0613                     EM='All metabolites must have an associated compartment string';
-0614                     dispEM(EM);
-0615                 end
-0616             case 'REPLACEMENT ID'
-0617                 metReplacement=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
-0618             case 'CHARGE'
-0619                 model.metCharges=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
-0620         end
-0621     end
-0622     
-0623     %Check that necessary fields are loaded (METID)
-0624     if isempty(model.mets)
-0625         EM='There must be a column named ID in the METS sheet';
-0626         dispEM(EM);
-0627     end
-0628     
-0629     %Check that some other stuff is loaded and use default values otherwise
-0630     if isempty(model.metNames)
-0631         model.metNames=cell(numel(model.mets),1);
-0632         if printWarnings==true
-0633             EM='There is no column named NAME in the METS sheet. ID will be used as name';
-0634             dispEM(EM,false);
-0635         end
-0636     end
-0637     if isempty(model.unconstrained)
-0638         model.unconstrained=zeros(numel(model.mets),1);
-0639         if printWarnings==true
-0640             EM='There is no column named UNCONSTRAINED in the METS sheet. All metabolites will be constrained';
-0641             dispEM(EM,false);
-0642         end
-0643     end
-0644     
-0645     if isempty(model.metComps)
-0646         model.metComps=cell(numel(model.mets),1);
-0647         model.metComps(:)=model.comps(1);
-0648         if printWarnings==true
-0649             EM='There is no column named COMPARTMENT in the METS sheet. All metabolites will be assigned to the first compartment in COMPS. Note that RAVEN makes extensive use of metabolite names and compartments. Some features will therefore not function correctly if metabolite compartments are not correctly assigned';
-0650             dispEM(EM,false);
-0651         end
-0652     end
-0653     
-0654     %The composition should be loaded from InChIs when available
-0655     I=find(~cellfun(@isempty,model.inchis));
-0656     for i=1:numel(I)
-0657         S=regexp(model.inchis(I(i)),'/','split');
-0658         S=S{1};
-0659         if numel(S)>=2
-0660             %Don't copy if it doesn't look good
-0661             model.metFormulas(I(i))=S(2);
-0662         end
-0663     end
-0664     
-0665     %Check that the compartment for each metabolite can be found. Also
-0666     %convert from id to index
-0667     [I, model.metComps]=ismember(model.metComps,model.comps);
-0668     EM='The following metabolites have compartment abbreviations which could not be found:';
-0669     dispEM(EM,true,model.mets(~I));
-0670     
-0671     %Check that the model.mets vector is unique. The problem is that the
-0672     %checkModelStruct cannot check for that since only the metReplacements
-0673     %(if used) end up in the model structure
-0674     I=false(numel(model.mets),1);
-0675     [J, K]=unique(model.mets);
-0676     if numel(J)~=numel(model.mets)
-0677         L=1:numel(model.mets);
-0678         L(K)=[];
-0679         I(L)=true;
-0680     end
-0681     EM='The following metabolites are duplicates:';
-0682     dispEM(EM,~ignoreErrors,model.mets(I));
-0683     
-0684     %Check that there are no metabolite IDs which are numbers. This would
-0685     %give errors when parsing the equations
-0686     I=cellfun(@str2double,model.mets);
-0687     EM='The following metabolites have names which cannot be distinguished from numbers:';
-0688     dispEM(EM,~ignoreErrors,model.mets(~isnan(I)));
-0689     I=cellfun(@str2double,metReplacement);
-0690     EM='The following metabolites have names which cannot be distinguished from numbers:';
-0691     dispEM(EM,~ignoreErrors,metReplacement(~isnan(I)));
-0692     
-0693     %Replace the metabolite IDs for those IDs that have a corresponding
-0694     %replacement metabolite. This is not used for matching, but will be
-0695     %checked for consistency with SBML naming conventions
-0696     metsForParsing=model.mets; %This is because the equations are written with this
-0697     I=cellfun(@any,metReplacement);
-0698     model.mets(I)=metReplacement(I);
-0699     
-0700     %If the metabolite name isn't set, replace it with the metabolite id
-0701     I=~cellfun(@any,model.metNames);
-0702     model.metNames(I)=model.mets(I);
-0703     
-0704     %Construct the metMiriams structure
-0705     model.metMiriams=parseMiriam(model.metMiriams);
-0706     
-0707     %Either all metabolites have charge or none of them. Check if it's only
-0708     %empty and if so return it to []
-0709     if ~isempty(model.metCharges)
-0710         if all(cellfun(@isempty,model.metCharges))
-0711             model.metCharges=[];
-0712         end
-0713     end
-0714     if ~isempty(model.metCharges)
-0715         model.metCharges=str2double(model.metCharges);
-0716     end
-0717 end
-0718 
-0719 %Everything seems fine with the metabolite IDs, compartments, genes, and
-0720 %reactions
-0721 
-0722 %Parse the equations
-0723 [model.S, mets, badRxns, model.rev]=constructS(equations,metsForParsing,model.rxns);
-0724 model.rev=model.rev*1; %Typecast to double
-0725 
-0726 %Add default constraints
-0727 model.lb(isnan(model.lb))=model.annotation.defaultLB.*model.rev(isnan(model.lb));
-0728 model.ub(isnan(model.ub))=model.annotation.defaultUB;
-0729 
-0730 %Reorder the S matrix so that it fits with the metabolite list in the
-0731 %structure
-0732 [~, I]=ismember(mets,metsForParsing);
-0733 model.S=model.S(I,:);
-0734 
-0735 %Print warnings about the reactions which contain the same metabolite as
-0736 %both reactants and products
-0737 EM='The following reactions have metabolites which are present more than once. Only the net reactions will be exported:';
-0738 dispEM(EM,false,model.rxns(badRxns));
-0739 
-0740 model.b=zeros(numel(model.mets),1);
-0741 
-0742 %Fix grRules and reconstruct rxnGeneMat
-0743 [grRules,rxnGeneMat] = standardizeGrRules(model,true);
-0744 model.grRules = grRules;
-0745 model.rxnGeneMat = rxnGeneMat;
-0746 
-0747 %Remove unused fields
-0748 if all(cellfun(@isempty,model.compOutside))
-0749     model=rmfield(model,'compOutside');
-0750 end
-0751 if all(cellfun(@isempty,model.compMiriams))
-0752     model=rmfield(model,'compMiriams');
-0753 end
-0754 if all(cellfun(@isempty,model.rxnNames))
-0755     model=rmfield(model,'rxnNames');
-0756 end
-0757 if isempty(model.rxnComps)
-0758     model=rmfield(model,'rxnComps');
-0759 end
-0760 if all(cellfun(@isempty,model.grRules))
-0761     model=rmfield(model,'grRules');
-0762 end
-0763 if isfield(model,'rxnGeneMat') && isempty(model.rxnGeneMat)
-0764     model=rmfield(model,'rxnGeneMat');
-0765 end
-0766 if all(cellfun(@isempty,model.subSystems))
-0767     model=rmfield(model,'subSystems');
-0768 end
-0769 if all(cellfun(@isempty,model.eccodes))
-0770     model=rmfield(model,'eccodes');
-0771 end
-0772 if all(cellfun(@isempty,model.rxnMiriams))
-0773     model=rmfield(model,'rxnMiriams');
-0774 end
-0775 if all(cellfun(@isempty,model.rxnNotes))
-0776     model=rmfield(model,'rxnNotes');
-0777 end
-0778 if all(cellfun(@isempty,model.rxnReferences))
-0779     model=rmfield(model,'rxnReferences');
-0780 end
-0781 if isempty(model.rxnConfidenceScores)
-0782     model=rmfield(model,'rxnConfidenceScores');
-0783 end
-0784 if isempty(model.genes)
-0785     model=rmfield(model,'genes');
-0786 end
-0787 if isempty(model.geneComps)
-0788     model=rmfield(model,'geneComps');
-0789 end
-0790 if isempty(model.geneMiriams)
-0791     model=rmfield(model,'geneMiriams');
-0792 end
-0793 if all(cellfun(@isempty,model.geneShortNames))
-0794     model=rmfield(model,'geneShortNames');
-0795 end
-0796 if all(cellfun(@isempty,model.inchis))
-0797     model=rmfield(model,'inchis');
-0798 end
-0799 if all(cellfun(@isempty,model.metFormulas))
-0800     model=rmfield(model,'metFormulas');
-0801 end
-0802 if all(cellfun(@isempty,model.metMiriams))
-0803     model=rmfield(model,'metMiriams');
-0804 end
-0805 if isempty(model.metCharges)
-0806     model=rmfield(model,'metCharges');
-0807 end
-0808 
-0809 %The model structure has now been reconstructed but it can still contain
-0810 %many types of errors. The checkModelConsistency function is used to make
-0811 %sure that naming and mapping of stuff looks good
-0812 checkModelStruct(model,~ignoreErrors);
-0813 
-0814 if removeExcMets==true
-0815     model=simplifyModel(model);
-0816 end
-0817 end
-0818 
-0819 function miriamStruct=parseMiriam(strings,miriamStruct)
-0820 %Gets the names and values of Miriam-string. Nothing fancy at all, just to
-0821 %prevent using the same code for metabolites, genes, and reactions. The
-0822 %function also allows for supplying a miriamStruct and the info will then
-0823 %be added
-0824 
-0825 if nargin<2
-0826     miriamStruct=cell(numel(strings),1);
-0827 end
-0828 for i=1:numel(strings)
-0829     if any(strings{i})
-0830         %A Miriam string can be several ids separated by ";". Each id is
-0831         %"name(..:..)/value"; an old format when value is separated by
-0832         %colon is also supported
-0833         I=regexp(strings{i},';','split');
-0834         if isfield(miriamStruct{i},'name')
-0835             startIndex=numel(miriamStruct{i}.name);
-0836             miriamStruct{i}.name=[miriamStruct{i}.name;cell(numel(I),1)];
-0837             miriamStruct{i}.value=[miriamStruct{i}.value;cell(numel(I),1)];
-0838         else
-0839             startIndex=0;
-0840             miriamStruct{i}.name=cell(numel(I),1);
-0841             miriamStruct{i}.value=cell(numel(I),1);
-0842         end
-0843         
-0844         for j=1:numel(I)
-0845             if any(strfind(I{j},'/'))
-0846                 index=max(strfind(I{j},'/'));
-0847             elseif any(strfind(I{j},':'))
-0848                 index=max(strfind(I{j},':'));
-0849             end
-0850             if exist('index','var') & any(index)
-0851                 miriamStruct{i}.name{startIndex+j}=I{j}(1:index-1);
-0852                 miriamStruct{i}.value{startIndex+j}=I{j}(index+1:end);
-0853             else
-0854                 EM=['"' I{j} '" is not a valid MIRIAM string. The format must be "identifier/value" or identifier:value'];
-0855                 dispEM(EM);
-0856             end
-0857         end
-0858     end
-0859 end
-0860 end
-0861 
-0862 %For converting a value to string. This is used instead of num2str because
-0863 %I want to convert empty cells to {''}.
-0864 function y=toStr(x)
-0865 %x can be empty, numerical, string or boolean. It cannot be NaN. Boolean
-0866 %values will be converted to '1'/'0'
-0867 if isempty(x)
-0868     y='';
-0869 else
-0870     y=num2str(x);
-0871 end
-0872 end
-0873 
-0874 %For converting to numeric. This is used instead of str2num because I want
-0875 %to be able to choose what empty values should be mapped to.
-0876 %
-0877 % default the value to use for empty input
-0878 function y=toDouble(x,default)
-0879 if isempty(x) %Note that this catches '' as well
-0880     y=default;
-0881 else
-0882     if isnumeric(x)
-0883         y=x;
-0884     else
-0885         y=str2double(x);
-0886         
-0887         %This happens if the input couldn't be converted. Note that the
-0888         %input itself cannot be NaN since it was fixed in clean imported
-0889         if isnan(y)
-0890             EM=['Cannot convert the string "' x '" to double'];
-0891             dispEM(EM);
-0892         end
-0893     end
-0894 end
-0895 end
-0896 
-0897 %For converting boolean (the UNCONSTRAINED field) to double (the
-0898 %model.unconstrained field)
-0899 function y=boolToDouble(x)
-0900 if isempty(x)
-0901     y=0;
-0902     return;
-0903 end
-0904 if islogical(x)
-0905     y=x*1; %Typecast to double
-0906     return;
-0907 end
-0908 if isnumeric(x)
-0909     if x~=0
-0910         y=1;
-0911         return;
-0912     else
-0913         y=0;
-0914         return;
-0915     end
-0916 end
-0917 if ischar(x)
-0918     if strcmpi(x,'TRUE')
-0919         y=1;
-0920         return;
-0921     end
-0922     if strcmpi(x,'FALSE')
-0923         y=0;
-0924         return;
-0925     end
-0926 end
-0927 y=NaN; %This means that the input couldn't be parsed
-0928 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/io/importModel.html b/doc/io/importModel.html deleted file mode 100644 index dff37de8c..000000000 --- a/doc/io/importModel.html +++ /dev/null @@ -1,1263 +0,0 @@ - - - - Description of importModel - - - - - - - - - -
Home > io > importModel.m
- - - -

importModel -

- -

PURPOSE ^

-
importModel
- -

SYNOPSIS ^

-
function model=importModel(fileName,removeExcMets,removePrefix,supressWarnings)
- -

DESCRIPTION ^

-
 importModel
-   Import a constraint-based model from an SBML file.
-
- Input:
-   fileName        a SBML file to import. A dialog window will open if
-                   no file name is specified.
-   removeExcMets   true if exchange metabolites should be removed. This is
-                   needed to be able to run simulations, but it could also
-                   be done using simplifyModel at a later stage (optional,
-                   default true)
-   removePrefix    true if identifier prefixes should be removed when
-                   loading the model: G_ for genes, R_ for reactions,
-                   M_ for metabolites, and C_ for compartments. These are
-                   only removed if all identifiers of a certain type
-                   contain the prefix. (optional, default true)
-   supressWarnings true if warnings regarding the model structure should
-                   be supressed (optional, default false)
-
- Output:
-   model
-       id               model ID
-       name             name of model contents
-       annotation       additional information about model
-       rxns             reaction ids
-       mets             metabolite ids
-       S                stoichiometric matrix
-       lb               lower bounds
-       ub               upper bounds
-       rev              reversibility vector
-       c                objective coefficients
-       b                equality constraints for the metabolite equations
-       comps            compartment ids
-       compNames        compartment names
-       compOutside      the id (as in comps) for the compartment
-                        surrounding each of the compartments
-       compMiriams      structure with MIRIAM information about the
-                        compartments
-       rxnNames         reaction description
-       rxnComps         compartments for reactions
-       grRules          reaction to gene rules in text form
-       rxnGeneMat       reaction-to-gene mapping in sparse matrix form
-       subSystems       subsystem name for each reaction
-       eccodes          EC-codes for the reactions
-       rxnMiriams       structure with MIRIAM information about the reactions
-       rxnNotes         reaction notes
-       rxnReferences    reaction references
-       rxnConfidenceScores reaction confidence scores
-       genes            list of all genes
-       geneComps        compartments for genes
-       geneMiriams      structure with MIRIAM information about the genes
-       geneShortNames   gene alternative names (e.g. ERG10)
-       proteins         protein associated to each gene
-       metNames         metabolite description
-       metComps         compartments for metabolites
-       inchis           InChI-codes for metabolites
-       metFormulas      metabolite chemical formula
-       metMiriams       structure with MIRIAM information about the metabolites
-       metCharges       metabolite charge
-       unconstrained    true if the metabolite is an exchange metabolite
-
- Note: A number of consistency checks are performed in order to ensure that the
- model is valid. Take these warnings seriously and modify the model
- structure to solve them.
-
- Usage: model = importModel(fileName, removeExcMets, removePrefix, supressWarnings)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 function model=importModel(fileName,removeExcMets,removePrefix,supressWarnings)
-0002 % importModel
-0003 %   Import a constraint-based model from an SBML file.
-0004 %
-0005 % Input:
-0006 %   fileName        a SBML file to import. A dialog window will open if
-0007 %                   no file name is specified.
-0008 %   removeExcMets   true if exchange metabolites should be removed. This is
-0009 %                   needed to be able to run simulations, but it could also
-0010 %                   be done using simplifyModel at a later stage (optional,
-0011 %                   default true)
-0012 %   removePrefix    true if identifier prefixes should be removed when
-0013 %                   loading the model: G_ for genes, R_ for reactions,
-0014 %                   M_ for metabolites, and C_ for compartments. These are
-0015 %                   only removed if all identifiers of a certain type
-0016 %                   contain the prefix. (optional, default true)
-0017 %   supressWarnings true if warnings regarding the model structure should
-0018 %                   be supressed (optional, default false)
-0019 %
-0020 % Output:
-0021 %   model
-0022 %       id               model ID
-0023 %       name             name of model contents
-0024 %       annotation       additional information about model
-0025 %       rxns             reaction ids
-0026 %       mets             metabolite ids
-0027 %       S                stoichiometric matrix
-0028 %       lb               lower bounds
-0029 %       ub               upper bounds
-0030 %       rev              reversibility vector
-0031 %       c                objective coefficients
-0032 %       b                equality constraints for the metabolite equations
-0033 %       comps            compartment ids
-0034 %       compNames        compartment names
-0035 %       compOutside      the id (as in comps) for the compartment
-0036 %                        surrounding each of the compartments
-0037 %       compMiriams      structure with MIRIAM information about the
-0038 %                        compartments
-0039 %       rxnNames         reaction description
-0040 %       rxnComps         compartments for reactions
-0041 %       grRules          reaction to gene rules in text form
-0042 %       rxnGeneMat       reaction-to-gene mapping in sparse matrix form
-0043 %       subSystems       subsystem name for each reaction
-0044 %       eccodes          EC-codes for the reactions
-0045 %       rxnMiriams       structure with MIRIAM information about the reactions
-0046 %       rxnNotes         reaction notes
-0047 %       rxnReferences    reaction references
-0048 %       rxnConfidenceScores reaction confidence scores
-0049 %       genes            list of all genes
-0050 %       geneComps        compartments for genes
-0051 %       geneMiriams      structure with MIRIAM information about the genes
-0052 %       geneShortNames   gene alternative names (e.g. ERG10)
-0053 %       proteins         protein associated to each gene
-0054 %       metNames         metabolite description
-0055 %       metComps         compartments for metabolites
-0056 %       inchis           InChI-codes for metabolites
-0057 %       metFormulas      metabolite chemical formula
-0058 %       metMiriams       structure with MIRIAM information about the metabolites
-0059 %       metCharges       metabolite charge
-0060 %       unconstrained    true if the metabolite is an exchange metabolite
-0061 %
-0062 % Note: A number of consistency checks are performed in order to ensure that the
-0063 % model is valid. Take these warnings seriously and modify the model
-0064 % structure to solve them.
-0065 %
-0066 % Usage: model = importModel(fileName, removeExcMets, removePrefix, supressWarnings)
-0067 
-0068 if nargin<1 || isempty(fileName)
-0069     [fileName, pathName] = uigetfile({'*.xml;*.sbml'}, 'Please select the model file');
-0070     if fileName == 0
-0071         error('You should select a model file')
-0072     else
-0073         fileName = fullfile(pathName,fileName);
-0074     end
-0075 end
-0076 fileName=char(fileName);
-0077 if nargin<2 || isempty(removeExcMets)
-0078     removeExcMets=true;
-0079 end
-0080 
-0081 if nargin<3 || isempty(removePrefix)
-0082     removePrefix=true;
-0083 end
-0084 
-0085 if nargin<4
-0086     supressWarnings=false;
-0087 end
-0088 
-0089 fileName=checkFileExistence(fileName,1);
-0090 % If path contains non-ASCII characters, copy file to tempdir first, as
-0091 % libSBML is known to have problems with this on Windows:
-0092 % https://sbml.org/software/libsbml/libsbml-docs/known-pitfalls/#matlab-on-windows-has-issues-with-unicode-filenames
-0093 if ispc && any(double(fileName)>128)
-0094     [~,originalFile,ext] = fileparts(fileName);
-0095     tempFile = fullfile(tempdir,[originalFile ext]);
-0096     copyfile(fileName,tempFile);
-0097     fileName = tempFile;
-0098 end
-0099 
-0100 %This is to match the order of the fields to those you get from importing
-0101 %from Excel
-0102 model=[];
-0103 model.id=[];
-0104 model.name=[];
-0105 model.annotation=[];
-0106 model.rxns={};
-0107 model.mets={};
-0108 model.S=[];
-0109 model.lb=[];
-0110 model.ub=[];
-0111 model.rev=[];
-0112 model.c=[];
-0113 model.b=[];
-0114 model.comps={};
-0115 model.compNames={};
-0116 model.compOutside={};
-0117 model.compMiriams={};
-0118 model.rxnNames={};
-0119 model.rxnComps=[];
-0120 model.grRules={};
-0121 model.rxnGeneMat=[];
-0122 model.subSystems={};
-0123 model.eccodes={};
-0124 model.rxnMiriams={};
-0125 model.rxnNotes={};
-0126 model.rxnReferences={};
-0127 model.rxnConfidenceScores=[];
-0128 model.genes={};
-0129 model.geneComps=[];
-0130 model.geneMiriams={};
-0131 model.geneShortNames={};
-0132 model.proteins={};
-0133 model.metNames={};
-0134 model.metComps=[];
-0135 model.inchis={};
-0136 model.metFormulas={};
-0137 model.metMiriams={};
-0138 model.metCharges=[];
-0139 model.unconstrained=[];
-0140 
-0141 %Load the model using libSBML
-0142 [modelSBML,errorMsg] = TranslateSBML_RAVEN(fileName,0,0,[1 1]);
-0143 if exist('tempFile','var')
-0144     delete(tempFile)
-0145 end
-0146 
-0147 if isempty(modelSBML)
-0148     EM=['There is a problem with the SBML file. Try using the SBML Validator at http://sbml.org/Facilities/Validator.\nlibSBML reports: ', errorMsg.message];
-0149     dispEM(EM);
-0150 end
-0151 
-0152 %Retrieve compartment names and IDs
-0153 compartmentNames=cell(numel(modelSBML.compartment),1);
-0154 compartmentIDs=cell(numel(modelSBML.compartment),1);
-0155 compartmentOutside=cell(numel(modelSBML.compartment),1);
-0156 compartmentMiriams=cell(numel(modelSBML.compartment),1);
-0157 
-0158 if isfield(modelSBML.compartment,'sboTerm') && isscalar(unique([modelSBML.compartment.sboTerm]))
-0159     %If all the SBO terms are identical, don't add them to compMiriams
-0160     modelSBML.compartment = rmfield(modelSBML.compartment,'sboTerm');
-0161 end
-0162 
-0163 for i=1:numel(modelSBML.compartment)
-0164     compartmentNames{i}=modelSBML.compartment(i).name;
-0165     compartmentIDs{i}=modelSBML.compartment(i).id;
-0166     if isfield(modelSBML.compartment(i),'outside')
-0167         if ~isempty(modelSBML.compartment(i).outside)
-0168             compartmentOutside{i}=modelSBML.compartment(i).outside;
-0169         else
-0170             compartmentOutside{i}='';
-0171         end
-0172     else
-0173         compartmentOutside{i}=[];
-0174     end
-0175 
-0176     if isfield(modelSBML.compartment(i),'annotation')
-0177         compartmentMiriams{i}=parseMiriam(modelSBML.compartment(i).annotation);
-0178     else
-0179         compartmentMiriams{i}=[];
-0180     end
-0181 
-0182     if isfield(modelSBML.compartment(i),'sboTerm') && ~(modelSBML.compartment(i).sboTerm==-1)
-0183         compartmentMiriams{i} = addSBOtoMiriam(compartmentMiriams{i},modelSBML.compartment(i).sboTerm);
-0184     end
-0185 end
-0186 
-0187 %If there are no compartment names then use compartment id as name
-0188 if all(cellfun(@isempty,compartmentNames))
-0189     compartmentNames=compartmentIDs;
-0190 end
-0191 
-0192 %Retrieve info on metabolites, genes, complexes
-0193 metaboliteNames={};
-0194 metaboliteIDs={};
-0195 metaboliteCompartments={};
-0196 metaboliteUnconstrained=[];
-0197 metaboliteFormula={};
-0198 metaboliteInChI={};
-0199 metaboliteMiriams={};
-0200 metaboliteCharges=[];
-0201 
-0202 geneNames={};
-0203 geneIDs={};
-0204 geneMiriams={};
-0205 geneShortNames={};
-0206 proteins={};
-0207 geneCompartments={};
-0208 complexIDs={};
-0209 complexNames={};
-0210 
-0211 %If the file is not a COBRA Toolbox model. According to the format
-0212 %specified in the yeast consensus model both metabolites and genes are a
-0213 %type of 'species'. The metabolites have names starting with 'M_' and genes
-0214 %with 'E_'
-0215 geneSBOs = [];
-0216 metSBOs = [];
-0217 %Regex of compartment names, later to be used to remove from metabolite
-0218 %names if present as suffix.
-0219 regexCompNames = ['\s?\[((' strjoin({modelSBML.compartment.name},')|(') '))\]$'];
-0220 for i=1:numel(modelSBML.species)
-0221     if length(modelSBML.species(i).id)>=2 && strcmpi(modelSBML.species(i).id(1:2),'E_')
-0222         geneNames{numel(geneNames)+1,1}=modelSBML.species(i).name;
-0223 
-0224         %The "E_" is included in the ID. This is because it's only used
-0225         %internally in this file and it makes the matching a little
-0226         %smoother
-0227         geneIDs{numel(geneIDs)+1,1}=modelSBML.species(i).id;
-0228         geneCompartments{numel(geneCompartments)+1,1}=modelSBML.species(i).compartment;
-0229 
-0230         %Get Miriam structure
-0231         if isfield(modelSBML.species(i),'annotation')
-0232             %Get Miriam info
-0233             geneMiriam=parseMiriam(modelSBML.species(i).annotation);
-0234             geneMiriams{numel(geneMiriams)+1,1}=geneMiriam;
-0235         else
-0236             geneMiriams{numel(geneMiriams)+1,1}=[];
-0237         end
-0238 
-0239         %Protein short names (for example ERG10) are saved as SHORT
-0240         %NAME: NAME in the notes-section of metabolites for SBML Level
-0241         %2 and as PROTEIN_ASSOCIATION for each reaction in SBML Level 2
-0242         %COBRA Toolbox format. For now only the SHORT NAME is loaded
-0243         %and no mapping takes place
-0244         if isfield(modelSBML.species(i),'notes')
-0245             geneShortNames{numel(geneShortNames)+1,1}=parseNote(modelSBML.species(i).notes,'SHORT NAME');
-0246         else
-0247             geneShortNames{numel(geneShortNames)+1,1}='';
-0248         end
-0249 
-0250         %Get SBO term
-0251         if isfield(modelSBML.species(i),'sboTerm') && ~(modelSBML.species(i).sboTerm==-1)
-0252             geneSBOs(end+1,1) = modelSBML.species(i).sboTerm;
-0253         end
-0254     elseif length(modelSBML.species(i).id)>=2 && strcmpi(modelSBML.species(i).id(1:3),'Cx_')
-0255         %If it's a complex keep the ID and name
-0256         complexIDs=[complexIDs;modelSBML.species(i).id];
-0257         complexNames=[complexNames;modelSBML.species(i).name];
-0258     else
-0259         %If it is not gene or complex, then it must be a metabolite
-0260         metaboliteNames{numel(metaboliteNames)+1,1}=modelSBML.species(i).name;
-0261         metaboliteIDs{numel(metaboliteIDs)+1,1}=modelSBML.species(i).id;
-0262         metaboliteCompartments{numel(metaboliteCompartments)+1,1}=modelSBML.species(i).compartment;
-0263         metaboliteUnconstrained(numel(metaboliteUnconstrained)+1,1)=modelSBML.species(i).boundaryCondition;
-0264 
-0265         %For each metabolite retrieve the formula and the InChI code if
-0266         %available First add the InChI code and the formula from the
-0267         %InChI. This allows for overwriting the formula by setting the
-0268         %actual formula field
-0269         if ~isempty(modelSBML.species(i).annotation)
-0270             %Get the formula if available
-0271             startString='>InChI=';
-0272             endString='</in:inchi>';
-0273             formStart=strfind(modelSBML.species(i).annotation,startString);
-0274             if isempty(formStart)
-0275                 startString='InChI=';
-0276                 endString='"/>';
-0277             end
-0278             formStart=strfind(modelSBML.species(i).annotation,startString);
-0279             if ~isempty(formStart)
-0280                 formEnd=strfind(modelSBML.species(i).annotation,endString);
-0281                 formEndIndex=find(formEnd>formStart, 1 );
-0282                 formula=modelSBML.species(i).annotation(formStart+numel(startString):formEnd(formEndIndex)-1);
-0283                 metaboliteInChI{numel(metaboliteInChI)+1,1}=formula;
-0284 
-0285                 %The composition is most often present between the
-0286                 %first and second "/" in the model. In some simple
-0287                 %molecules, such as salts, there is no second "/". The
-0288                 %formula is then assumed to be to the end of the string
-0289                 compositionIndexes=strfind(formula,'/');
-0290                 if numel(compositionIndexes)>1
-0291                     metaboliteFormula{numel(metaboliteFormula)+1,1}=...
-0292                         formula(compositionIndexes(1)+1:compositionIndexes(2)-1);
-0293                 else
-0294                     if isscalar(compositionIndexes)
-0295                         %Probably a simple molecule which can have only
-0296                         %one conformation
-0297                         metaboliteFormula{numel(metaboliteFormula)+1,1}=...
-0298                             formula(compositionIndexes(1)+1:numel(formula));
-0299                     else
-0300                         metaboliteFormula{numel(metaboliteFormula)+1,1}='';
-0301                     end
-0302                 end
-0303             elseif isfield(modelSBML.species(i),'fbc_chemicalFormula')
-0304                 metaboliteInChI{numel(metaboliteInChI)+1,1}='';
-0305                 if ~isempty(modelSBML.species(i).fbc_chemicalFormula)
-0306                     %Cannot extract InChi from formula, so remains
-0307                     %empty
-0308                     metaboliteFormula{numel(metaboliteFormula)+1,1}=modelSBML.species(i).fbc_chemicalFormula;
-0309                 else
-0310                     metaboliteFormula{numel(metaboliteFormula)+1,1}='';
-0311                 end
-0312             else
-0313                 metaboliteInChI{numel(metaboliteInChI)+1,1}='';
-0314                 metaboliteFormula{numel(metaboliteFormula)+1,1}='';
-0315             end
-0316 
-0317             %Get Miriam info
-0318             metMiriam=parseMiriam(modelSBML.species(i).annotation);
-0319             metaboliteMiriams{numel(metaboliteMiriams)+1,1}=metMiriam;
-0320         else
-0321             metaboliteInChI{numel(metaboliteInChI)+1,1}='';
-0322             if isfield(modelSBML.species(i),'notes')
-0323                 metaboliteFormula{numel(metaboliteFormula)+1,1}=parseNote(modelSBML.species(i).notes,'FORMULA');
-0324             else
-0325                 metaboliteFormula{numel(metaboliteFormula)+1,1}='';
-0326             end
-0327             metaboliteMiriams{numel(metaboliteMiriams)+1,1}=[];
-0328         end
-0329         if ~isempty(modelSBML.species(i).notes)
-0330             if ~isfield(modelSBML.species(i),'annotation')
-0331                 metaboliteFormula{numel(metaboliteFormula)+1,1}=parseNote(modelSBML.species(i).notes,'FORMULA');
-0332             end
-0333         elseif ~isfield(modelSBML.species(i),'annotation')
-0334             metaboliteFormula{numel(metaboliteFormula)+1,1}='';
-0335         end
-0336         %Get SBO term
-0337         if isfield(modelSBML.species(i),'sboTerm') && ~(modelSBML.species(i).sboTerm==-1)
-0338             metSBOs(end+1,1) = modelSBML.species(i).sboTerm;
-0339         end
-0340     end
-0341 
-0342     %The following lines are executed regardless isSBML2COBRA setting
-0343     if isempty(modelSBML.species(i).id) || ~strcmpi(modelSBML.species(i).id(1:2),'E_')
-0344         if isempty(modelSBML.species(i).id) || ~strcmpi(modelSBML.species(i).id(1:3),'Cx_')
-0345             %Remove trailing [compartment] from metabolite name if present
-0346             metaboliteNames{end,1}=regexprep(metaboliteNames{end,1},regexCompNames,'');
-0347             metaboliteNames{end,1}=metaboliteNames{end,1};
-0348             if isfield(modelSBML.species(i),'fbc_charge')
-0349                 if ~isempty(modelSBML.species(i).fbc_charge) && modelSBML.species(i).isSetfbc_charge
-0350                     metaboliteCharges(numel(metaboliteCharges)+1,1)=double(modelSBML.species(i).fbc_charge);
-0351                 else
-0352                     if isfield(modelSBML.species(i),'notes')
-0353                         if strfind(modelSBML.species(i).notes,'CHARGE')
-0354                             metaboliteCharges(numel(metaboliteCharges)+1,1)=str2double(parseNote(modelSBML.species(i).notes,'CHARGE'));
-0355                         else
-0356                             metaboliteCharges(numel(metaboliteCharges)+1,1)=NaN;
-0357                         end
-0358                     else
-0359                         metaboliteCharges(numel(metaboliteCharges)+1,1)=NaN;
-0360                     end
-0361                 end
-0362             elseif isfield(modelSBML.species(i),'notes')
-0363                 if strfind(modelSBML.species(i).notes,'CHARGE')
-0364                     metaboliteCharges(numel(metaboliteCharges)+1,1)=str2double(parseNote(modelSBML.species(i).notes,'CHARGE'));
-0365                 else
-0366                     metaboliteCharges(numel(metaboliteCharges)+1,1)=NaN;
-0367                 end
-0368             else
-0369                 metaboliteCharges(numel(metaboliteCharges)+1,1)=NaN;
-0370             end
-0371             %Additional information from FBC format Chemical formula
-0372             if isfield(modelSBML.species(i),'fbc_chemicalFormula')
-0373                 if ~isempty(modelSBML.species(i).fbc_chemicalFormula)
-0374                     metaboliteFormula{numel(metaboliteFormula),1}=modelSBML.species(i).fbc_chemicalFormula;
-0375                 end
-0376             end
-0377         end
-0378     end
-0379 end
-0380 
-0381 %Add SBO terms to gene and metabolite miriam fields
-0382 if numel(unique(geneSBOs)) > 1  % don't add if they're all identical
-0383     for i = 1:numel(geneNames)
-0384         geneMiriams{i} = addSBOtoMiriam(geneMiriams{i},geneSBOs(i));
-0385     end
-0386 end
-0387 if numel(unique(metSBOs)) > 1
-0388     for i = 1:numel(metaboliteNames)
-0389         metaboliteMiriams{i} = addSBOtoMiriam(metaboliteMiriams{i},metSBOs(i));
-0390     end
-0391 end
-0392 
-0393 %Retrieve info on reactions
-0394 reactionNames=cell(numel(modelSBML.reaction),1);
-0395 reactionIDs=cell(numel(modelSBML.reaction),1);
-0396 subsystems=cell(numel(modelSBML.reaction),1);
-0397 eccodes=cell(numel(modelSBML.reaction),1);
-0398 eccodes(:,:)=cellstr('');
-0399 rxnconfidencescores=NaN(numel(modelSBML.reaction),1);
-0400 rxnreferences=cell(numel(modelSBML.reaction),1);
-0401 rxnreferences(:,:)=cellstr('');
-0402 rxnnotes=cell(numel(modelSBML.reaction),1);
-0403 rxnnotes(:,:)=cellstr('');
-0404 grRules=cell(numel(modelSBML.reaction),1);
-0405 grRules(:,:)=cellstr('');
-0406 grRulesFromModifier=grRules;
-0407 rxnComps=zeros(numel(modelSBML.reaction),1);
-0408 rxnMiriams=cell(numel(modelSBML.reaction),1);
-0409 reactionReversibility=zeros(numel(modelSBML.reaction),1);
-0410 reactionUB=zeros(numel(modelSBML.reaction),1);
-0411 reactionLB=zeros(numel(modelSBML.reaction),1);
-0412 reactionObjective=zeros(numel(modelSBML.reaction),1);
-0413 
-0414 %Construct the stoichiometric matrix while the reaction info is read
-0415 S=zeros(numel(metaboliteIDs),numel(modelSBML.reaction));
-0416 
-0417 counter=0;
-0418 %If FBC, then bounds have parameter ids defined for the whole model
-0419 if isfield(modelSBML,'parameter')
-0420     parameter.name=cell(numel(modelSBML.parameter),1);
-0421     parameter.name={modelSBML.parameter(:).id}';
-0422     parameter.value={modelSBML.parameter(:).value}';
-0423 end
-0424 
-0425 if isfield(modelSBML.reaction,'sboTerm') && isscalar(unique([modelSBML.reaction.sboTerm]))
-0426     %If all the SBO terms are identical, don't add them to rxnMiriams
-0427     modelSBML.reaction = rmfield(modelSBML.reaction,'sboTerm');
-0428 end
-0429 
-0430 for i=1:numel(modelSBML.reaction)
-0431 
-0432     %Check that the reaction doesn't produce a complex and nothing else. If
-0433     %so, then jump to the next reaction. This is because I get the genes
-0434     %for complexes from the names and not from the reactions that create
-0435     %them. This only applies to the non-COBRA format
-0436     if isscalar(modelSBML.reaction(i).product)
-0437         if length(modelSBML.reaction(i).product(1).species)>=3
-0438             if strcmp(modelSBML.reaction(i).product(1).species(1:3),'Cx_')==true
-0439                 continue;
-0440             end
-0441         end
-0442     end
-0443 
-0444     %It didn't look like a gene complex-forming reaction
-0445     counter=counter+1;
-0446 
-0447     reactionNames{counter}=modelSBML.reaction(i).name;
-0448 
-0449     reactionIDs{counter}=modelSBML.reaction(i).id;
-0450     reactionReversibility(counter)=modelSBML.reaction(i).reversible;
-0451 
-0452     %If model is FBC, first get parameter of bound and then replace it with
-0453     %the correct value. Probably faster with replace(), but this was only
-0454     %introduced in Matlab R2016b
-0455     if isfield(modelSBML.reaction(i),'fbc_lowerFluxBound')
-0456         lb=modelSBML.reaction(i).fbc_lowerFluxBound;
-0457         ub=modelSBML.reaction(i).fbc_upperFluxBound;
-0458         [~,fluxBoundIdx] = ismember({lb,ub},parameter.name);
-0459         reactionLB(counter) = parameter.value{fluxBoundIdx(1)};
-0460         reactionUB(counter) = parameter.value{fluxBoundIdx(2)};
-0461     elseif isfield(modelSBML.reaction(i).kineticLaw,'parameter')
-0462         reactionLB(counter)=modelSBML.reaction(i).kineticLaw.parameter(1).value;
-0463         reactionUB(counter)=modelSBML.reaction(i).kineticLaw.parameter(2).value;
-0464         reactionObjective(counter)=modelSBML.reaction(i).kineticLaw.parameter(3).value;
-0465     else
-0466         if reactionReversibility(counter)==true
-0467             reactionLB(counter)=-inf;
-0468         else
-0469             reactionLB(counter)=0;
-0470         end
-0471         reactionUB(counter)=inf;
-0472         reactionObjective(counter)=0;
-0473     end
-0474 
-0475     %Find the associated gene if available
-0476     %If FBC, get gene association data from corresponding fields
-0477     if isfield(modelSBML.reaction(i),'fbc_geneProductAssociation')
-0478         if ~isempty(modelSBML.reaction(i).fbc_geneProductAssociation) && ~isempty(modelSBML.reaction(i).fbc_geneProductAssociation.fbc_association)
-0479             grRules{counter}=modelSBML.reaction(i).fbc_geneProductAssociation.fbc_association.fbc_association;
-0480         end
-0481     elseif isfield(modelSBML.reaction(i),'notes')
-0482         %This section was previously executed only if isSBML2COBRA is true. Now
-0483         %it will be executed, if 'GENE_ASSOCIATION' is found in
-0484         %modelSBML.reaction(i).notes
-0485         if strfind(modelSBML.reaction(i).notes,'GENE_ASSOCIATION')
-0486             geneAssociation=parseNote(modelSBML.reaction(i).notes,'GENE_ASSOCIATION');
-0487         elseif strfind(modelSBML.reaction(i).notes,'GENE ASSOCIATION')
-0488             geneAssociation=parseNote(modelSBML.reaction(i).notes,'GENE ASSOCIATION');
-0489         else
-0490             geneAssociation='';
-0491         end
-0492         if ~isempty(geneAssociation)
-0493             %This adds the grRules. The gene list and rxnGeneMat are created
-0494             %later
-0495             grRules{counter}=geneAssociation;
-0496         end
-0497     end
-0498     if isempty(grRules{counter}) && ~isempty(modelSBML.reaction(i).modifier)
-0499         rules='';
-0500         for j=1:numel(modelSBML.reaction(i).modifier)
-0501             modifier=modelSBML.reaction(i).modifier(j).species;
-0502             if ~isempty(modifier)
-0503                 if strcmpi(modifier(1:2),'E_')
-0504                     index=find(strcmp(modifier,geneIDs));
-0505                     %This should be unique and in the geneIDs list,
-0506                     %otherwise something is wrong
-0507                     if numel(index)~=1
-0508                         EM=['Could not get the gene association data from reaction ' reactionIDs{i}];
-0509                         dispEM(EM);
-0510                     end
-0511                     if ~isempty(rules)
-0512                         rules=[rules ' or (' geneNames{index} ')'];
-0513                     else
-0514                         rules=['(' geneNames{index} ')'];
-0515                     end
-0516                 elseif strcmp(modifier(1:2),'s_')
-0517                     index=find(strcmp(modifier,metaboliteIDs));
-0518                     %This should be unique and in the geneIDs list,
-0519                     %otherwise something is wrong
-0520                     if numel(index)~=1
-0521                         EM=['Could not get the gene association data from reaction ' reactionIDs{i}];
-0522                         dispEM(EM);
-0523                     end
-0524                     if ~isempty(rules)
-0525                         rules=[rules ' or (' metaboliteIDs{index} ')'];
-0526                     else
-0527                         rules=['(' metaboliteIDs{index} ')'];
-0528                     end
-0529                 else
-0530                     %It seems to be a complex. Add the corresponding
-0531                     %genes from the name of the complex (not the
-0532                     %reaction that creates it)
-0533                     index=find(strcmp(modifier,complexIDs));
-0534                     if isscalar(index)
-0535                         if ~isempty(rules)
-0536                             rules=[rules ' or (' strrep(complexNames{index},':',' and ') ')'];
-0537                         else
-0538                             rules=['(' strrep(complexNames{index},':',' and ') ')'];
-0539                         end
-0540                     else
-0541                         %Could not find a complex
-0542                         EM=['Could not get the gene association data from reaction ' reactionIDs{i}];
-0543                         dispEM(EM);
-0544                     end
-0545                 end
-0546             end
-0547         end
-0548         grRules{counter}=rules;
-0549         grRulesFromModifier{counter}=rules;%Backup copy for grRules, useful to parse Yeast 7.6
-0550     end
-0551 
-0552     %Add reaction compartment
-0553     if isfield(modelSBML.reaction(i),'compartment')
-0554         if ~isempty(modelSBML.reaction(i).compartment)
-0555             rxnComp=modelSBML.reaction(i).compartment;
-0556         else
-0557             rxnComp='';
-0558         end
-0559     elseif isfield(modelSBML.reaction(i),'notes')
-0560         rxnComp=parseNote(modelSBML.reaction(i).notes,'COMPARTMENT');
-0561     end
-0562     if ~isempty(rxnComp)
-0563         %Find it in the compartment list
-0564         [~, J]=ismember(rxnComp,compartmentIDs);
-0565         rxnComps(counter)=J;
-0566     end
-0567 
-0568 
-0569     miriamStruct=parseMiriam(modelSBML.reaction(i).annotation);
-0570     rxnMiriams{counter}=miriamStruct;
-0571     if isfield(modelSBML.reaction(i),'notes')
-0572         subsystems{counter,1}=cellstr(parseNote(modelSBML.reaction(i).notes,'SUBSYSTEM'));
-0573         subsystems{counter,1}(cellfun('isempty',subsystems{counter,1})) = [];
-0574         if strfind(modelSBML.reaction(i).notes,'Confidence Level')
-0575             confScore = parseNote(modelSBML.reaction(i).notes,'Confidence Level');
-0576             if isempty(confScore)
-0577                 confScore = 0;
-0578             end
-0579             rxnconfidencescores(counter)=str2double(confScore);
-0580         end
-0581         rxnreferences{counter,1}=parseNote(modelSBML.reaction(i).notes,'AUTHORS');
-0582         rxnnotes{counter,1}=parseNote(modelSBML.reaction(i).notes,'NOTES');
-0583     end
-0584 
-0585     %Get SBO terms
-0586     if isfield(modelSBML.reaction(i),'sboTerm') && ~(modelSBML.reaction(i).sboTerm==-1)
-0587         rxnMiriams{counter} = addSBOtoMiriam(rxnMiriams{counter}, modelSBML.reaction(i).sboTerm);
-0588     end
-0589 
-0590     %Get ec-codes
-0591     eccode='';
-0592     if ~isempty(modelSBML.reaction(i).annotation)
-0593         if strfind(modelSBML.reaction(i).annotation,'urn:miriam:ec-code')
-0594             eccode=parseAnnotation(modelSBML.reaction(i).annotation,'urn:miriam:',':','ec-code');
-0595         elseif strfind(modelSBML.reaction(i).annotation,'http://identifiers.org/ec-code')
-0596             eccode=parseAnnotation(modelSBML.reaction(i).annotation,'http://identifiers.org/','/','ec-code');
-0597         elseif strfind(modelSBML.reaction(i).annotation,'https://identifiers.org/ec-code')
-0598             eccode=parseAnnotation(modelSBML.reaction(i).annotation,'https://identifiers.org/','/','ec-code');
-0599         end
-0600     elseif isfield(modelSBML.reaction(i),'notes')
-0601         if strfind(modelSBML.reaction(i).notes,'EC Number')
-0602             eccode=[eccode parseNote(modelSBML.reaction(i).notes,'EC Number')];
-0603         elseif strfind(modelSBML.reaction(i).notes,'PROTEIN_CLASS')
-0604             eccode=[eccode parseNote(modelSBML.reaction(i).notes,'PROTEIN_CLASS')];
-0605         end
-0606     end
-0607     eccodes{counter}=eccode;
-0608 
-0609     %Add all reactants
-0610     for j=1:numel(modelSBML.reaction(i).reactant)
-0611         %Get the index of the metabolite in metaboliteIDs. External
-0612         %metabolites will be removed at a later stage
-0613         metIndex=find(strcmp(modelSBML.reaction(i).reactant(j).species,metaboliteIDs),1);
-0614         if isempty(metIndex)
-0615             EM=['Could not find metabolite ' modelSBML.reaction(i).reactant(j).species ' in reaction ' reactionIDs{counter}];
-0616             dispEM(EM);
-0617         end
-0618         S(metIndex,counter)=S(metIndex,counter)+modelSBML.reaction(i).reactant(j).stoichiometry*-1;
-0619     end
-0620 
-0621     %Add all products
-0622     for j=1:numel(modelSBML.reaction(i).product)
-0623         %Get the index of the metabolite in metaboliteIDs.
-0624         metIndex=find(strcmp(modelSBML.reaction(i).product(j).species,metaboliteIDs),1);
-0625         if isempty(metIndex)
-0626             EM=['Could not find metabolite ' modelSBML.reaction(i).product(j).species ' in reaction ' reactionIDs{counter}];
-0627             dispEM(EM);
-0628         end
-0629         S(metIndex,counter)=S(metIndex,counter)+modelSBML.reaction(i).product(j).stoichiometry;
-0630     end
-0631 end
-0632 
-0633 %if FBC, objective function is separately defined. Multiple objective
-0634 %functions can be defined, one is set as active
-0635 if isfield(modelSBML, 'fbc_activeObjective')
-0636     obj=modelSBML.fbc_activeObjective;
-0637     for i=1:numel(modelSBML.fbc_objective)
-0638         if strcmp(obj,modelSBML.fbc_objective(i).fbc_id)
-0639             if ~isempty(modelSBML.fbc_objective(i).fbc_fluxObjective)
-0640                 rxn=modelSBML.fbc_objective(i).fbc_fluxObjective.fbc_reaction;
-0641                 idx=ismember(reactionIDs,rxn);
-0642                 reactionObjective(idx)=modelSBML.fbc_objective(i).fbc_fluxObjective.fbc_coefficient;
-0643             end
-0644         end
-0645     end
-0646 end
-0647 
-0648 %subSystems can be stored as groups instead of in annotations
-0649 if isfield(modelSBML,'groups_group')
-0650     for i=1:numel(modelSBML.groups_group)
-0651         groupreactions={modelSBML.groups_group(i).groups_member(:).groups_idRef};
-0652         [~, idx] = ismember(groupreactions, reactionIDs);
-0653         if any(idx)
-0654             for j=1:numel(idx)
-0655                 if isempty(subsystems{idx(j)}) % First subsystem
-0656                     subsystems{idx(j)} = {modelSBML.groups_group(i).groups_name};
-0657                 else % Consecutive subsystems: concatenate
-0658                     subsystems{idx(j)} = horzcat(subsystems{idx(j)}, modelSBML.groups_group(i).groups_name);
-0659                 end
-0660             end
-0661         end
-0662     end
-0663 end
-0664 
-0665 %Shrink the structures if complex-forming reactions had to be skipped
-0666 reactionNames=reactionNames(1:counter);
-0667 reactionIDs=reactionIDs(1:counter);
-0668 subsystems=subsystems(1:counter);
-0669 eccodes=eccodes(1:counter);
-0670 rxnconfidencescores=rxnconfidencescores(1:counter);
-0671 rxnreferences=rxnreferences(1:counter);
-0672 rxnnotes=rxnnotes(1:counter);
-0673 grRules=grRules(1:counter);
-0674 rxnMiriams=rxnMiriams(1:counter);
-0675 reactionReversibility=reactionReversibility(1:counter);
-0676 reactionUB=reactionUB(1:counter);
-0677 reactionLB=reactionLB(1:counter);
-0678 reactionObjective=reactionObjective(1:counter);
-0679 S=S(:,1:counter);
-0680 
-0681 model.name=modelSBML.name;
-0682 model.id=modelSBML.id;
-0683 model.rxns=reactionIDs;
-0684 model.mets=metaboliteIDs;
-0685 model.S=sparse(S);
-0686 model.lb=reactionLB;
-0687 model.ub=reactionUB;
-0688 model.rev=reactionReversibility;
-0689 model.c=reactionObjective;
-0690 model.b=zeros(numel(metaboliteIDs),1);
-0691 model.comps=compartmentIDs;
-0692 model.compNames=compartmentNames;
-0693 model.rxnConfidenceScores=rxnconfidencescores;
-0694 model.rxnReferences=rxnreferences;
-0695 model.rxnNotes=rxnnotes;
-0696 
-0697 %Load annotation if available. If there are several authors, only the first
-0698 %author credentials are imported
-0699 if isfield(modelSBML,'annotation')
-0700     endString='</';
-0701     I=strfind(modelSBML.annotation,endString);
-0702     J=strfind(modelSBML.annotation,'<vCard:Family>');
-0703     if any(J)
-0704         model.annotation.familyName=modelSBML.annotation(J(1)+14:I(find(I>J(1),1))-1);
-0705     end
-0706     J=strfind(modelSBML.annotation,'<vCard:Given>');
-0707     if any(J)
-0708         model.annotation.givenName=modelSBML.annotation(J(1)+13:I(find(I>J(1),1))-1);
-0709     end
-0710     J=strfind(modelSBML.annotation,'<vCard:EMAIL>');
-0711     if any(J)
-0712         model.annotation.email=modelSBML.annotation(J(1)+13:I(find(I>J(1),1))-1);
-0713     end
-0714     J=strfind(modelSBML.annotation,'<vCard:Orgname>');
-0715     if any(J)
-0716         model.annotation.organization=modelSBML.annotation(J(1)+15:I(find(I>J(1),1))-1);
-0717     end
-0718     endString='"/>';
-0719     I=strfind(modelSBML.annotation,endString);
-0720     if strfind(modelSBML.annotation,'"urn:miriam:')
-0721         J=strfind(modelSBML.annotation,'"urn:miriam:');
-0722         if any(J)
-0723             model.annotation.taxonomy=modelSBML.annotation(J+12:I(find(I>J,1))-1);
-0724         end
-0725     else
-0726         J=strfind(modelSBML.annotation,'"http://identifiers.org/');
-0727         if any(J)
-0728             I = I(find(I>J,1))-1;
-0729             J = J(find(J<I,1))+24;
-0730             model.annotation.taxonomy=modelSBML.annotation(J:I);
-0731         else
-0732             J=strfind(modelSBML.annotation,'"https://identifiers.org/');
-0733             if any(J)
-0734                 I = I(find(I>J,1))-1;
-0735                 J = J(find(J<I,1))+25;
-0736                 model.annotation.taxonomy=modelSBML.annotation(J:I);
-0737             end
-0738         end
-0739     end
-0740 end
-0741 if isfield(modelSBML,'notes')
-0742     startString=strfind(modelSBML.notes,'xhtml">');
-0743     endString=strfind(modelSBML.notes,'</body>');
-0744     if any(startString) && any(endString)
-0745         model.annotation.note=modelSBML.notes(startString(1)+7:endString-1);
-0746         model.annotation.note=regexprep(model.annotation.note,'<p.*?>|</p.*?>','');
-0747         model.annotation.note=strtrim(model.annotation.note);
-0748         if regexp(model.annotation.note,'This file was generated using the exportModel function in RAVEN Toolbox \d\.\d and OutputSBML in libSBML')
-0749             model.annotation=rmfield(model.annotation,'note'); % Default note added when running exportModel
-0750         end
-0751     end
-0752 end
-0753 
-0754 if any(~cellfun(@isempty,compartmentOutside))
-0755     model.compOutside=compartmentOutside;
-0756 end
-0757 
-0758 model.rxnNames=reactionNames;
-0759 model.metNames=metaboliteNames;
-0760 
-0761 %Match the compartments for metabolites
-0762 [~, J]=ismember(metaboliteCompartments,model.comps);
-0763 model.metComps=J;
-0764 
-0765 %If any genes have been loaded (only for the new format)
-0766 if ~isempty(geneNames)
-0767     %In some rare cases geneNames may not necessarily be used in grRules.
-0768     %That is true for Yeast 7.6. It's therefore important to change gene
-0769     %systematic names to geneIDs in sophisticated way. Gene systematic
-0770     %names are not unique, since exactly the same name may be in different
-0771     %compartments
-0772     if all(cellfun(@isempty,strfind(grRules,geneNames{1})))
-0773         geneShortNames=geneNames;
-0774         %geneShortNames contain compartments as well, so these are removed
-0775         geneShortNames=regexprep(geneShortNames,' \[.+$','');
-0776         %grRules obtained from modifier fields contain geneNames. These are
-0777         %changed into geneIDs. grRulesFromModifier is a good way to have
-0778         %geneIDs and rxns association when it's important to resolve
-0779         %systematic name ambiguities
-0780         grRulesFromModifier=regexprep(regexprep(grRulesFromModifier,'\[|\]','_'),regexprep(geneNames,'\[|\]','_'),geneIDs);
-0781         grRules=regexprep(regexprep(grRules,'\[|\]','_'),regexprep(geneNames,'\[|\]','_'),geneIDs);
-0782 
-0783         %Yeast 7.6 contains several metabolites, which were used in gene
-0784         %associations. For that reason, the list of species ID is created
-0785         %and we then check whether any of them have kegg.genes annotation
-0786         %thereby obtaining systematic gene names
-0787         geneShortNames=vertcat(geneShortNames,metaboliteNames);
-0788         geneIDs=vertcat(geneIDs,metaboliteIDs);
-0789         geneSystNames=extractMiriam(vertcat(geneMiriams,metaboliteMiriams),'kegg.genes');
-0790         geneCompartments=vertcat(geneCompartments,metaboliteCompartments);
-0791         geneMiriams=vertcat(geneMiriams,metaboliteMiriams);
-0792 
-0793         %Now we retain information for only these entries, which have
-0794         %kegg.genes annotation
-0795         geneShortNames=geneShortNames(~cellfun('isempty',geneSystNames));
-0796         geneIDs=geneIDs(~cellfun('isempty',geneSystNames));
-0797         geneSystNames=geneSystNames(~cellfun('isempty',geneSystNames));
-0798         geneCompartments=geneCompartments(~cellfun('isempty',geneSystNames));
-0799         geneMiriams=geneMiriams(~cellfun('isempty',geneSystNames));
-0800         %Now we reorder geneIDs and geneSystNames by geneSystNames string
-0801         %length
-0802         geneNames=geneIDs;%Backuping geneIDs, since we need unsorted order for later
-0803         [~, Indx] = sort(cellfun('size', geneSystNames, 2), 'descend');
-0804         geneIDs = geneIDs(Indx);
-0805         geneSystNames = geneSystNames(Indx);
-0806         for i=1:numel(geneSystNames)
-0807             for j=1:numel(grRules)
-0808                 if strfind(grRules{j},geneSystNames{i})
-0809                     if ~isempty(grRules{j})
-0810                         if sum(ismember(geneSystNames,geneSystNames{i}))==1
-0811                             grRules{j}=regexprep(grRules{j},geneSystNames{i},geneIDs{i});
-0812                         elseif sum(ismember(geneSystNames,geneSystNames{i}))>1
-0813                             counter=0;
-0814                             ovrlpIDs=geneIDs(ismember(geneSystNames,geneSystNames{i}));
-0815                             for k=1:numel(ovrlpIDs)
-0816                                 if strfind(grRulesFromModifier{j},ovrlpIDs{k})
-0817                                     counter=counter+1;
-0818                                     grRules{j}=regexprep(grRules{j},geneSystNames{i},ovrlpIDs{k});
-0819                                 end
-0820                                 if counter>1
-0821                                     EM=['Gene association is ambiguous for reaction ' modelSBML.reaction(j).id];
-0822                                     dispEM(EM);
-0823                                 end
-0824                             end
-0825                         end
-0826                     end
-0827                 end
-0828             end
-0829         end
-0830     end
-0831     model.genes=geneNames;
-0832     model.grRules=grRules;
-0833     [grRules,rxnGeneMat] = standardizeGrRules(model,true);
-0834     model.grRules = grRules;
-0835     model.rxnGeneMat = rxnGeneMat;
-0836 
-0837     %Match the compartments for genes
-0838     [~, J]=ismember(geneCompartments,model.comps);
-0839     model.geneComps=J;
-0840 else
-0841     if ~all(cellfun(@isempty,grRules))
-0842         %If fbc_geneProduct exists, follow the specified gene order, such
-0843         %that matching geneShortNames in function below will work
-0844         if isfield(modelSBML,'fbc_geneProduct')
-0845             genes={modelSBML.fbc_geneProduct.fbc_id};
-0846 
-0847             %Get gene Miriams if they were not retrieved above (this occurs
-0848             %when genes are stored as fbc_geneProduct instead of species)
-0849             if isempty(geneMiriams)
-0850                 geneMiriams = cell(numel(genes),1);
-0851                 if isfield(modelSBML.fbc_geneProduct,'sboTerm') && isscalar(unique([modelSBML.fbc_geneProduct.sboTerm]))
-0852                     %If all the SBO terms are identical, don't add them to geneMiriams
-0853                     modelSBML.fbc_geneProduct = rmfield(modelSBML.fbc_geneProduct,'sboTerm');
-0854                 end
-0855                 for i = 1:numel(genes)
-0856                     geneMiriams{i}=parseMiriam(modelSBML.fbc_geneProduct(i).annotation);
-0857                     if isfield(modelSBML.fbc_geneProduct(i),'sboTerm') && ~(modelSBML.fbc_geneProduct(i).sboTerm==-1)
-0858                         geneMiriams{i} = addSBOtoMiriam(geneMiriams{i},modelSBML.fbc_geneProduct(i).sboTerm);
-0859                     end
-0860                 end
-0861             end
-0862             proteins={modelSBML.fbc_geneProduct.fbc_name};
-0863         else
-0864             genes=getGenesFromGrRules(grRules);
-0865         end
-0866         model.genes=genes;
-0867         model.grRules=grRules;
-0868         [grRules,rxnGeneMat] = standardizeGrRules(model,true);
-0869         model.grRules = grRules;
-0870         model.rxnGeneMat = rxnGeneMat;
-0871     end
-0872 end
-0873 
-0874 if all(cellfun(@isempty,geneShortNames))
-0875     if isfield(modelSBML,'fbc_geneProduct')
-0876         for i=1:numel(genes)
-0877             if ~isempty(modelSBML.fbc_geneProduct(i).fbc_label)
-0878                 geneShortNames{i,1}=modelSBML.fbc_geneProduct(i).fbc_label;
-0879             elseif ~isempty(modelSBML.fbc_geneProduct(i).fbc_name)
-0880                 geneShortNames{i,1}=modelSBML.fbc_geneProduct(i).fbc_name;
-0881             else
-0882                 geneShortNames{i,1}='';
-0883             end
-0884         end
-0885     end
-0886 end
-0887 
-0888 %If any InChIs have been loaded
-0889 if any(~cellfun(@isempty,metaboliteInChI))
-0890     model.inchis=metaboliteInChI;
-0891 end
-0892 
-0893 %If any formulas have been loaded
-0894 if any(~cellfun(@isempty,metaboliteFormula))
-0895     model.metFormulas=metaboliteFormula;
-0896 end
-0897 
-0898 %If any charges have been loaded
-0899 if ~isempty(metaboliteCharges)
-0900     model.metCharges=metaboliteCharges;
-0901 end
-0902 
-0903 %If any gene short names have been loaded
-0904 if any(~cellfun(@isempty,geneShortNames))
-0905     model.geneShortNames=geneShortNames;
-0906 end
-0907 
-0908 %If any Miriam strings for compartments have been loaded
-0909 if any(~cellfun(@isempty,compartmentMiriams))
-0910     model.compMiriams=compartmentMiriams;
-0911 end
-0912 
-0913 %If any Miriam strings for metabolites have been loaded
-0914 if any(~cellfun(@isempty,metaboliteMiriams))
-0915     model.metMiriams=metaboliteMiriams;
-0916 end
-0917 
-0918 %If any subsystems have been loaded
-0919 if any(~cellfun(@isempty,subsystems))
-0920     model.subSystems=subsystems;
-0921 end
-0922 if any(rxnComps)
-0923     if all(rxnComps)
-0924         model.rxnComps=rxnComps;
-0925     else
-0926         if supressWarnings==false
-0927             EM='The compartments for the following reactions could not be matched. Ignoring reaction compartment information';
-0928             dispEM(EM,false,model.rxns(rxnComps==0));
-0929         end
-0930     end
-0931 end
-0932 
-0933 %If any ec-codes have been loaded
-0934 if any(~cellfun(@isempty,eccodes))
-0935     model.eccodes=eccodes;
-0936 end
-0937 
-0938 %If any Miriam strings for reactions have been loaded
-0939 if any(~cellfun(@isempty,rxnMiriams))
-0940     model.rxnMiriams=rxnMiriams;
-0941 end
-0942 
-0943 %If any Miriam strings for genes have been loaded
-0944 if any(~cellfun(@isempty,geneMiriams))
-0945     model.geneMiriams=geneMiriams;
-0946 end
-0947 
-0948 %If any protein strings have been loaded
-0949 if any(~cellfun(@isempty,proteins))
-0950     proteins = reshape(proteins,[],1);
-0951     model.proteins=proteins;
-0952 end
-0953 
-0954 model.unconstrained=metaboliteUnconstrained;
-0955 
-0956 %Convert SBML IDs back into their original strings. Here we are using part
-0957 %from convertSBMLID, originating from the COBRA Toolbox
-0958 model.rxns=regexprep(model.rxns,'__([0-9]+)__','${char(str2num($1))}');
-0959 model.mets=regexprep(model.mets,'__([0-9]+)__','${char(str2num($1))}');
-0960 model.comps=regexprep(model.comps,'__([0-9]+)__','${char(str2num($1))}');
-0961 model.grRules=regexprep(model.grRules,'__([0-9]+)__','${char(str2num($1))}');
-0962 model.genes=regexprep(model.genes,'__([0-9]+)__','${char(str2num($1))}');
-0963 model.id=regexprep(model.id,'__([0-9]+)__','${char(str2num($1))}');
-0964 
-0965 if removePrefix
-0966     [model, hasChanged]=removeIdentifierPrefix(model);
-0967     dispEM(['The following fields have prefixes removed from all entries. '...
-0968     'If this is undesired, run importModel with removePrefix as false. Example: '...
-0969     'importModel(''filename.xml'',[],false);'],false,hasChanged)
-0970 end
-0971 
-0972 %Remove unused fields
-0973 if isempty(model.annotation)
-0974     model=rmfield(model,'annotation');
-0975 end
-0976 if isempty(model.compOutside)
-0977     model=rmfield(model,'compOutside');
-0978 end
-0979 if isempty(model.compMiriams)
-0980     model=rmfield(model,'compMiriams');
-0981 end
-0982 if isempty(model.rxnComps)
-0983     model=rmfield(model,'rxnComps');
-0984 end
-0985 if isempty(model.grRules)
-0986     model=rmfield(model,'grRules');
-0987 end
-0988 if isempty(model.rxnGeneMat)
-0989     model=rmfield(model,'rxnGeneMat');
-0990 end
-0991 if isempty(model.subSystems)
-0992     model=rmfield(model,'subSystems');
-0993 else
-0994     model.subSystems(cellfun(@isempty,subsystems))={{''}};
-0995     % If all subSystems have single entries, then unnest them
-0996     if all(cellfun(@(x) iscell(x) && isscalar(x), model.subSystems))
-0997         model.subSystems = transpose([model.subSystems{:}]);
-0998     end
-0999 end
-1000 if isempty(model.eccodes)
-1001     model=rmfield(model,'eccodes');
-1002 end
-1003 if isempty(model.rxnMiriams)
-1004     model=rmfield(model,'rxnMiriams');
-1005 end
-1006 if cellfun(@isempty,model.rxnNotes)
-1007     model=rmfield(model,'rxnNotes');
-1008 end
-1009 if cellfun(@isempty,model.rxnReferences)
-1010     model=rmfield(model,'rxnReferences');
-1011 end
-1012 if isempty(model.rxnConfidenceScores) || all(isnan(model.rxnConfidenceScores))
-1013     model=rmfield(model,'rxnConfidenceScores');
-1014 end
-1015 if isempty(model.genes)
-1016     model=rmfield(model,'genes');
-1017 elseif isrow(model.genes)
-1018     model.genes=transpose(model.genes);
-1019 end
-1020 if isempty(model.geneComps)
-1021     model=rmfield(model,'geneComps');
-1022 end
-1023 if isempty(model.geneMiriams)
-1024     model=rmfield(model,'geneMiriams');
-1025 end
-1026 if isempty(model.geneShortNames)
-1027     model=rmfield(model,'geneShortNames');
-1028 end
-1029 if isempty(model.proteins)
-1030     model=rmfield(model,'proteins');
-1031 end
-1032 if isempty(model.inchis)
-1033     model=rmfield(model,'inchis');
-1034 end
-1035 if isempty(model.metFormulas)
-1036     model=rmfield(model,'metFormulas');
-1037 end
-1038 if isempty(model.metMiriams)
-1039     model=rmfield(model,'metMiriams');
-1040 end
-1041 if ~any(model.metCharges)
-1042     model=rmfield(model,'metCharges');
-1043 end
-1044 
-1045 %This just removes the grRules if no genes have been loaded
-1046 if ~isfield(model,'genes') && isfield(model,'grRules')
-1047     model=rmfield(model,'grRules');
-1048 end
-1049 
-1050 %Print warnings about bad structure
-1051 if supressWarnings==false
-1052     checkModelStruct(model,false);
-1053 end
-1054 
-1055 if removeExcMets==true
-1056     model=simplifyModel(model);
-1057 end
-1058 end
-1059 
-1060 function fieldContent=parseNote(searchString,fieldName)
-1061 %The function obtains the particular information from 'notes' field, using
-1062 %fieldName as the dummy string
-1063 
-1064 fieldContent='';
-1065 
-1066 if strfind(searchString,fieldName)
-1067     [~,targetString] = regexp(searchString,['<p>' fieldName '.*?</p>'],'tokens','match');
-1068     targetString=regexprep(targetString,'<p>|</p>','');
-1069     targetString=regexprep(targetString,[fieldName, ':'],'');
-1070     for i=1:numel(targetString)
-1071         fieldContent=[fieldContent ';' strtrim(targetString{1,i})];
-1072     end
-1073     fieldContent=regexprep(fieldContent,'^;|;$','');
-1074 else
-1075     fieldContent='';
-1076 end
-1077 end
-1078 
-1079 function fieldContent=parseAnnotation(searchString,startString,midString,fieldName)
-1080 
-1081 fieldContent='';
-1082 
-1083 %Removing whitespace characters from the ending strings, which may occur in
-1084 %several cases
-1085 searchString=regexprep(searchString,'" />','"/>');
-1086 [~,targetString] = regexp(searchString,['<rdf:li rdf:resource="' startString fieldName midString '.*?"/>'],'tokens','match');
-1087 targetString=regexprep(targetString,'<rdf:li rdf:resource="|"/>','');
-1088 targetString=regexprep(targetString,startString,'');
-1089 targetString=regexprep(targetString,[fieldName midString],'');
-1090 
-1091 for i=1:numel(targetString)
-1092     fieldContent=[fieldContent ';' strtrim(targetString{1,i})];
-1093 end
-1094 
-1095 fieldContent=regexprep(fieldContent,'^;|;$','');
-1096 end
-1097 
-1098 function miriamStruct=parseMiriam(searchString)
-1099 %Generates miriam structure from annotation field
-1100 
-1101 %Finding whether miriams are written in the old or the new way
-1102 if strfind(searchString,'urn:miriam:')
-1103     startString='urn:miriam:';
-1104 elseif strfind(searchString,'http://identifiers.org/')
-1105     startString='http://identifiers.org/';
-1106 elseif strfind(searchString,'https://identifiers.org/')
-1107     startString='https://identifiers.org/';
-1108 else
-1109     miriamStruct=[];
-1110     return;
-1111 end
-1112 
-1113 miriamStruct=[];
-1114 
-1115 searchString=regexprep(searchString,'" />','"/>');
-1116 [~,targetString] = regexp(searchString,'<rdf:li rdf:resource=".*?"/>','tokens','match');
-1117 targetString=regexprep(targetString,'<rdf:li rdf:resource="|"/>','');
-1118 targetString=regexprep(targetString,startString,'');
-1119 
-1120 fwdslash  = contains(targetString,'/');
-1121 midString = cell(numel(targetString),1);
-1122 midString(fwdslash) = {'/'};
-1123 midString(~fwdslash) = {':'};
-1124 
-1125 counter=0;
-1126 for i=1:numel(targetString)
-1127     if isempty(regexp(targetString{1,i},'inchi|ec-code', 'once'))
-1128         counter=counter+1;
-1129         miriamStruct.name{counter,1} = regexprep(targetString{1,i},[midString{i} '.+'],'','once');
-1130         miriamStruct.value{counter,1} = regexprep(targetString{1,i},[miriamStruct.name{counter,1} midString{i}],'','once');
-1131         miriamStruct.name{counter,1} = regexprep(miriamStruct.name{counter,1},'^obo\.','');
-1132     end
-1133 end
-1134 end
-1135 
-1136 function miriam = addSBOtoMiriam(miriam,sboTerm)
-1137 %Appends SBO term to miriam structure
-1138 
-1139 sboTerm = {['SBO:' sprintf('%07u',sboTerm)]};  % convert to proper format
-1140 if isempty(miriam)
-1141     miriam.name = {'sbo'};
-1142     miriam.value = sboTerm;
-1143 elseif any(strcmp('sbo',miriam.name))
-1144     currSbo = strcmp('sbo',miriam.name);
-1145     miriam.value(currSbo) = sboTerm;
-1146 else
-1147     miriam.name(end+1) = {'sbo'};
-1148     miriam.value(end+1) = sboTerm;
-1149 end
-1150 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/io/index.html b/doc/io/index.html deleted file mode 100644 index 894f6b1fc..000000000 --- a/doc/io/index.html +++ /dev/null @@ -1,29 +0,0 @@ - - - - Index for Directory io - - - - - - - - - - -
< Master indexIndex for io >
- -

Index for io

- -

Matlab files in this directory:

- -
 SBMLFromExcelSBMLFromExcel
 addJavaPathsaddJavaPaths
 checkFileExistencecheckFileExistence
 cleanSheetcleanSheet
 closeModelcloseModel
 exportForGitexportForGit
 exportModelexportModel
 exportModelToSIFexportModelToSIF
 exportToExcelFormatexportToExcelFormat
 exportToTabDelimitedexportToTabDelimited
 getFullPathgetFullPath - Get absolute canonical path of a file or folder
 getMD5HashgetMD5Hash
 getToolboxVersiongetToolboxVersion
 importExcelModelimportExcelModel
 importModelimportModel
 loadSheetloadSheet
 loadWorkbookloadWorkbook
 readYAMLmodelreadYAMLmodel
 sortIdentifiersexportModel
 startupAdd the Java Paths at startup in order to be ready for use if the Toolbox is on the path
 writeSheetwriteSheet
 writeYAMLmodelwriteYAMLmodel
- - - - -
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/io/loadSheet.html b/doc/io/loadSheet.html deleted file mode 100644 index 0504929b9..000000000 --- a/doc/io/loadSheet.html +++ /dev/null @@ -1,130 +0,0 @@ - - - - Description of loadSheet - - - - - - - - - -
Home > io > loadSheet.m
- - - -

loadSheet -

- -

PURPOSE ^

-
loadSheet
- -

SYNOPSIS ^

-
function [raw, flag]=loadSheet(workbook, sheet)
- -

DESCRIPTION ^

-
 loadSheet
-   Loads an Excel sheet into a cell matrix using the Java library Apache POI
-
-   workbook    Workbook object representing the Excel file
-   sheet       name of the sheet (optional, default first sheet)
-
-   raw         cell array with the data in the sheet
-   flag        0 if everything worked, -1 if it didn't
-
- Usage: [raw, flag]=loadSheet(workbook, sheet)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - - - -

SOURCE CODE ^

-
0001 % loadSheet
-0002 %   Loads an Excel sheet into a cell matrix using the Java library Apache POI
-0003 %
-0004 %   workbook    Workbook object representing the Excel file
-0005 %   sheet       name of the sheet (optional, default first sheet)
-0006 %
-0007 %   raw         cell array with the data in the sheet
-0008 %   flag        0 if everything worked, -1 if it didn't
-0009 %
-0010 % Usage: [raw, flag]=loadSheet(workbook, sheet)
-0011 
-0012 function [raw, flag]=loadSheet(workbook, sheet)
-0013 if nargin<2
-0014     sheet=[];
-0015 end
-0016 flag=0;
-0017 raw={};
-0018 
-0019 if any(sheet)
-0020     sh=workbook.getSheet(sheet);
-0021 else
-0022     sh=workbook.getSheetAt(0);
-0023 end
-0024 if isempty(sh)
-0025     flag=-1;
-0026     return;
-0027 end
-0028 
-0029 lastRow=sh.getLastRowNum();
-0030 wasEmpty=false(lastRow+1,1);
-0031 raw=cell(lastRow+1,0); %Allocate space for the cell array. The number of columns isn't know yet, as it's saved row-by-row
-0032 for i=0:lastRow
-0033     row=sh.getRow(i);
-0034     %Sometimes the last rows only contain formatting (or some other weird
-0035     %Excel thing). Ignore such empty rows. Note the +1 to deal with that
-0036     %Matlab indexing starts at 1
-0037     if isempty(row)
-0038         wasEmpty(i+1)=true;
-0039         continue;
-0040     end
-0041     lastCol=row.getLastCellNum();
-0042     
-0043     %Adjust the size of the cell array if needed
-0044     if (lastCol+1)>size(raw,2)
-0045         raw=[raw cell(lastRow+1,lastCol+1-size(raw,2))];
-0046     end
-0047     
-0048     %Loop over the columns
-0049     for j=0:lastCol
-0050         c=row.getCell(j,row.RETURN_BLANK_AS_NULL);
-0051         if ~isempty(c)
-0052             %Then decide how to save it depending on the type. First check
-0053             %if it's a formula. If so the cached value should be used
-0054             if c.getCellType()==c.CELL_TYPE_FORMULA
-0055                 type=c.getCachedFormulaResultType();
-0056             else
-0057                 type=c.getCellType();
-0058             end
-0059             
-0060             switch type
-0061                 case c.CELL_TYPE_STRING
-0062                     raw{i+1,j+1}=char(c.getRichStringCellValue().getString());
-0063                 case c.CELL_TYPE_NUMERIC
-0064                     raw{i+1,j+1}=c.getNumericCellValue();
-0065                 case c.CELL_TYPE_BOOLEAN
-0066                     raw{i+1,j+1}=c.getBooleanCellValue();
-0067             end
-0068         end
-0069     end
-0070 end
-0071 
-0072 %Remove empty rows
-0073 raw(wasEmpty,:)=[];
-0074 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/io/loadWorkbook.html b/doc/io/loadWorkbook.html deleted file mode 100644 index 945e419a3..000000000 --- a/doc/io/loadWorkbook.html +++ /dev/null @@ -1,119 +0,0 @@ - - - - Description of loadWorkbook - - - - - - - - - -
Home > io > loadWorkbook.m
- - - -

loadWorkbook -

- -

PURPOSE ^

-
loadWorkbook
- -

SYNOPSIS ^

-
function workbook=loadWorkbook(fileName,createEmpty)
- -

DESCRIPTION ^

-
 loadWorkbook
-   Loads an Excel file into a Workbook object using the Java library Apache POI
-
-   fileName    name of the Excel file. If it doesn't exist it will be
-               created
-   createEmpty true if an empty workbook should be created if the file
-               didn't exist (optional, default false)
-
-   workbook    Workbook object representing the Excel file
-
- Usage: workbook=loadWorkbook(fileName,createEmpty)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function workbook=loadWorkbook(fileName,createEmpty)
-0002 % loadWorkbook
-0003 %   Loads an Excel file into a Workbook object using the Java library Apache POI
-0004 %
-0005 %   fileName    name of the Excel file. If it doesn't exist it will be
-0006 %               created
-0007 %   createEmpty true if an empty workbook should be created if the file
-0008 %               didn't exist (optional, default false)
-0009 %
-0010 %   workbook    Workbook object representing the Excel file
-0011 %
-0012 % Usage: workbook=loadWorkbook(fileName,createEmpty)
-0013 
-0014 if nargin<2
-0015     createEmpty=false;
-0016 end
-0017 
-0018 %Check if the user has MATLAB Text Analytics Toolbox installed, as it comes
-0019 %with its own conflicting version of the required Apache POI files
-0020 if exist('vaderSentimentScores.m')== 2
-0021     error(['MATLAB Text Analytics Toolbox found. This should be uninstalled ' ...
-0022            'if you want to read/write Excel files. See RAVEN GitHub Issues '...
-0023            'page for instructions.'])    
-0024 end
-0025     
-0026 %Adds the required classes to the static Java path if not already added
-0027 addJavaPaths();
-0028 
-0029 %Import required classes from Apache POI
-0030 import org.apache.poi.ss.usermodel.*;
-0031 import org.apache.poi.ss.util.*;
-0032 import java.io.FileInputStream;
-0033 import org.apache.poi.hssf.usermodel.*;
-0034 import org.apache.poi.xssf.usermodel.*;
-0035 
-0036 %Check if the file exists
-0037 if ~isfile(fileName)
-0038     if createEmpty==false
-0039         EM='The Excel file could not be found';
-0040         dispEM(EM);
-0041     else
-0042         %Create an empty workbook
-0043         [~,~,I]=fileparts(fileName);
-0044         if strcmpi(I,'.xls')
-0045             workbook=HSSFWorkbook();
-0046         else
-0047             if strcmpi(I,'.xlsx')
-0048                 workbook=XSSFWorkbook();
-0049             else
-0050                 EM='The file name must end in .xls or .xlsx';
-0051                 dispEM(EM);
-0052             end
-0053         end
-0054     end
-0055 else
-0056     %Opens the workbook. The input stream is needed since it will otherwise
-0057     %keep the file open
-0058     is=FileInputStream(getFullPath(fileName));
-0059     workbook=WorkbookFactory.create(is);
-0060     is.close();
-0061 end
-0062 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/io/readYAMLmodel.html b/doc/io/readYAMLmodel.html deleted file mode 100644 index d1e03747e..000000000 --- a/doc/io/readYAMLmodel.html +++ /dev/null @@ -1,750 +0,0 @@ - - - - Description of readYAMLmodel - - - - - - - - - -
Home > io > readYAMLmodel.m
- - - -

readYAMLmodel -

- -

PURPOSE ^

-
readYAMLmodel
- -

SYNOPSIS ^

-
function model=readYAMLmodel(fileName, verbose)
- -

DESCRIPTION ^

-
 readYAMLmodel
-   Reads a yaml file matching (roughly) the cobrapy yaml structure
-
-   Input:
-   fileName    a model file in yaml file format. A dialog window will open
-               if no file name is specified.
-   verbose     set as true to monitor progress (optional, default false)
-
-   Output:
-   model       a model structure
-
- Usage: model = readYAMLmodel(fileName, verbose)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 function model=readYAMLmodel(fileName, verbose)
-0002 % readYAMLmodel
-0003 %   Reads a yaml file matching (roughly) the cobrapy yaml structure
-0004 %
-0005 %   Input:
-0006 %   fileName    a model file in yaml file format. A dialog window will open
-0007 %               if no file name is specified.
-0008 %   verbose     set as true to monitor progress (optional, default false)
-0009 %
-0010 %   Output:
-0011 %   model       a model structure
-0012 %
-0013 % Usage: model = readYAMLmodel(fileName, verbose)
-0014 if nargin<1 || isempty(fileName)
-0015     [fileName, pathName] = uigetfile({'*.yml;*.yaml'}, 'Please select the model file');
-0016     if fileName == 0
-0017         error('You should select a model file')
-0018     else
-0019         fileName = fullfile(pathName,fileName);
-0020     end
-0021 end
-0022 if nargin < 2
-0023     verbose = false;
-0024 end
-0025 
-0026 if ~isfile(fileName)
-0027     error('Yaml file %s cannot be found', string(fileName));
-0028 end
-0029 
-0030 if verLessThan('matlab','9.9') %readlines introduced 2020b
-0031     fid=fopen(fileName);
-0032     line_raw=cell(1000000,1);
-0033     i=1;
-0034     while ~feof(fid)
-0035         line_raw{i}=fgetl(fid);
-0036         i=i+1;
-0037     end
-0038     line_raw(i:end)=[];
-0039     line_raw=string(line_raw);
-0040     fclose(fid);
-0041 else
-0042     line_raw=readlines(fileName);
-0043 end
-0044 % If entry is broken of multiple lines, concatenate. Assumes at least 6
-0045 % leading spaces to avoid metaData to be concatenated.
-0046 newLine=regexp(line_raw,'^ {6,}([\w\(\)].*)','tokenExtents');
-0047 brokenLine=find(~cellfun('isempty',newLine));
-0048 for i=flip(1:numel(brokenLine))
-0049     extraLine = char(line_raw(brokenLine(i)));
-0050     extraLine = extraLine(newLine{brokenLine(i)}{1}(1):end);
-0051     line_raw{brokenLine(i)-1} = strjoin({line_raw{brokenLine(i)-1},extraLine},' ');
-0052 end
-0053 line_raw(brokenLine)=[];
-0054 
-0055 line_key = regexprep(line_raw,'^ *-? ([^:]+)(:)($| .*)','$1');
-0056 line_key = regexprep(line_key,'(.*!!omap)|(---)|( {4,}.*)','');
-0057 
-0058 line_value = regexprep(line_raw, '.*:$','');
-0059 line_value = regexprep(line_value, '[^":]+: "?(.+)"?$','$1');
-0060 line_value = regexprep(line_value, '(")|(^ {4,}- )','');
-0061 line_value(strcmp(line_value,'''''')) = {''};
-0062 line_value(strcmp(line_value,line_raw)) = {''};
-0063 
-0064 modelFields =   {'id',char();...
-0065                'name',char();...
-0066         'description',char();...
-0067             'version',char();...
-0068                'date',char();...
-0069          'annotation',struct();...
-0070                'rxns',{};...
-0071            'rxnNames',{};...
-0072                'mets',{};...
-0073            'metNames',{};...
-0074                   'S',sparse([]);...
-0075                  'lb',{};... %Changed to double in the end.
-0076                  'ub',{};... %Changed to double in the end.
-0077                 'rev',{};... %Changed to double in the end.
-0078                   'c',[];...
-0079                   'b',cell(0,0);... %Changed to double in the end.
-0080               'genes',cell(0,0);...
-0081             'grRules',cell(0,0);...
-0082          'rxnGeneMat',sparse([]);...
-0083            'rxnComps',cell(0,0);... %Changed to double in the end.
-0084          'subSystems',cell(0,0);...
-0085             'eccodes',cell(0,0);...
-0086          'rxnMiriams',cell(0,0);...
-0087           'rxnDeltaG',{};... %Changed to double in the end.
-0088            'rxnNotes',cell(0,0);...
-0089       'rxnReferences',cell(0,0);...
-0090 'rxnConfidenceScores',cell(0,0);...
-0091            'metComps',cell(0,0);... %Changed to double in the end.
-0092              'inchis',cell(0,0);...
-0093           'metSmiles',cell(0,0);...
-0094         'metFormulas',cell(0,0);...
-0095          'metMiriams',cell(0,0);...
-0096           'metDeltaG',{};... %Changed to double in the end.
-0097          'metCharges',cell(0,0);... %Changed to double in the end.
-0098            'metNotes',cell(0,0);...
-0099               'comps',cell(0,0);...
-0100           'compNames',cell(0,0);...
-0101         'compOutside',cell(0,0);...
-0102           'geneComps',cell(0,0);... %Changed to double in the end.
-0103         'geneMiriams',cell(0,0);...
-0104      'geneShortNames',cell(0,0);...
-0105        'proteins',cell(0,0);...
-0106       'unconstrained',cell(0,0);... %Changed to double in the end.
-0107             'metFrom',cell(0,0);...
-0108             'rxnFrom',cell(0,0)};
-0109 for i=1:size(modelFields,1)
-0110     model.(modelFields{i,1})=modelFields{i,2};
-0111 end
-0112 
-0113 % If GECKO model
-0114 if any(contains(line_key,'geckoLight'))
-0115     isGECKO=true;
-0116     ecFields = {'geckoLight', false;...
-0117                       'rxns', {};...
-0118                       'kcat', {};...
-0119                     'source', cell(0,0);...
-0120                      'notes', cell(0,0);...
-0121                    'eccodes', cell(0,0);...
-0122                      'genes', cell(0,0);...
-0123                    'enzymes', cell(0,0);...
-0124                         'mw', cell(0,0);...
-0125                   'sequence', cell(0,0);...
-0126                      'concs', cell(0,0);...
-0127                  'rxnEnzMat', []};
-0128     for i=1:size(ecFields,1)
-0129         model.ec.(ecFields{i,1})=ecFields{i,2};
-0130     end
-0131     ecGecko=cell(25000,2);      ecGeckoNo=1;
-0132     enzStoich=cell(100000,3);   enzStoichNo=1;
-0133 else
-0134     isGECKO=false;
-0135 end
-0136 
-0137 section = 0;
-0138 metMiriams=cell(100000,3);   metMirNo=1;
-0139 rxnMiriams=cell(100000,3);   rxnMirNo=1;
-0140 geneMiriams=cell(100000,3);  genMirNo=1;
-0141 subSystems=cell(100000,2);   subSysNo=1;
-0142 eccodes=cell(100000,2);      ecCodeNo=1;
-0143 equations=cell(100000,3);    equatiNo=1;
-0144 
-0145 for i=1:numel(line_key)
-0146     tline_raw = line_raw{i};
-0147     tline_key = line_key{i};
-0148     tline_value = line_value{i};
-0149     % import different sections
-0150     switch tline_raw
-0151         case '- metaData:'
-0152             section = 1;
-0153             if verbose
-0154                 fprintf('\t%d\n', section);
-0155             end
-0156             continue % Go to next line
-0157         case '- metabolites:'
-0158             section = 2;
-0159             if verbose
-0160                 fprintf('\t%d\n', section);
-0161             end
-0162             pos=0;
-0163             continue
-0164         case '- reactions:'
-0165             section = 3;
-0166             if verbose
-0167                 fprintf('\t%d\n', section);
-0168             end
-0169             pos=0;
-0170             continue
-0171         case '- genes:'
-0172             section = 4;
-0173             if verbose
-0174                 fprintf('\t%d\n', section);
-0175             end
-0176             pos=0;
-0177             continue
-0178         case '- compartments: !!omap'
-0179             section = 5;
-0180             if verbose
-0181                 fprintf('\t%d\n', section);
-0182             end
-0183             pos=0;
-0184             continue
-0185         case '- ec-rxns:'
-0186             section = 6;
-0187             if verbose
-0188                 fprintf('\t%d\n', section);
-0189             end
-0190             pos=0;
-0191             continue
-0192         case '- ec-enzymes:'
-0193             section = 7;
-0194             if verbose
-0195                 fprintf('\t%d\n', section);
-0196             end
-0197             pos=0;
-0198             continue
-0199     end
-0200 
-0201     % skip over empty keys
-0202     if isempty(tline_raw) || (isempty(tline_key) && contains(tline_raw,'!!omap'))
-0203         continue;
-0204     end
-0205     
-0206     % import metaData
-0207     if section == 1
-0208         switch tline_key
-0209             case {'short_name','id'} %short_name used by human-GEM
-0210                 model.id = tline_value;
-0211             case 'name'
-0212                 model.name = tline_value;                
-0213             case 'full_name' %used by human-GEM
-0214                 model.description = tline_value;
-0215             case 'version'
-0216                 model.version = tline_value;
-0217             case 'date'
-0218                 model.date = tline_value;                
-0219             case 'taxonomy'
-0220                 model.annotation.taxonomy = tline_value;
-0221             case {'description','note'} %description used by human-GEM
-0222                 model.annotation.note = tline_value;
-0223             case 'github'
-0224                 model.annotation.sourceUrl = tline_value;
-0225             case 'sourceUrl'
-0226                 model.annotation.sourceUrl = tline_value;                
-0227             case 'givenName'
-0228                 model.annotation.givenName = tline_value;
-0229             case 'familyName'
-0230                 model.annotation.familyName = tline_value;
-0231             case 'authors'
-0232                 model.annotation.authorList = tline_value;
-0233             case 'email'
-0234                 model.annotation.email = tline_value;
-0235             case 'organization'
-0236                 model.annotation.organization = tline_value;
-0237             case 'geckoLight'
-0238                 if strcmp(tline_value,'true')
-0239                     model.ec.geckoLight = true;
-0240                 end
-0241         end; continue
-0242     end
-0243 
-0244     % import metabolites:
-0245     if section == 2
-0246         switch tline_key
-0247             case 'id'
-0248                 pos = pos + 1;
-0249                 model = readFieldValue(model, 'mets', tline_value,pos);
-0250                 readList=''; miriamKey='';
-0251             case 'name'
-0252                 model = readFieldValue(model, 'metNames', tline_value, pos);
-0253                 readList=''; miriamKey='';
-0254             case 'compartment'
-0255                 model = readFieldValue(model, 'metComps', tline_value, pos);
-0256                 readList=''; miriamKey='';
-0257             case 'formula'
-0258                 model = readFieldValue(model, 'metFormulas', tline_value, pos);
-0259                 readList=''; miriamKey='';
-0260             case 'charge'
-0261                 model = readFieldValue(model, 'metCharges', tline_value, pos);
-0262                 readList=''; miriamKey='';
-0263             case 'notes'
-0264                 model = readFieldValue(model, 'metNotes', tline_value, pos);
-0265                 readList=''; miriamKey='';
-0266             case 'inchis'
-0267                 model = readFieldValue(model, 'inchis', tline_value, pos);
-0268                 readList=''; miriamKey='';
-0269             case 'smiles'
-0270                 model = readFieldValue(model, 'metSmiles', tline_value, pos);
-0271                 readList=''; miriamKey='';    
-0272             case 'deltaG'
-0273                 model = readFieldValue(model, 'metDeltaG', tline_value, pos);
-0274                 readList=''; miriamKey='';                                
-0275             case 'metFrom'
-0276                 model = readFieldValue(model, 'metFrom', tline_value, pos);
-0277                 readList=''; miriamKey='';
-0278             case 'annotation'
-0279                 readList = 'annotation';
-0280             otherwise
-0281                 switch readList
-0282                     case 'annotation'
-0283                         [metMiriams, miriamKey, metMirNo] = gatherAnnotation(pos,metMiriams,tline_key,tline_value,miriamKey,metMirNo);
-0284                     otherwise
-0285                         error(['Unknown entry in yaml file: ' tline_raw])
-0286                 end
-0287         end; continue
-0288     end
-0289 
-0290     % import reactions:
-0291     if section == 3
-0292         switch tline_key
-0293             case 'id'
-0294                 pos = pos + 1;
-0295                 model = readFieldValue(model, 'rxns', tline_value,pos);
-0296                 readList=''; miriamKey='';
-0297             case 'name'
-0298                 model = readFieldValue(model, 'rxnNames', tline_value, pos);
-0299                 readList=''; miriamKey='';
-0300             case 'lower_bound'
-0301                 model.lb(pos,1) = {tline_value};
-0302                 readList=''; miriamKey='';
-0303             case 'upper_bound'
-0304                 model.ub(pos,1) = {tline_value};
-0305                 readList=''; miriamKey='';
-0306             case 'rev'
-0307                 model.rev(pos,1) = {tline_value};
-0308                 readList=''; miriamKey='';
-0309             case 'gene_reaction_rule'
-0310                 model = readFieldValue(model, 'grRules', tline_value, pos);
-0311                 readList=''; miriamKey='';
-0312             case 'rxnNotes'
-0313                 model = readFieldValue(model, 'rxnNotes', tline_value, pos);
-0314                 readList=''; miriamKey='';
-0315             case 'rxnFrom'
-0316                 model = readFieldValue(model, 'rxnFrom', tline_value, pos);
-0317                 readList=''; miriamKey='';
-0318             case 'deltaG'
-0319                 model = readFieldValue(model, 'rxnDeltaG', tline_value, pos);
-0320                 readList=''; miriamKey='';                
-0321             case 'objective_coefficient'
-0322                 model.c(pos,1) = 1;
-0323                 readList=''; miriamKey='';
-0324             case 'references'
-0325                 model = readFieldValue(model, 'rxnReferences', tline_value, pos);
-0326                 readList=''; miriamKey='';
-0327             case 'confidence_score'
-0328                 model = readFieldValue(model, 'rxnConfidenceScores', tline_value, pos);
-0329                 readList=''; miriamKey='';
-0330             case 'eccodes'
-0331                 if isempty(tline_value)
-0332                     readList = 'eccodes';
-0333                 else
-0334                     eccodes(ecCodeNo,1:2)={pos,tline_value};
-0335                     ecCodeNo=ecCodeNo+1;
-0336                 end
-0337             case 'subsystem'
-0338                 if isempty(tline_value)
-0339                     readList = 'subsystem';
-0340                 else
-0341                     subSystems(subSysNo,1:2)={pos,tline_value};
-0342                     subSysNo=subSysNo+1;
-0343                 end
-0344             case 'metabolites'
-0345                 readList = 'equation';
-0346             case 'annotation'
-0347                 readList = 'annotation';
-0348                 
-0349             otherwise
-0350                 switch readList
-0351                     case 'eccodes'
-0352                         eccodes(ecCodeNo,1:2)={pos,regexprep(tline_value,'^ +- "?(.*)"?$','$1')};
-0353                         ecCodeNo=ecCodeNo+1;
-0354                     case 'subsystem'
-0355                         subSystems(subSysNo,1:2)={pos,regexprep(tline_value,'^ +- "?(.*)"?$','$1')};
-0356                         subSysNo=subSysNo+1;
-0357                     case 'annotation'
-0358                         [rxnMiriams, miriamKey,rxnMirNo] = gatherAnnotation(pos,rxnMiriams,tline_key,tline_value,miriamKey,rxnMirNo);
-0359                     case 'equation'
-0360                         coeff = sscanf(tline_value,'%f');
-0361                         equations(equatiNo,1:3)={pos,tline_key,coeff};
-0362                         equatiNo=equatiNo+1;
-0363                     otherwise
-0364                         error(['Unknown entry in yaml file: ' tline_raw])
-0365                 end                
-0366         end; continue
-0367     end
-0368 
-0369     % import genes:
-0370     if section == 4
-0371         switch tline_key
-0372             case 'id'
-0373                 pos = pos + 1;
-0374                 model = readFieldValue(model, 'genes', tline_value, pos);
-0375                 readList = '';
-0376                 miriamKey = '';
-0377             case 'name'
-0378                 model = readFieldValue(model, 'geneShortNames', tline_value, pos);
-0379             case 'protein'
-0380                 model = readFieldValue(model, 'proteins', tline_value, pos);
-0381             case 'annotation'
-0382                 readList = 'annotation';
-0383             otherwise
-0384                 switch readList
-0385                     case 'annotation'
-0386                         [geneMiriams, miriamKey,genMirNo] = gatherAnnotation(pos,geneMiriams,tline_key,tline_value,miriamKey,genMirNo);
-0387                     otherwise
-0388                         error(['Unknown entry in yaml file: ' tline_raw])
-0389                 end
-0390         end; continue
-0391     end
-0392 
-0393     % import compartments:
-0394     if section == 5
-0395         model.comps(end+1,1) = {tline_key};
-0396         model.compNames(end+1,1) = {tline_value};
-0397     end
-0398 
-0399     % import ec reaction info
-0400     if section == 6
-0401         switch tline_key
-0402             case 'id'
-0403                 pos = pos + 1;
-0404                 model.ec = readFieldValue(model.ec, 'rxns', tline_value, pos);
-0405                 readList='';
-0406             case 'kcat'
-0407                 model.ec = readFieldValue(model.ec, 'kcat', tline_value, pos);
-0408                 readList='';
-0409             case 'source'
-0410                 model.ec = readFieldValue(model.ec, 'source', tline_value, pos);
-0411                 readList='';
-0412             case 'notes'
-0413                 model.ec = readFieldValue(model.ec, 'notes', tline_value, pos);
-0414                 readList='';
-0415             case 'eccodes'
-0416                 if isempty(tline_value)
-0417                     readList = 'eccodes';
-0418                 else
-0419                     ecGecko(ecGeckoNo,1:2)={pos,tline_value};
-0420                     ecGeckoNo=ecGeckoNo+1;
-0421                 end
-0422             case 'enzymes'
-0423                 readList = 'enzStoich';
-0424             otherwise
-0425                 switch readList
-0426                     case 'eccodes'
-0427                         ecGecko(ecGeckoNo,1:2)={pos,regexprep(tline_value,'^ +- "?(.*)"?$','$1')};
-0428                         ecGeckoNo=ecGeckoNo+1;
-0429                     case 'enzStoich'
-0430                         coeff = sscanf(tline_value,'%f');
-0431                         enzStoich(enzStoichNo,1:3)={pos,tline_key,coeff};
-0432                         enzStoichNo=enzStoichNo+1;
-0433                     otherwise
-0434                         error(['Unknown entry in yaml file: ' tline_raw])
-0435                 end
-0436         end; continue
-0437     end
-0438 
-0439     % import ec enzyme info
-0440     if section == 7
-0441         switch tline_key
-0442             case 'genes'
-0443                 pos = pos + 1;
-0444                 model.ec = readFieldValue(model.ec, 'genes', tline_value, pos);
-0445             case 'enzymes'
-0446                 model.ec = readFieldValue(model.ec, 'enzymes', tline_value, pos);
-0447             case 'mw'
-0448                 model.ec = readFieldValue(model.ec, 'mw', tline_value, pos);
-0449             case 'sequence'
-0450                 model.ec = readFieldValue(model.ec, 'sequence', tline_value, pos);
-0451             case 'concs'
-0452                 model.ec = readFieldValue(model.ec, 'concs', tline_value, pos);
-0453             otherwise
-0454                 error(['Unknown entry in yaml file: ' tline_raw])
-0455         end; continue
-0456     end
-0457 end
-0458 
-0459 %Parse annotations
-0460 if ~isempty(metMiriams)
-0461     locs = cell2mat(metMiriams(:,1));
-0462     for i=unique(locs)'
-0463         model.metMiriams{i,1}.name=metMiriams(locs==i,2);
-0464         model.metMiriams{i,1}.value=metMiriams(locs==i,3);
-0465     end
-0466 end
-0467 if ~isempty(rxnMiriams)
-0468     locs = cell2mat(rxnMiriams(:,1));
-0469     for i=unique(locs)'
-0470         model.rxnMiriams{i,1}.name=rxnMiriams(locs==i,2);
-0471         model.rxnMiriams{i,1}.value=rxnMiriams(locs==i,3);
-0472     end
-0473 end
-0474 if ~isempty(geneMiriams)
-0475     locs = cell2mat(geneMiriams(:,1));
-0476     for i=unique(locs)'
-0477         model.geneMiriams{i,1}.name=geneMiriams(locs==i,2);
-0478         model.geneMiriams{i,1}.value=geneMiriams(locs==i,3);
-0479     end
-0480 end
-0481 
-0482 %Parse subSystems
-0483 if ~isempty(subSystems)
-0484     locs = cell2mat(subSystems(:,1));
-0485     for i=unique(locs)'
-0486         model.subSystems{i,1}=subSystems(locs==i,2);
-0487     end
-0488 end
-0489 
-0490 %Parse ec-codes
-0491 if ~isempty(eccodes)
-0492     locs = cell2mat(eccodes(:,1));
-0493     for i=unique(locs)'
-0494         eccodesCat=strjoin(eccodes(locs==i,2),';');
-0495         model.eccodes{i,1}=eccodesCat;
-0496     end
-0497     emptyEc=cellfun('isempty',model.eccodes);
-0498     model.eccodes(emptyEc)={''};
-0499 end
-0500 
-0501 % follow-up data processing
-0502 if verbose
-0503     fprintf('\nimporting completed\nfollow-up processing...');
-0504 end
-0505 [~, model.metComps] = ismember(model.metComps, model.comps);
-0506 [~, model.geneComps] = ismember(model.geneComps, model.comps);
-0507 [~, model.rxnComps] = ismember(model.rxnComps, model.comps);
-0508 
-0509 % Fill S-matrix
-0510 rxnIdx = cellfun('isempty', equations(:,1));
-0511 equations(rxnIdx,:) = '';
-0512 rxnIdx = cell2mat(equations(:,1));
-0513 [~,metIdx] = ismember(equations(:,2),model.mets);
-0514 coeffs = cell2mat(equations(:,3));
-0515 model.S=sparse(max(metIdx),max(rxnIdx));
-0516 linearIndices = sub2ind([max(metIdx), max(rxnIdx)],metIdx,rxnIdx);
-0517 model.S(linearIndices) = coeffs;
-0518 
-0519 % Convert strings to numeric
-0520 model.metCharges = str2double(model.metCharges);
-0521 model.lb = str2double(model.lb);
-0522 model.ub = str2double(model.ub);
-0523 model.rxnConfidenceScores = str2double(model.rxnConfidenceScores);
-0524 model.b = zeros(length(model.mets),1);
-0525 model.metDeltaG = str2double(model.metDeltaG);
-0526 model.rxnDeltaG = str2double(model.rxnDeltaG);
-0527 
-0528 % Fill some other fields
-0529 model.annotation.defaultLB = min(model.lb);
-0530 model.annotation.defaultUB = max(model.ub);
-0531 if numel(model.lb)<numel(model.rxns) %No LB reported = min
-0532     model.lb(end+1:numel(model.rxns)-numel(model.lb),1) = double(model.annotation.defaultLB);
-0533 end
-0534 if numel(model.ub)<numel(model.rxns) %No UB reported = max
-0535     model.ub(end+1:numel(model.rxns)-numel(model.ub),1) = double(model.annotation.defaultUB);
-0536 end
-0537 if ~all(cellfun('isempty',model.rev))
-0538     model.rev = str2double(model.rev);
-0539 else
-0540     model.rev = [];
-0541 end
-0542 if numel(model.rev)<numel(model.rxns) %No rev reported, assume from LB and UB
-0543     model.rev(end+1:numel(model.rxns)-numel(model.rev),1) = double(model.lb<0 & model.ub>0);
-0544 end
-0545 
-0546 % Remove empty fields, otherwise fill to correct length
-0547 % Reactions
-0548 for i={'rxnNames','grRules','eccodes','rxnNotes','rxnReferences',...
-0549        'rxnFrom','subSystems','rxnMiriams'} % Empty strings
-0550    model = emptyOrFill(model,i{1},{''},'rxns');
-0551 end
-0552 for i={'c'} % Zeros
-0553    model = emptyOrFill(model,i{1},0,'rxns',true);
-0554 end
-0555 for i={'rxnConfidenceScores','rxnDeltaG'} % NaNs
-0556    model = emptyOrFill(model,i{1},NaN,'rxns');
-0557 end
-0558 for i={'rxnComps'} % Ones, assume first compartment
-0559    model = emptyOrFill(model,i{1},1,'rxns');
-0560 end
-0561 % Metabolites
-0562 for i={'metNames','inchis','metFormulas','metMiriams','metFrom','metSmiles','metNotes'} % Empty strings
-0563    model = emptyOrFill(model,i{1},{''},'mets');
-0564 end
-0565 for i={'metCharges','unconstrained'} % Zeros
-0566    model = emptyOrFill(model,i{1},0,'mets');
-0567 end
-0568 for i={'metDeltaG'} % % NaNs
-0569     model = emptyOrFill(model,i{1},NaN,'mets');
-0570  end
-0571 for i={'metComps'} % Ones, assume first compartment
-0572    model = emptyOrFill(model,i{1},1,'mets');
-0573 end
-0574 % Genes
-0575 for i={'geneMiriams','geneShortNames','proteins'} % Empty strings
-0576    model = emptyOrFill(model,i{1},{''},'genes');
-0577 end
-0578 for i={'geneComps'} % Ones, assume first compartment
-0579    model = emptyOrFill(model,i{1},1,'genes');
-0580 end
-0581 % Comps
-0582 for i={'compNames'} % Empty strings
-0583    model = emptyOrFill(model,i{1},{''},'comps');
-0584 end
-0585 for i={'compOutside'} % First comp
-0586    model = emptyOrFill(model,i{1},model.comps{1},'comps');
-0587 end
-0588 % Single fields are kept, even if empty
-0589 % for i={'description','name','version','date','annotation'}
-0590 %     if isempty(model.(i{1}))
-0591 %         model = rmfield(model,i{1});
-0592 %     end
-0593 % end
-0594 
-0595 if isfield(model,'subSystems')
-0596 % If all entries are 1x1, then flatten
-0597     if all(cellfun(@(x) numel(x) <= 1, model.subSystems))
-0598         model.subSystems = transpose([model.subSystems{:}]);
-0599     end
-0600 end
-0601 
-0602 % Make rxnGeneMat fields and map to the existing model.genes field
-0603 if isfield(model,'grRules')
-0604     [genes, rxnGeneMat] = getGenesFromGrRules(model.grRules);
-0605     model.rxnGeneMat = sparse(numel(model.rxns),numel(model.genes));
-0606     [~,geneOrder] = ismember(genes,model.genes);
-0607     if any(geneOrder == 0)
-0608         error(['The grRules includes the following gene(s), that are not in '...
-0609             'the list of model genes: ', genes{~geneOrder}])
-0610     end
-0611     model.rxnGeneMat(:,geneOrder) = rxnGeneMat;
-0612 end
-0613 
-0614 % Finalize GECKO model
-0615 if isGECKO
-0616     % Fill in empty fields and empty entries
-0617     for i={'kcat','source','notes','eccodes'} % Even keep empty
-0618         model.ec = emptyOrFill(model.ec,i{1},{''},'rxns',true);
-0619     end
-0620     for i={'enzymes','mw','sequence'}
-0621         model.ec = emptyOrFill(model.ec,i{1},{''},'genes',true);
-0622     end
-0623     model.ec = emptyOrFill(model.ec,'concs',{'NaN'},'genes',true);
-0624     model.ec = emptyOrFill(model.ec,'kcat',{'0'},'genes',true);
-0625     % Change string to double
-0626     for i={'kcat','mw','concs'}
-0627         if isfield(model.ec,i{1})
-0628             model.ec.(i{1}) = str2double(model.ec.(i{1}));
-0629         end
-0630     end
-0631     % Fill rxnEnzMat
-0632     rxnIdx              = cellfun('isempty', enzStoich(:,1));
-0633     enzStoich(rxnIdx,:) = '';
-0634     rxnIdx              = cell2mat(enzStoich(:,1));
-0635     [~,enzIdx]          = ismember(enzStoich(:,2),model.ec.enzymes);
-0636     coeffs              = cell2mat(enzStoich(:,3));
-0637     model.ec.rxnEnzMat  = zeros(numel(model.ec.rxns), numel(model.ec.genes));
-0638     linearIndices       = sub2ind([numel(model.ec.rxns), numel(model.ec.genes)], rxnIdx, enzIdx);
-0639     model.ec.rxnEnzMat(linearIndices) = coeffs;
-0640     %Parse ec-codes
-0641     if ~isempty(ecGecko)
-0642         locs = cell2mat(ecGecko(:,1));
-0643         for i=unique(locs)'
-0644             ecGeckoCat=strjoin(ecGecko(locs==i,2),';');
-0645             model.ec.eccodes{i,1}=ecGeckoCat;
-0646         end
-0647         emptyEc=cellfun('isempty',model.ec.eccodes);
-0648         model.ec.eccodes(emptyEc)={''};
-0649     end
-0650 end
-0651 
-0652 if verbose
-0653     fprintf(' Done!\n');
-0654 end
-0655 end
-0656 
-0657 function model = emptyOrFill(model,field,emptyEntry,type,keepEmpty)
-0658 if nargin<5
-0659     keepEmpty=false;
-0660 end
-0661 if isnumeric(emptyEntry)
-0662     emptyCells=isempty(model.(field));
-0663 else
-0664     emptyCells=cellfun('isempty',model.(field));
-0665 end
-0666 if all(emptyCells) && ~keepEmpty
-0667     model = rmfield(model, field);
-0668 elseif numel(model.(field))<numel(model.(type))
-0669     model.(field)(end+1:numel(model.(type)),1)=emptyEntry;
-0670 end
-0671 end
-0672 
-0673 function model = readFieldValue(model, fieldName, value, pos)
-0674 if numel(model.(fieldName))<pos-1
-0675     model.(fieldName)(end+1:pos,1) = {''};
-0676 end
-0677 model.(fieldName)(pos,1) = {value};
-0678 end
-0679 
-0680 function [miriams,miriamKey,entryNumber] = gatherAnnotation(pos,miriams,key,value,miriamKey,entryNumber)
-0681 if isempty(key)
-0682     key=miriamKey;
-0683 else
-0684     miriamKey=key;
-0685 end
-0686 if ~isempty(value)
-0687     miriams(entryNumber,1:3) = {pos, key, strip(value)};
-0688     entryNumber = entryNumber + 1;
-0689 end
-0690 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/io/sortIdentifiers.html b/doc/io/sortIdentifiers.html deleted file mode 100644 index 1198cb318..000000000 --- a/doc/io/sortIdentifiers.html +++ /dev/null @@ -1,83 +0,0 @@ - - - - Description of sortIdentifiers - - - - - - - - - -
Home > io > sortIdentifiers.m
- - - -

sortIdentifiers -

- -

PURPOSE ^

-
exportModel
- -

SYNOPSIS ^

-
function newModel = sortIdentifiers(model)
- -

DESCRIPTION ^

-
 exportModel
-   Sort reactions, metabolites, genes and compartments alphabetically by
-   their identifier.
-
-   Input:
-   model       a model structure
-
-   Output:
-   newModel    an updated model structure with alphabetically sorted
-               identifiers
-
- Usage: newModel=sortIdentifiers(model)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function newModel = sortIdentifiers(model)
-0002 % exportModel
-0003 %   Sort reactions, metabolites, genes and compartments alphabetically by
-0004 %   their identifier.
-0005 %
-0006 %   Input:
-0007 %   model       a model structure
-0008 %
-0009 %   Output:
-0010 %   newModel    an updated model structure with alphabetically sorted
-0011 %               identifiers
-0012 %
-0013 % Usage: newModel=sortIdentifiers(model)
-0014 
-0015 [~,I]=sort(model.rxns);
-0016 newModel=permuteModel(model,I,'rxns');
-0017 [~,I]=sort(newModel.mets);
-0018 newModel=permuteModel(newModel,I,'mets');
-0019 if isfield(newModel,'genes')
-0020     [~,I]=sort(newModel.genes);
-0021     newModel=permuteModel(newModel,I,'genes');
-0022 end
-0023 [~,I]=sort(newModel.comps);
-0024 newModel=permuteModel(newModel,I,'comps');
-0025 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/io/startup.html b/doc/io/startup.html deleted file mode 100644 index 1f8c31159..000000000 --- a/doc/io/startup.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - Description of startup - - - - - - - - - -
Home > io > startup.m
- - - -

startup -

- -

PURPOSE ^

-
Add the Java Paths at startup in order to be ready for use if the Toolbox is on the path
- -

SYNOPSIS ^

-
This is a script file.
- -

DESCRIPTION ^

-
Add the Java Paths at startup in order to be ready for use if the Toolbox is on the path
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 %Add the Java Paths at startup in order to be ready for use if the Toolbox is on the path
-0002 addJavaPaths()
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/io/writeSheet.html b/doc/io/writeSheet.html deleted file mode 100644 index 049b90ffb..000000000 --- a/doc/io/writeSheet.html +++ /dev/null @@ -1,211 +0,0 @@ - - - - Description of writeSheet - - - - - - - - - -
Home > io > writeSheet.m
- - - -

writeSheet -

- -

PURPOSE ^

-
writeSheet
- -

SYNOPSIS ^

-
function wb=writeSheet(wb,sheetName,sheetPosition,captions,units,raw,isIntegers)
- -

DESCRIPTION ^

-
 writeSheet
-   Writes a cell matrix to an Excel sheet into using the Java library Apache POI
-
-   workbook        Workbook object representing the Excel file
-   sheetName       name of the sheet
-   sheetPosition   0-based position of the sheet
-   captions        cell array of captions (optional)
-   units           WRITE INFO
-   raw             cell array with the data in the sheet
-   isIntegers      true if numeric values should be integers (optional, default
-                   true)
-
- Usage: wb=writeSheet(wb,sheetName,sheetPosition,captions,units,raw)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 function wb=writeSheet(wb,sheetName,sheetPosition,captions,units,raw,isIntegers)
-0002 % writeSheet
-0003 %   Writes a cell matrix to an Excel sheet into using the Java library Apache POI
-0004 %
-0005 %   workbook        Workbook object representing the Excel file
-0006 %   sheetName       name of the sheet
-0007 %   sheetPosition   0-based position of the sheet
-0008 %   captions        cell array of captions (optional)
-0009 %   units           WRITE INFO
-0010 %   raw             cell array with the data in the sheet
-0011 %   isIntegers      true if numeric values should be integers (optional, default
-0012 %                   true)
-0013 %
-0014 % Usage: wb=writeSheet(wb,sheetName,sheetPosition,captions,units,raw)
-0015 
-0016 if nargin<7
-0017     isIntegers=true;
-0018 end
-0019 
-0020 %Adds the required classes to the static Java path if not already added
-0021 addJavaPaths();
-0022 
-0023 %Import required classes from Apache POI.
-0024 import org.apache.poi.ss.usermodel.*;
-0025 import org.apache.poi.ss.util.*;
-0026 import org.apache.poi.hssf.usermodel.*;
-0027 import org.apache.poi.xssf.usermodel.*;
-0028 
-0029 %Set default style object and bold style object
-0030 defaultStyle = wb.createCellStyle();
-0031 if isIntegers
-0032     idx = wb.getCreationHelper().createDataFormat().getFormat('0');
-0033 else
-0034     idx = wb.getCreationHelper().createDataFormat().getFormat('##0.00');
-0035 end
-0036 defaultStyle.setDataFormat(idx);
-0037 
-0038 boldFont=wb.createFont();
-0039 boldFont.setBoldweight(boldFont.BOLDWEIGHT_BOLD);
-0040 boldStyle=defaultStyle.clone();
-0041 boldStyle.setFont(boldFont);
-0042 
-0043 s=wb.createSheet();
-0044 wb.setSheetName(sheetPosition, sheetName);
-0045 
-0046 %Create the header row and units
-0047 counter=0;
-0048 if ~isempty(captions)
-0049     r=s.createRow(counter);
-0050     for i=0:numel(captions)-1
-0051         c=r.createCell(i);
-0052         c.setCellValue(captions{i+1});
-0053         c.setCellStyle(boldStyle);
-0054     end
-0055     counter=counter+1;
-0056 end
-0057 if ~isempty(units)
-0058     r=s.createRow(counter);
-0059     for i=0:numel(units)-1
-0060         c=r.createCell(i);
-0061         content=units{i+1};
-0062         if iscell(content) && numel(content)==2
-0063             c.setCellValue(content{1});
-0064             
-0065             %This means that the cell should have a list of allowed values
-0066             dvHelper=XSSFDataValidationHelper(s);
-0067             
-0068             cellRange=CellRangeAddressList(1,1,i,i); %Units are on the second line
-0069             dvConstraint=dvHelper.createExplicitListConstraint(toValid(content{2}));
-0070             validation=dvHelper.createValidation(dvConstraint, cellRange);
-0071             validation.setShowErrorBox(true);
-0072             s.addValidationData(validation);
-0073         else
-0074             c.setCellValue(content{1});
-0075         end
-0076         c.setCellStyle(boldStyle);
-0077     end
-0078     counter=counter+1;
-0079 end
-0080 
-0081 %Loop through and fill in the values
-0082 for i=0:size(raw,1)-1
-0083     r=s.createRow(i+counter);
-0084     
-0085     for j=0:size(raw,2)-1
-0086         if ~isempty(raw{i+1,j+1})
-0087             c=r.createCell(j);
-0088             content=raw{i+1,j+1};
-0089             if iscell(content) && numel(content)==2
-0090                 c.setCellValue(content{1});
-0091                 
-0092                 %This means that the cell should have a list of allowed
-0093                 %values
-0094                 dvHelper=XSSFDataValidationHelper(s);
-0095                 cellRange=CellRangeAddressList(i+1,i+1,j,j);
-0096                 dvConstraint=dvHelper.createExplicitListConstraint(toValid(content{2}));
-0097                 validation=dvHelper.createValidation(dvConstraint, cellRange);
-0098                 validation.setShowErrorBox(true);
-0099                 s.addValidationData(validation);
-0100             else
-0101                 c.setCellValue(content);
-0102             end
-0103             c.setCellStyle(defaultStyle);
-0104         end
-0105     end
-0106 end
-0107 
-0108 %Pre-determine column widths for each sheet
-0109 if strcmp(sheetName,'RXNS')
-0110     widths=[786;2358;7860;15719;3406;7860;3406;3406;2358;3406;7860;7860;3668;7860;7860;4192];
-0111 elseif strcmp(sheetName,'METS')
-0112     widths=[786;7860;7860;3668;7860;7860;7860;3406;3668;1834];
-0113 elseif strcmp(sheetName,'COMPS')
-0114     widths=[786;3144;7860;3144;7860];
-0115 elseif strcmp(sheetName,'GENES')
-0116     widths=[786;3144;7860;3144;3406];
-0117 elseif strcmp(sheetName,'MODEL')
-0118     widths=[786;3144;7860;3668;3668;5240;5240;7860;7860;2620;7860];
-0119 end;
-0120 
-0121 %Resize columns
-0122 for i=0:size(raw,2)-1
-0123     s.setColumnWidth(i,widths(i+1));
-0124 end
-0125 
-0126 %Add freeze panes
-0127 if counter>0
-0128     s.createFreezePane(0,counter,0,counter);
-0129 end
-0130 end
-0131 
-0132 function I=toValid(J)
-0133 I=cell(numel(J),1);
-0134 for i=1:numel(J)
-0135     if ischar(J{i})
-0136         I(i)=J(i);
-0137     else
-0138         if islogical(J{i})
-0139             if J{i}==true
-0140                 I{i}='TRUE';
-0141             else
-0142                 I{i}='FALSE';
-0143             end
-0144         else
-0145             %Other, most likely numbers
-0146             I{i}=num2str(J{i});
-0147         end
-0148     end
-0149 end
-0150 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/io/writeYAMLmodel.html b/doc/io/writeYAMLmodel.html deleted file mode 100644 index e41204160..000000000 --- a/doc/io/writeYAMLmodel.html +++ /dev/null @@ -1,448 +0,0 @@ - - - - Description of writeYAMLmodel - - - - - - - - - -
Home > io > writeYAMLmodel.m
- - - -

writeYAMLmodel -

- -

PURPOSE ^

-
writeYAMLmodel
- -

SYNOPSIS ^

-
function writeYAMLmodel(model,fileName,preserveQuotes,sortIds)
- -

DESCRIPTION ^

-
 writeYAMLmodel
-   Writes a yaml file matching (roughly) the cobrapy yaml structure
-
-   model           a model structure
-   fileName        name that the file will have.  A dialog window will 
-                   open if no file name is specified.
-   preserveQuotes  if quotes should be preserved for strings
-                   (logical, default=true)
-   sortIds         if metabolites, reactions, genes and compartments
-                   should be sorted alphabetically by their identifier,
-                   otherwise they are kept in their original order
-                   (logical, default=false)   
-
- Usage: writeYAMLmodel(model,fileName,preserveQuotes,sortIds)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 function writeYAMLmodel(model,fileName,preserveQuotes,sortIds)
-0002 % writeYAMLmodel
-0003 %   Writes a yaml file matching (roughly) the cobrapy yaml structure
-0004 %
-0005 %   model           a model structure
-0006 %   fileName        name that the file will have.  A dialog window will
-0007 %                   open if no file name is specified.
-0008 %   preserveQuotes  if quotes should be preserved for strings
-0009 %                   (logical, default=true)
-0010 %   sortIds         if metabolites, reactions, genes and compartments
-0011 %                   should be sorted alphabetically by their identifier,
-0012 %                   otherwise they are kept in their original order
-0013 %                   (logical, default=false)
-0014 %
-0015 % Usage: writeYAMLmodel(model,fileName,preserveQuotes,sortIds)
-0016 if nargin<2|| isempty(fileName)
-0017     [fileName, pathName] = uiputfile({'*.yml;*.yaml'}, 'Select file for model export',[model.id '.yml']);
-0018     if fileName == 0
-0019         error('You should provide a file location')
-0020     else
-0021         fileName = fullfile(pathName,fileName);
-0022     end
-0023 end
-0024 fileName=char(fileName);
-0025 
-0026 if nargin < 3
-0027     preserveQuotes = true;
-0028 end
-0029 if nargin < 4
-0030     sortIds = false;
-0031 end
-0032 if ~endsWith(fileName,{'.yml','.yaml'})
-0033     fileName = strcat(fileName,'.yml');
-0034 end
-0035 
-0036 %Check that model is in RAVEN format:
-0037 if isfield(model,'rules')
-0038     model = ravenCobraWrapper(model);
-0039 end
-0040 
-0041 %Check that the model structure has no problems
-0042 checkModelStruct(model);
-0043 
-0044 %Sort identifiers alphabetically
-0045 if sortIds == true
-0046     model = sortIdentifiers(model);
-0047 end
-0048 
-0049 %Simplify Miriam fields:
-0050 if isfield(model,'metMiriams')
-0051     [model.newMetMiriams,model.newMetMiriamNames]   = extractMiriam(model.metMiriams);
-0052 end
-0053 if isfield(model,'rxnMiriams')
-0054     [model.newRxnMiriams,model.newRxnMiriamNames]   = extractMiriam(model.rxnMiriams);
-0055 end
-0056 if isfield(model,'geneMiriams')
-0057     [model.newGeneMiriams,model.newGeneMiriamNames] = extractMiriam(model.geneMiriams);
-0058 end
-0059 if isfield(model,'compMiriams')
-0060     [model.newCompMiriams,model.newCompMiriamNames] = extractMiriam(model.compMiriams);
-0061 end
-0062 
-0063 %Open file:
-0064 fid = fopen(fileName,'wt');
-0065 if fid == -1
-0066     error(['Cannot write to ' fileName ', does the directory exist?'])
-0067 end
-0068 fprintf(fid,'---\n!!omap\n');
-0069 
-0070 %Insert file header (metadata)
-0071 writeMetadata(model,fid);
-0072 
-0073 %Metabolites:
-0074 fprintf(fid,'- metabolites:\n');
-0075 for i = 1:length(model.mets)
-0076     fprintf(fid,'    - !!omap\n');
-0077     writeField(model, fid, 'mets',        'txt', i, '  - id',          preserveQuotes)
-0078     writeField(model, fid, 'metNames',    'txt', i, '  - name',        preserveQuotes)
-0079     writeField(model, fid, 'metComps',    'txt', i, '  - compartment', preserveQuotes)
-0080     writeField(model, fid, 'metFormulas', 'txt', i, '  - formula',     preserveQuotes)
-0081     writeField(model, fid, 'metCharges',  'num', i, '  - charge',      preserveQuotes)
-0082     writeField(model, fid, 'inchis',      'txt', i, '  - inchis',      preserveQuotes)
-0083     writeField(model, fid, 'metSmiles',   'txt', i, '  - smiles',      preserveQuotes)
-0084     writeField(model, fid, 'metMiriams',  'txt', i, '  - annotation',  preserveQuotes)
-0085     writeField(model, fid, 'metDeltaG',   'num', i, '  - deltaG',      preserveQuotes)
-0086     writeField(model, fid, 'metNotes',    'txt', i, '  - notes',       preserveQuotes)
-0087     writeField(model, fid, 'metFrom',     'txt', i, '  - metFrom',     preserveQuotes)
-0088 end
-0089 
-0090 %Reactions:
-0091 fprintf(fid,'- reactions:\n');
-0092 for i = 1:length(model.rxns)
-0093     fprintf(fid,'    - !!omap\n');
-0094     writeField(model, fid, 'rxns',                 'txt', i, '  - id',                    preserveQuotes)
-0095     writeField(model, fid, 'rxnNames',             'txt', i, '  - name',                  preserveQuotes)
-0096     writeField(model, fid, 'S',                    'txt', i, '  - metabolites',           preserveQuotes)
-0097     writeField(model, fid, 'lb',                   'num', i, '  - lower_bound',           preserveQuotes)
-0098     writeField(model, fid, 'ub',                   'num', i, '  - upper_bound',           preserveQuotes)
-0099     writeField(model, fid, 'grRules',              'txt', i, '  - gene_reaction_rule',    preserveQuotes)
-0100     writeField(model, fid, 'rxnFrom',              'txt', i, '  - rxnFrom',               preserveQuotes)
-0101     if model.c(i)~=0
-0102         writeField(model, fid, 'c',                    'num', i, '  - objective_coefficient', preserveQuotes)    
-0103     end
-0104     writeField(model, fid, 'eccodes',              'txt', i, '  - eccodes',               preserveQuotes)
-0105     writeField(model, fid, 'rxnReferences',        'txt', i, '  - references',            preserveQuotes)
-0106     writeField(model, fid, 'subSystems',           'txt', i, '  - subsystem',             preserveQuotes)
-0107     writeField(model, fid, 'rxnMiriams',           'txt', i, '  - annotation',            preserveQuotes)
-0108     writeField(model, fid, 'rxnDeltaG',            'num', i, '  - deltaG',                preserveQuotes)
-0109     writeField(model, fid, 'rxnConfidenceScores',  'num', i, '  - confidence_score',      preserveQuotes)
-0110     writeField(model, fid, 'rxnNotes',             'txt', i, '  - rxnNotes',              preserveQuotes)
-0111 end
-0112 
-0113 %Genes:
-0114 if isfield(model,'genes')
-0115     fprintf(fid,'- genes:\n');
-0116     for i = 1:length(model.genes)
-0117         fprintf(fid,'    - !!omap\n');
-0118         writeField(model, fid, 'genes',          'txt', i, '  - id',         preserveQuotes)
-0119         writeField(model, fid, 'geneShortNames', 'txt', i, '  - name',       preserveQuotes)
-0120         writeField(model, fid, 'proteins',   'txt', i, '  - protein',    preserveQuotes)
-0121         writeField(model, fid, 'geneMiriams',    'txt', i, '  - annotation', preserveQuotes)
-0122     end
-0123 end
-0124 
-0125 %Compartments:
-0126 fprintf(fid,'- compartments: !!omap\n');
-0127 for i = 1:length(model.comps)
-0128     writeField(model, fid, 'compNames',   'txt', i, ['- ' model.comps{i}], preserveQuotes)
-0129     writeField(model, fid, 'compMiriams', 'txt', i, '- annotation',             preserveQuotes)
-0130 end
-0131 
-0132 
-0133 %EC-model:
-0134 if isfield(model,'ec')
-0135     fprintf(fid,'- ec-rxns:\n');
-0136     for i = 1:length(model.ec.rxns)
-0137         fprintf(fid,'  - !!omap\n');
-0138         writeField(model.ec, fid, 'rxns',      'txt', i, '- id',      preserveQuotes)
-0139         writeField(model.ec, fid, 'kcat',      'num', i, '- kcat',    preserveQuotes)
-0140         writeField(model.ec, fid, 'source',    'txt', i, '- source',  preserveQuotes)
-0141         writeField(model.ec, fid, 'notes',     'txt', i, '- notes',   preserveQuotes)
-0142         writeField(model.ec, fid, 'eccodes',   'txt', i, '- eccodes', preserveQuotes)
-0143         writeField(model.ec, fid, 'rxnEnzMat', 'txt', i, '- enzymes', preserveQuotes)
-0144     end
-0145 
-0146     fprintf(fid,'- ec-enzymes:\n');
-0147     for i = 1:length(model.ec.genes)
-0148         fprintf(fid,'  - !!omap\n');
-0149         writeField(model.ec, fid, 'genes',    'txt', i, '- genes',    preserveQuotes)
-0150         writeField(model.ec, fid, 'enzymes',  'txt', i, '- enzymes',  preserveQuotes)
-0151         writeField(model.ec, fid, 'mw',       'num', i, '- mw',       preserveQuotes)
-0152         writeField(model.ec, fid, 'sequence', 'txt', i, '- sequence', preserveQuotes)
-0153         writeField(model.ec, fid, 'concs',    'num', i, '- concs',    preserveQuotes)
-0154     end
-0155 end
-0156 
-0157 %Close file:
-0158 fclose(fid);
-0159 
-0160 end
-0161 
-0162 function writeField(model,fid,fieldName,type,pos,name,preserveQuotes)
-0163 %Writes a new line in the yaml file if the field exists and the field is
-0164 %not empty at the correspoinding position. It's recursive for some fields
-0165 %(metMiriams, rxnMiriams, and S)
-0166 
-0167 if isfield(model,fieldName)
-0168     if strcmp(fieldName,'metComps')
-0169         %metComps: write full name
-0170         fieldName = 'comps';
-0171         pos       = model.metComps(pos);
-0172     end
-0173     
-0174     field = model.(fieldName);
-0175     
-0176     if strcmp(fieldName,'metMiriams')
-0177         if ~isempty(model.metMiriams{pos})
-0178             fprintf(fid,'    %s: !!omap\n',name);
-0179             for i=1:size(model.newMetMiriams,2)
-0180                 %'i' represents the different miriam names, e.g.
-0181                 %kegg.compound or chebi
-0182                 if ~isempty(model.newMetMiriams{pos,i})
-0183                     %As during the following writeField call the value of
-0184                     %'i' would be lost, it is temporarily concatenated to
-0185                     %'name' parameter, which will be edited later
-0186                     writeField(model, fid, 'newMetMiriams', 'txt', pos, ['      - ' model.newMetMiriamNames{i} '_' sprintf('%d',i)], preserveQuotes)
-0187                 end
-0188             end
-0189         end
-0190         
-0191     elseif strcmp(fieldName,'rxnMiriams')
-0192         if ~isempty(model.rxnMiriams{pos})
-0193             fprintf(fid,'    %s: !!omap\n',name);
-0194             for i=1:size(model.newRxnMiriams,2)
-0195                 if ~isempty(model.newRxnMiriams{pos,i})
-0196                     writeField(model, fid, 'newRxnMiriams', 'txt', pos, ['      - ' model.newRxnMiriamNames{i} '_' sprintf('%d',i)], preserveQuotes)
-0197                 end
-0198             end
-0199         end
-0200         
-0201     elseif strcmp(fieldName,'geneMiriams')
-0202         if ~isempty(model.geneMiriams{pos})
-0203             fprintf(fid,'    %s: !!omap\n',name);
-0204             for i=1:size(model.newGeneMiriams,2)
-0205                 if ~isempty(model.newGeneMiriams{pos,i})
-0206                     writeField(model, fid, 'newGeneMiriams', 'txt', pos, ['      - ' model.newGeneMiriamNames{i} '_' sprintf('%d',i)], preserveQuotes)
-0207                 end
-0208             end
-0209         end
-0210         
-0211     elseif strcmp(fieldName,'compMiriams')
-0212         if ~isempty(model.compMiriams{pos})
-0213             fprintf(fid,'    %s: !!omap\n',name);
-0214             for i=1:size(model.newCompMiriams,2)
-0215                 if ~isempty(model.newCompMiriams{pos,i})
-0216                     writeField(model, fid, 'newCompMiriams', 'txt', pos, ['      - ' model.newCompMiriamNames{i} '_' sprintf('%d',i)], preserveQuotes)
-0217                 end
-0218             end
-0219         end
-0220         
-0221     elseif strcmp(fieldName,'S')
-0222         %S: create header & write each metabolite in a new line
-0223         fprintf(fid,'    %s: !!omap\n',name);
-0224         if sum(field(:,pos) ~= 0) > 0
-0225             model.mets   = model.mets(field(:,pos) ~= 0);
-0226             model.coeffs = field(field(:,pos) ~= 0,pos);
-0227             %Sort metabolites:
-0228             [model.mets,order] = sort(model.mets);
-0229             model.coeffs       = model.coeffs(order);
-0230             for i = 1:length(model.mets)
-0231                 writeField(model, fid, 'coeffs',  'num', i, ['      - ' model.mets{i}], preserveQuotes)
-0232             end
-0233         end
-0234 
-0235     elseif strcmp(fieldName,'rxnEnzMat')
-0236         %S: create header & write each enzyme in a new line
-0237         fprintf(fid,'    %s: !!omap\n',name);
-0238         if sum(field(pos,:) ~= 0) > 0
-0239             model.enzymes = model.enzymes(field(pos,:) ~= 0);
-0240             model.coeffs  = field(pos,field(pos,:) ~= 0);
-0241             %Sort metabolites:
-0242             [model.enzymes,order] = sort(model.enzymes);
-0243             model.coeffs          = model.coeffs(order);
-0244             for i = 1:length(model.enzymes)
-0245                 writeField(model, fid, 'coeffs',  'num', i, ['    - ' model.enzymes{i}], preserveQuotes)
-0246             end
-0247         end        
-0248 
-0249     elseif sum(strcmp({'subSystems','newMetMiriams','newRxnMiriams','newGeneMiriams','newCompMiriams','eccodes'},fieldName)) > 0
-0250         %eccodes/rxnNotes: if 1 write in 1 line, if more create header and list
-0251         if strcmp(fieldName,'subSystems')
-0252             list = field{pos};  %subSystems already comes in a cell array
-0253             if isempty(list)
-0254                 return
-0255             end
-0256         elseif strcmp(fieldName,'newMetMiriams')
-0257             index = str2double(regexprep(name,'^.+_',''));
-0258             name  = regexprep(name,'_\d+$','');
-0259             list = strsplit(model.newMetMiriams{pos,index},'; ');
-0260         elseif strcmp(fieldName,'newRxnMiriams')
-0261             index = str2double(regexprep(name,'^.+_',''));
-0262             name  = regexprep(name,'_\d+$','');
-0263             list = strsplit(model.newRxnMiriams{pos,index},'; ');
-0264         elseif strcmp(fieldName,'newGeneMiriams')
-0265             index = str2double(regexprep(name,'^.+_',''));
-0266             name  = regexprep(name,'_\d+$','');
-0267             list = strsplit(model.newGeneMiriams{pos,index},'; ');
-0268         elseif strcmp(fieldName,'newCompMiriams')
-0269             index = str2double(regexprep(name,'^.+_',''));
-0270             name  = regexprep(name,'_\d+$','');
-0271             list = strsplit(model.newCompMiriams{pos,index},'; ');
-0272         elseif ~isempty(field{pos})
-0273             list = strrep(field{pos},' ','');
-0274             list = strsplit(list,';');
-0275         else
-0276             return % empty, needs no line in file
-0277         end
-0278         list=strip(list);
-0279 
-0280         if length(list) == 1 && ~strcmp(list{1},'') && ~strcmp(fieldName,'subSystems')
-0281             if preserveQuotes
-0282                 list = ['"' list{1} '"'];
-0283             end
-0284             if iscell(list)
-0285                 list=list{1};
-0286             end
-0287             fprintf(fid,'    %s: %s\n',name,list);
-0288         elseif ischar(list) && strcmp(fieldName,'subSystems')
-0289             if preserveQuotes
-0290                 list = ['"' list '"'];
-0291             end
-0292             fprintf(fid,'    %s: %s\n',name,list);            
-0293         elseif length(list) > 1 || strcmp(fieldName,'subSystems')
-0294             if preserveQuotes
-0295                 for j=1:numel(list)
-0296                     list{j} = ['"' list{j} '"'];
-0297                 end
-0298             end
-0299             fprintf(fid,'    %s:\n',name);
-0300             for i = 1:length(list)
-0301                 fprintf(fid,'%s        - %s\n',regexprep(name,'(^\s*).*','$1'),list{i});
-0302             end
-0303         end
-0304         
-0305     elseif sum(pos) > 0
-0306         %All other fields:
-0307         if strcmp(type,'txt')
-0308             value = field{pos};
-0309             if preserveQuotes && ~isempty(value)
-0310                 value = ['"',value,'"'];
-0311             end
-0312         elseif strcmp(type,'num')
-0313             if isnan(field(pos))
-0314                 value = [];
-0315             else
-0316                 value = sprintf('%.15g',full(field(pos)));
-0317             end
-0318         end
-0319         if ~isempty(value)
-0320             fprintf(fid,'    %s: %s\n',name,value);
-0321         end
-0322     end
-0323 end
-0324 end
-0325 
-0326 function writeMetadata(model,fid)
-0327 % Writes model metadata to the yaml file. This information will eventually
-0328 % be extracted entirely from the model, but for now, many of the entries
-0329 % are hard-coded defaults for HumanGEM.
-0330 
-0331 fprintf(fid, '- metaData:\n');
-0332 if isfield(model,'id')
-0333     fprintf(fid, '    id: "%s"\n',  model.id);
-0334 else
-0335     fprintf(fid, '    id: "blankID"\n');
-0336 end
-0337 if isfield(model,'name')
-0338     fprintf(fid, '    name: "%s"\n',model.name);
-0339 else
-0340     fprintf(fid, '    name: "blankName"\n');
-0341 end
-0342 if isfield(model,'version')
-0343     fprintf(fid, '    version: "%s"\n',model.version);
-0344 end
-0345 fprintf(fid, '    date: "%s"\n',datestr(now,29));  % 29=YYYY-MM-DD
-0346 if isfield(model,'annotation')
-0347     if isfield(model.annotation,'defaultLB')
-0348         fprintf(fid, '    defaultLB: "%g"\n',   model.annotation.defaultLB);
-0349     end
-0350     if isfield(model.annotation,'defaultUB')
-0351         fprintf(fid, '    defaultUB: "%g"\n',   model.annotation.defaultUB);
-0352     end
-0353     if isfield(model.annotation,'givenName')
-0354         fprintf(fid, '    givenName: "%s"\n',   model.annotation.givenName);
-0355     end
-0356     if isfield(model.annotation,'familyName')
-0357         fprintf(fid, '    familyName: "%s"\n',  model.annotation.familyName);
-0358     end
-0359     if isfield(model.annotation,'authors')
-0360         fprintf(fid, '    authors: "%s"\n',     model.annotation.authors);
-0361     end
-0362     if isfield(model.annotation,'email')
-0363         fprintf(fid, '    email: "%s"\n',       model.annotation.email);
-0364     end
-0365     if isfield(model.annotation,'organization')
-0366         fprintf(fid, '    organization: "%s"\n',model.annotation.organization);
-0367     end
-0368     if isfield(model.annotation,'taxonomy')
-0369         fprintf(fid, '    taxonomy: "%s"\n',    model.annotation.taxonomy);
-0370     end
-0371     if isfield(model.annotation,'note')
-0372         fprintf(fid, '    note: "%s"\n',        model.annotation.note);
-0373     end
-0374     if isfield(model.annotation,'sourceUrl')
-0375         fprintf(fid, '    sourceUrl: "%s"\n',   model.annotation.sourceUrl);
-0376     end
-0377 end
-0378 if isfield(model,'ec')
-0379     if model.ec.geckoLight
-0380         geckoLight = 'true';
-0381     else
-0382         geckoLight = 'false';
-0383     end
-0384     fprintf(fid,'    geckoLight: "%s"\n',geckoLight);
-0385 end
-0386 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/left.png b/doc/left.png deleted file mode 100644 index 404df045f40970496c71ca6b8c1f1357af271e27..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 136 zcmeAS@N?(olHy`uVBq!ia0vp^{2}w1qqB3TN5VEvJYV8 a;bDlI$G>{!EB$9cJq(_%elF{r5}E)JM - - - Description of changeGeneAssoc - - - - - - - - - -
Home > legacy > core > changeGeneAssoc.m
- - - -

changeGeneAssoc -

- -

PURPOSE ^

-
changeGeneAssoc
- -

SYNOPSIS ^

-
function model = changeGeneAssoc(model,rxnID,geneAssoc,replace)
- -

DESCRIPTION ^

-
 changeGeneAssoc
-   Changes gene association for a defined reaction
-
-   model       a model structure to change the gene association
-   rxnID       string or cell array of reaction IDs
-   geneAssoc   string of additional or replacement gene association.
-               Should be written with ' and ' to indicate subunits, ' or '
-               to indicate isoenzymes, and brackets '()' to separate
-               different instances
-   replace     true if old gene association should be replaced with new
-               association. False if new gene association should be
-               concatenated to the old association (optional, default true)
-
-   model       an updated model structure
-
- Usage: changeGeneAssoc(model,rxnID,geneAssoc,replace)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function model = changeGeneAssoc(model,rxnID,geneAssoc,replace)
-0002 % changeGeneAssoc
-0003 %   Changes gene association for a defined reaction
-0004 %
-0005 %   model       a model structure to change the gene association
-0006 %   rxnID       string or cell array of reaction IDs
-0007 %   geneAssoc   string of additional or replacement gene association.
-0008 %               Should be written with ' and ' to indicate subunits, ' or '
-0009 %               to indicate isoenzymes, and brackets '()' to separate
-0010 %               different instances
-0011 %   replace     true if old gene association should be replaced with new
-0012 %               association. False if new gene association should be
-0013 %               concatenated to the old association (optional, default true)
-0014 %
-0015 %   model       an updated model structure
-0016 %
-0017 % Usage: changeGeneAssoc(model,rxnID,geneAssoc,replace)
-0018 
-0019 if nargin==3
-0020     replace=true;
-0021 end
-0022 
-0023 if isstr(rxnID)
-0024     rxnID={rxnID};
-0025 end
-0026 
-0027 if ~isstr(geneAssoc)
-0028     EM='geneAssoc has to be string';
-0029     error(sprintf(EM))
-0030 end
-0031 
-0032 
-0033 % Add genes to model
-0034 geneList=transpose(cell(unique(regexp(geneAssoc,'[)(]*|( and )*|( or )*','split')))); % Extract individual, unique genes from the geneAssoc provided
-0035 geneList=geneList(~cellfun(@isempty, geneList));
-0036 genesToAdd.genes=setdiff(geneList,model.genes); % Only keep the genes that are not yet part of the model.genes.
-0037 if ~isempty(genesToAdd.genes)
-0038     model=addGenesRaven(model,genesToAdd); % Add genes
-0039 end
-0040 
-0041 % Find reaction and gene indices
-0042 idx=getIndexes(model,rxnID,'rxns');
-0043 
-0044 % Change gene associations
-0045 if replace==true % Replace old gene associations
-0046     model.grRules(idx)=cellstr(geneAssoc);
-0047 else % Add gene associations, add new gene rules after 'OR'.
-0048     model.grRules(idx)=cellstr('(',[model.grRules{idx},') or (',geneAssoc,')']);
-0049 end
-0050 
-0051 %Fix grRules and reconstruct rxnGeneMat
-0052 [grRules,rxnGeneMat] = standardizeGrRules(model,true);
-0053 model.grRules = grRules;
-0054 model.rxnGeneMat = rxnGeneMat;
-0055 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/legacy/core/index.html b/doc/legacy/core/index.html deleted file mode 100644 index 6ebe50eec..000000000 --- a/doc/legacy/core/index.html +++ /dev/null @@ -1,29 +0,0 @@ - - - - Index for Directory legacy\core - - - - - - - - - - -
< Master indexIndex for legacy\core >
- -

Index for legacy\core

- -

Matlab files in this directory:

- -
 changeGeneAssocchangeGeneAssoc
- - - - -
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/legacy/external/constructPathwayFromCelldesigner.html b/doc/legacy/external/constructPathwayFromCelldesigner.html deleted file mode 100644 index 0a25f26fe..000000000 --- a/doc/legacy/external/constructPathwayFromCelldesigner.html +++ /dev/null @@ -1,590 +0,0 @@ - - - - Description of constructPathwayFromCelldesigner - - - - - - - - - -
Home > legacy > external > constructPathwayFromCelldesigner.m
- - - -

constructPathwayFromCelldesigner -

- -

PURPOSE ^

-
constructPathwayFromCelldesigner
- -

SYNOPSIS ^

-
function pathway = constructPathwayFromCelldesigner(inputFile)
- -

DESCRIPTION ^

-
 constructPathwayFromCelldesigner
-    Constructs a pathway structure from a CellDesigner XML file.
-
-    inputFile   string representing the pathway of the Celldesigner XML 
-               file
-
-    pathway
-       listOfCompartments      structure with information on the compartments
-                               in the Celldesigner file
-           x                   the x position
-           y                   the y position
-           h                   the height
-           w                   the width
-           compartment         string representing the compartment
-           id                  alias of the compartment. Used if there are
-                               several instances of the same compartment
-           name                the name of the compartment
-       listOfSpecies           structure with information on each species in
-                               the Celldesigner file. Both metabolites and
-                               enzymes are species
-           x                   the x position
-           y                   the y position
-           h                   the height
-           w                   the width
-           species             string representing the species
-           alias               alias of the species. Used if the species is
-                               present in several places in the map
-           name                the name of the species
-           type                the type of the species. At the moment only
-                               'SIMPLE_MOLECULE' (for metabolites) and
-                               'PROTEIN' (for enzymes) are supported
-           note                string that can be used on enzymes to link them
-                               to the corresponding reaction in a model
-       listOfReactions         structure with information on each of the
-                               reactions in the Celldesigner file
-           reversible          true if the reaction is reversible
-           middlePoint         vector with the x and y points of the middle
-                               point of the reaction. All reactions are
-                               defines as having one reactant and one product.
-                               They may also have a number of modifiers (such
-                               as cofactors or enzymes). Each of these
-                               modifiers are drawn as being connected to the
-                               middle point. The middle point is calculated
-                               from the positions of the reactant and the
-                               product
-           componentList       structure with information on the reactant,
-                               product, and modifiers of the reaction
-               alias           string representing the alias of the
-                               species. Corresponds to the alias in
-                               listOfSpecies
-               species         string representing the species.
-                               Corresponds to the species in listOfSpecies
-               anchor          vector with the x and y points of the
-                               connecting point of the species
-               baseReaction    true if the species is the base reactant
-               baseProduct     true if the species is the base product
-               toArrow         true if the line connecting the species
-                               to the middle point should start with an
-                               arrow
-               fromArrow       true if the line connecting the species
-                               to the middle point should end with an
-                               arrow
-               type            'METABOLITE' or 'ENZYME'
-
-    Usage: pathway = constructPathwayFromCelldesigner(inputFile)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 function pathway = constructPathwayFromCelldesigner(inputFile)
-0002 % constructPathwayFromCelldesigner
-0003 %    Constructs a pathway structure from a CellDesigner XML file.
-0004 %
-0005 %    inputFile   string representing the pathway of the Celldesigner XML
-0006 %               file
-0007 %
-0008 %    pathway
-0009 %       listOfCompartments      structure with information on the compartments
-0010 %                               in the Celldesigner file
-0011 %           x                   the x position
-0012 %           y                   the y position
-0013 %           h                   the height
-0014 %           w                   the width
-0015 %           compartment         string representing the compartment
-0016 %           id                  alias of the compartment. Used if there are
-0017 %                               several instances of the same compartment
-0018 %           name                the name of the compartment
-0019 %       listOfSpecies           structure with information on each species in
-0020 %                               the Celldesigner file. Both metabolites and
-0021 %                               enzymes are species
-0022 %           x                   the x position
-0023 %           y                   the y position
-0024 %           h                   the height
-0025 %           w                   the width
-0026 %           species             string representing the species
-0027 %           alias               alias of the species. Used if the species is
-0028 %                               present in several places in the map
-0029 %           name                the name of the species
-0030 %           type                the type of the species. At the moment only
-0031 %                               'SIMPLE_MOLECULE' (for metabolites) and
-0032 %                               'PROTEIN' (for enzymes) are supported
-0033 %           note                string that can be used on enzymes to link them
-0034 %                               to the corresponding reaction in a model
-0035 %       listOfReactions         structure with information on each of the
-0036 %                               reactions in the Celldesigner file
-0037 %           reversible          true if the reaction is reversible
-0038 %           middlePoint         vector with the x and y points of the middle
-0039 %                               point of the reaction. All reactions are
-0040 %                               defines as having one reactant and one product.
-0041 %                               They may also have a number of modifiers (such
-0042 %                               as cofactors or enzymes). Each of these
-0043 %                               modifiers are drawn as being connected to the
-0044 %                               middle point. The middle point is calculated
-0045 %                               from the positions of the reactant and the
-0046 %                               product
-0047 %           componentList       structure with information on the reactant,
-0048 %                               product, and modifiers of the reaction
-0049 %               alias           string representing the alias of the
-0050 %                               species. Corresponds to the alias in
-0051 %                               listOfSpecies
-0052 %               species         string representing the species.
-0053 %                               Corresponds to the species in listOfSpecies
-0054 %               anchor          vector with the x and y points of the
-0055 %                               connecting point of the species
-0056 %               baseReaction    true if the species is the base reactant
-0057 %               baseProduct     true if the species is the base product
-0058 %               toArrow         true if the line connecting the species
-0059 %                               to the middle point should start with an
-0060 %                               arrow
-0061 %               fromArrow       true if the line connecting the species
-0062 %                               to the middle point should end with an
-0063 %                               arrow
-0064 %               type            'METABOLITE' or 'ENZYME'
-0065 %
-0066 %    Usage: pathway = constructPathwayFromCelldesigner(inputFile)
-0067 
-0068 %Loads the specified xml file using XML Toolbox
-0069 ravenPath=findRAVENroot();
-0070 
-0071 %Current path and xml toolbox path
-0072 cp=pwd;
-0073 xt=fullfile(ravenPath,'software','xml_toolbox');
-0074 
-0075 %Change path, run the script and change back
-0076 cd(xt);
-0077 v = xml_parseany(fileread(inputFile));
-0078 cd(cp);
-0079 
-0080 %Saves information on each compartment
-0081 for i=1:length(v.model{1,1}.annotation{1,1}.listOfCompartmentAliases{1,1}.compartmentAlias)
-0082     pathway.listOfCompartments(i).x=str2double(v.model{1,1}.annotation{1,1}.listOfCompartmentAliases{1,1}...
-0083         .compartmentAlias{1,i}.bounds{1,1}.ATTRIBUTE.x);
-0084     pathway.listOfCompartments(i).y=str2double(v.model{1,1}.annotation{1,1}.listOfCompartmentAliases{1,1}...
-0085         .compartmentAlias{1,i}.bounds{1,1}.ATTRIBUTE.y);
-0086     pathway.listOfCompartments(i).h=str2double(v.model{1,1}.annotation{1,1}.listOfCompartmentAliases{1,1}...
-0087         .compartmentAlias{1,i}.bounds{1,1}.ATTRIBUTE.h);
-0088     pathway.listOfCompartments(i).w=str2double(v.model{1,1}.annotation{1,1}.listOfCompartmentAliases{1,1}...
-0089         .compartmentAlias{1,i}.bounds{1,1}.ATTRIBUTE.w);
-0090     pathway.listOfCompartments(i).compartment=v.model{1,1}.annotation{1,1}.listOfCompartmentAliases{1,1}...
-0091         .compartmentAlias{1,i}.ATTRIBUTE.compartment;
-0092     pathway.listOfCompartments(i).id=v.model{1,1}.annotation{1,1}.listOfCompartmentAliases{1,1}...
-0093         .compartmentAlias{1,i}.ATTRIBUTE.id;
-0094     
-0095     %Finds the name of the compartment
-0096     for j=1:length(v.model{1,1}.listOfCompartments{1,1}.compartment)
-0097         if strcmpi(v.model{1,1}.listOfCompartments{1,1}.compartment{1,j}.ATTRIBUTE.id,...
-0098                 pathway.listOfCompartments(i).compartment)
-0099             pathway.listOfCompartments(i).name=v.model{1,1}.listOfCompartments{1,1}.compartment{1,j}.ATTRIBUTE.name;
-0100             break;
-0101         end
-0102     end
-0103 end
-0104 
-0105 %Saves information on each species and enzyme
-0106 for i=1:length(v.model{1,1}.annotation{1,1}.listOfSpeciesAliases{1,1}.speciesAlias)
-0107     pathway.listOfSpecies(i).x=str2double(v.model{1,1}.annotation{1,1}.listOfSpeciesAliases{1,1}...
-0108         .speciesAlias{1,i}.bounds{1,1}.ATTRIBUTE.x);
-0109     pathway.listOfSpecies(i).y=str2double(v.model{1,1}.annotation{1,1}.listOfSpeciesAliases{1,1}...
-0110         .speciesAlias{1,i}.bounds{1,1}.ATTRIBUTE.y);
-0111     pathway.listOfSpecies(i).h=str2double(v.model{1,1}.annotation{1,1}.listOfSpeciesAliases{1,1}...
-0112         .speciesAlias{1,i}.bounds{1,1}.ATTRIBUTE.h);
-0113     pathway.listOfSpecies(i).w=str2double(v.model{1,1}.annotation{1,1}.listOfSpeciesAliases{1,1}...
-0114         .speciesAlias{1,i}.bounds{1,1}.ATTRIBUTE.w);
-0115     pathway.listOfSpecies(i).alias=v.model{1,1}.annotation{1,1}.listOfSpeciesAliases{1,1}...
-0116         .speciesAlias{1,i}.ATTRIBUTE.id;
-0117     pathway.listOfSpecies(i).species=v.model{1,1}.annotation{1,1}.listOfSpeciesAliases{1,1}...
-0118         .speciesAlias{1,i}.ATTRIBUTE.species;
-0119     %Find the name and type of the species/enzyme
-0120     for j=1:length(v.model{1,1}.listOfSpecies{1,1}.species)
-0121         if strcmpi(v.model{1,1}.listOfSpecies{1,1}.species{1,j}.ATTRIBUTE.id,...
-0122                 pathway.listOfSpecies(i).species)
-0123             pathway.listOfSpecies(i).name=v.model{1,1}.listOfSpecies{1,1}.species{1,j}.ATTRIBUTE.name;
-0124             pathway.listOfSpecies(i).type=v.model{1,1}.listOfSpecies{1,1}.species{1,j}.annotation{1,1}...
-0125                 .speciesIdentity{1,1}.class{1,1}.CONTENT;
-0126             
-0127             %The Celldesigner chart can be linked to a model (e.g. for
-0128             %visualization of fluxes) by making a note in Celldesigner for
-0129             %the protein in interest (this can only be done for proteins at
-0130             %the moment). The note (not protein note!) should only contain
-0131             %the reaction id in the model which corresponds to the protein
-0132             %in Celldesigner.
-0133             if strcmpi(pathway.listOfSpecies(i).type,'PROTEIN')
-0134                 if isfield(v.model{1,1}.listOfSpecies{1,1}.species{1,j},'notes')
-0135                     pathway.listOfSpecies(i).note=cellstr(strtrim(v.model{1,1}.listOfSpecies{1,1}.species{1,j}...
-0136                         .notes{1,1}.html{1,1}.body{1,1}.CONTENT));
-0137                 end
-0138             end
-0139             break;
-0140         end
-0141     end
-0142 end
-0143 
-0144 %Saves information on each reaction
-0145 for i=1:length(v.model{1,1}.listOfReactions{1,1}.reaction)
-0146     %This is because it is standard for a reaction to be defined as
-0147     %reversible
-0148     if isfield(v.model{1,1}.listOfReactions{1,1}.reaction{1,i}.ATTRIBUTE,'reversible')
-0149         pathway.listOfReactions(i).reversible=v.model{1,1}.listOfReactions{1,1}...
-0150             .reaction{1,i}.ATTRIBUTE.reversible;
-0151     else
-0152         pathway.listOfReactions(i).reversible='true';
-0153     end
-0154     
-0155     %NOTE: As far as I know there can only be one base reactant/product per
-0156     %reaction. This method is written with that assumption.
-0157     
-0158     %Finds the alias of the base reactant
-0159     baseReactant=v.model{1,1}.listOfReactions{1,1}...
-0160         .reaction{1,i}.annotation{1,1}.baseReactants{1,1}.baseReactant{1,1}...
-0161         .ATTRIBUTE.alias;
-0162     
-0163     %Finds the alias of the base product
-0164     baseProduct=v.model{1,1}.listOfReactions{1,1}...
-0165         .reaction{1,i}.annotation{1,1}.baseProducts{1,1}.baseProduct{1,1}...
-0166         .ATTRIBUTE.alias;
-0167     
-0168     %Saves the middle point
-0169     [x1,y1]=getBindingPos(pathway,baseReactant,...
-0170         v.model{1,1}.listOfReactions{1,1}.reaction{1,i}.annotation{1,1}...
-0171         .baseReactants{1,1}.baseReactant{1,1}.linkAnchor{1,1}.ATTRIBUTE.position);
-0172     [x2,y2]=getBindingPos(pathway,baseProduct,...
-0173         v.model{1,1}.listOfReactions{1,1}.reaction{1,i}.annotation{1,1}...
-0174         .baseProducts{1,1}.baseProduct{1,1}.linkAnchor{1,1}.ATTRIBUTE.position);
-0175     pathway.listOfReactions(i).middlePoint(1)=x1+(x2-x1)/2;
-0176     pathway.listOfReactions(i).middlePoint(2)=y1+(y2-y1)/2;
-0177     
-0178     %Saves information on each of the components
-0179     counter=1; %Keeps track of where in componentList to add a component
-0180     
-0181     %Adds the base reactant
-0182     pathway.listOfReactions(i).componentList(counter).alias=v.model{1,1}...
-0183         .listOfReactions{1,1}.reaction{1,i}.annotation{1,1}.baseReactants{1,1}...
-0184         .baseReactant{1,1}.ATTRIBUTE.alias;
-0185     pathway.listOfReactions(i).componentList(counter).species=v.model{1,1}...
-0186         .listOfReactions{1,1}.reaction{1,i}.annotation{1,1}.baseReactants{1,1}...
-0187         .baseReactant{1,1}.ATTRIBUTE.species;
-0188     [x,y]=getBindingPos(pathway,baseReactant,v.model{1,1}.listOfReactions{1,1}...
-0189         .reaction{1,i}.annotation{1,1}.baseReactants{1,1}.baseReactant{1,1}...
-0190         .linkAnchor{1,1}.ATTRIBUTE.position);
-0191     pathway.listOfReactions(i).componentList(counter).anchor(1)=x;
-0192     pathway.listOfReactions(i).componentList(counter).anchor(2)=y;
-0193     pathway.listOfReactions(i).componentList(counter).baseReactant='true';
-0194     pathway.listOfReactions(i).componentList(counter).baseProduct='false';
-0195     
-0196     %toArrow should be true if the reaction is reversible
-0197     pathway.listOfReactions(i).componentList(counter).toArrow=...
-0198         pathway.listOfReactions(i).reversible;
-0199     pathway.listOfReactions(i).componentList(counter).fromArrow='false';
-0200     pathway.listOfReactions(i).componentList(counter).type='METABOLITE';
-0201     counter=counter+1;
-0202     
-0203     %Adds the base product
-0204     pathway.listOfReactions(i).componentList(counter).alias=v.model{1,1}...
-0205         .listOfReactions{1,1}.reaction{1,i}.annotation{1,1}.baseProducts{1,1}...
-0206         .baseProduct{1,1}.ATTRIBUTE.alias;
-0207     pathway.listOfReactions(i).componentList(counter).species=v.model{1,1}...
-0208         .listOfReactions{1,1}.reaction{1,i}.annotation{1,1}.baseProducts{1,1}...
-0209         .baseProduct{1,1}.ATTRIBUTE.species;
-0210     [x,y]=getBindingPos(pathway,baseProduct,v.model{1,1}.listOfReactions{1,1}...
-0211         .reaction{1,i}.annotation{1,1}.baseProducts{1,1}.baseProduct{1,1}...
-0212         .linkAnchor{1,1}.ATTRIBUTE.position);
-0213     pathway.listOfReactions(i).componentList(counter).anchor(1)=x;
-0214     pathway.listOfReactions(i).componentList(counter).anchor(2)=y;
-0215     pathway.listOfReactions(i).componentList(counter).baseReactant='false';
-0216     pathway.listOfReactions(i).componentList(counter).baseProduct='true';
-0217     pathway.listOfReactions(i).componentList(counter).toArrow='true';
-0218     pathway.listOfReactions(i).componentList(counter).fromArrow='false';
-0219     pathway.listOfReactions(i).componentList(counter).type='METABOLITE';
-0220     counter=counter+1;
-0221     
-0222     %Adds the non-base reactants Not all reactions have any non-base
-0223     %reactants
-0224     if isfield(v.model{1,1}.listOfReactions{1,1}.reaction{1,i}.annotation{1,1}...
-0225             ,'listOfReactantLinks')
-0226         for j=1:length(v.model{1,1}.listOfReactions{1,1}.reaction{1,i}.annotation{1,1}...
-0227                 .listOfReactantLinks{1,1}.reactantLink)
-0228             pathway.listOfReactions(i).componentList(counter).alias=v.model{1,1}...
-0229                 .listOfReactions{1,1}.reaction{1,i}.annotation{1,1}...
-0230                 .listOfReactantLinks{1,1}.reactantLink{1,j}.ATTRIBUTE.alias;
-0231             pathway.listOfReactions(i).componentList(counter).species=v.model{1,1}...
-0232                 .listOfReactions{1,1}.reaction{1,i}.annotation{1,1}...
-0233                 .listOfReactantLinks{1,1}.reactantLink{1,j}.ATTRIBUTE.reactant;
-0234             [x,y]=getBindingPos(pathway,pathway.listOfReactions(i).componentList(counter).alias...
-0235                 ,v.model{1,1}.listOfReactions{1,1}.reaction{1,i}.annotation{1,1}...
-0236                 .listOfReactantLinks{1,1}.reactantLink{1,j}.linkAnchor{1,1}...
-0237                 .ATTRIBUTE.position);
-0238             pathway.listOfReactions(i).componentList(counter).anchor(1)=x;
-0239             pathway.listOfReactions(i).componentList(counter).anchor(2)=y;
-0240             pathway.listOfReactions(i).componentList(counter).baseReactant='false';
-0241             pathway.listOfReactions(i).componentList(counter).baseProduct='false';
-0242             pathway.listOfReactions(i).componentList(counter).toArrow='false';
-0243             pathway.listOfReactions(i).componentList(counter).fromArrow='false';
-0244             pathway.listOfReactions(i).componentList(counter).type='METABOLITE';
-0245             counter=counter+1;
-0246         end
-0247     end
-0248     
-0249     %Adds the non-base products Not all reactions have any non-base
-0250     %products
-0251     if isfield(v.model{1,1}.listOfReactions{1,1}.reaction{1,i}.annotation{1,1}...
-0252             ,'listOfProductLinks')
-0253         for j=1:length(v.model{1,1}.listOfReactions{1,1}.reaction{1,i}.annotation{1,1}...
-0254                 .listOfProductLinks{1,1}.productLink)
-0255             pathway.listOfReactions(i).componentList(counter).alias=v.model{1,1}...
-0256                 .listOfReactions{1,1}.reaction{1,i}.annotation{1,1}...
-0257                 .listOfProductLinks{1,1}.productLink{1,j}.ATTRIBUTE.alias;
-0258             pathway.listOfReactions(i).componentList(counter).species=v.model{1,1}...
-0259                 .listOfReactions{1,1}.reaction{1,i}.annotation{1,1}...
-0260                 .listOfProductLinks{1,1}.productLink{1,j}.ATTRIBUTE.product;
-0261             [x,y]=getBindingPos(pathway,pathway.listOfReactions(i).componentList(counter).alias...
-0262                 ,v.model{1,1}.listOfReactions{1,1}.reaction{1,i}.annotation{1,1}...
-0263                 .listOfProductLinks{1,1}.productLink{1,j}.linkAnchor{1,1}...
-0264                 .ATTRIBUTE.position);
-0265             pathway.listOfReactions(i).componentList(counter).anchor(1)=x;
-0266             pathway.listOfReactions(i).componentList(counter).anchor(2)=y;
-0267             pathway.listOfReactions(i).componentList(counter).baseReactant='false';
-0268             pathway.listOfReactions(i).componentList(counter).baseProduct='false';
-0269             pathway.listOfReactions(i).componentList(counter).toArrow='true';
-0270             pathway.listOfReactions(i).componentList(counter).fromArrow='false';
-0271             pathway.listOfReactions(i).componentList(counter).type='METABOLITE';
-0272             counter=counter+1;
-0273         end
-0274     end
-0275     
-0276     %Adds the modifiers (enzymes) Not all reactions have any modifiers
-0277     if isfield(v.model{1,1}.listOfReactions{1,1}.reaction{1,i}.annotation{1,1}...
-0278             ,'listOfModification')
-0279         for j=1:length(v.model{1,1}.listOfReactions{1,1}.reaction{1,i}.annotation{1,1}...
-0280                 .listOfModification{1,1}.modification)
-0281             pathway.listOfReactions(i).componentList(counter).alias=v.model{1,1}...
-0282                 .listOfReactions{1,1}.reaction{1,i}.annotation{1,1}.listOfModification{1,1}...
-0283                 .modification{1,j}.linkTarget{1,1}.ATTRIBUTE.alias;
-0284             pathway.listOfReactions(i).componentList(counter).species=v.model{1,1}...
-0285                 .listOfReactions{1,1}.reaction{1,i}.annotation{1,1}.listOfModification{1,1}...
-0286                 .modification{1,j}.linkTarget{1,1}.ATTRIBUTE.species;
-0287             [x,y]=getBindingPos(pathway,pathway.listOfReactions(i).componentList(counter).alias...
-0288                 ,v.model{1,1}.listOfReactions{1,1}.reaction{1,i}.annotation{1,1}...
-0289                 .listOfModification{1,1}.modification{1,j}.linkTarget{1,1}...
-0290                 .linkAnchor{1,1}.ATTRIBUTE.position);
-0291             pathway.listOfReactions(i).componentList(counter).anchor(1)=x;
-0292             pathway.listOfReactions(i).componentList(counter).anchor(2)=y;
-0293             pathway.listOfReactions(i).componentList(counter).baseReactant='false';
-0294             pathway.listOfReactions(i).componentList(counter).baseProduct='false';
-0295             pathway.listOfReactions(i).componentList(counter).toArrow='false';
-0296             pathway.listOfReactions(i).componentList(counter).fromArrow='false';
-0297             pathway.listOfReactions(i).componentList(counter).type='ENZYME';
-0298             counter=counter+1;
-0299         end
-0300     end
-0301 end
-0302 end
-0303 
-0304 function [x,y]=getBindingPos(pathway,speciesAlias,bindingSite)
-0305 % getBindingPos
-0306 %   Calculates the position of a given binding site for a specified species
-0307 %
-0308 %   pathway         the pathway structure which should be modified
-0309 %   speciesAlias    the alias of the species bindingSite     The binding
-0310 %   site in Celldesigner is a string of up to
-0311 %                   three letters that defines which of the 16 bindings
-0312 %                   sites on each species to use. They are written as N
-0313 %                   (north), NNW (north north west) and so on
-0314 %
-0315 %   [x, y]          The position of the binding site for the species
-0316 %
-0317 % Usage: [x,y]=getBindingPos(pathway,speciesAlias,bindingSite)
-0318 
-0319 %Find the species
-0320 for i=1:length(pathway.listOfSpecies)
-0321     if strcmpi(pathway.listOfSpecies(i).alias,speciesAlias)
-0322         xpos=pathway.listOfSpecies(i).x;
-0323         ypos=pathway.listOfSpecies(i).y;
-0324         h=pathway.listOfSpecies(i).h;
-0325         w=pathway.listOfSpecies(i).w;
-0326         
-0327         %Species marked as "PROTEIN" should be drawn as rectangles. There
-0328         %is one binding site in each corner and three in between on each
-0329         %side.
-0330         if strcmpi(pathway.listOfSpecies(i).type,'PROTEIN')
-0331             %The binding sites clockwise from the top position
-0332             if strcmpi(bindingSite,'N')
-0333                 x=xpos+0.5*w;
-0334                 y=ypos;
-0335                 break;
-0336             end
-0337             if strcmpi(bindingSite,'NNE')
-0338                 x=xpos+0.75*w;
-0339                 y=ypos;
-0340                 break;
-0341             end
-0342             if strcmpi(bindingSite,'NE')
-0343                 x=xpos+w;
-0344                 y=ypos;
-0345                 break;
-0346             end
-0347             if strcmpi(bindingSite,'ENE')
-0348                 x=xpos+w;
-0349                 y=ypos+0.25*h;
-0350                 break;
-0351             end
-0352             if strcmpi(bindingSite,'E')
-0353                 x=xpos+w;
-0354                 y=ypos+0.5*h;
-0355                 break;
-0356             end
-0357             if strcmpi(bindingSite,'ESE')
-0358                 x=xpos+w;
-0359                 y=ypos+0.75*h;
-0360                 break;
-0361             end
-0362             if strcmpi(bindingSite,'SE')
-0363                 x=xpos+w;
-0364                 y=ypos+h;
-0365                 break;
-0366             end
-0367             if strcmpi(bindingSite,'SSE')
-0368                 x=xpos+0.75*w;
-0369                 y=ypos+h;
-0370                 break;
-0371             end
-0372             if strcmpi(bindingSite,'S')
-0373                 x=xpos+0.5*w;
-0374                 y=ypos+h;
-0375                 break;
-0376             end
-0377             if strcmpi(bindingSite,'SSW')
-0378                 x=xpos+0.25*w;
-0379                 y=ypos+h;
-0380                 break;
-0381             end
-0382             if strcmpi(bindingSite,'SW')
-0383                 x=xpos;
-0384                 y=ypos+h;
-0385                 break;
-0386             end
-0387             if strcmpi(bindingSite,'WSW')
-0388                 x=xpos;
-0389                 y=ypos+0.75*h;
-0390                 break;
-0391             end
-0392             if strcmpi(bindingSite,'W')
-0393                 x=xpos;
-0394                 y=ypos+0.5*h;
-0395                 break;
-0396             end
-0397             if strcmpi(bindingSite,'WNW')
-0398                 x=xpos;
-0399                 y=ypos+0.25*h;
-0400                 break;
-0401             end
-0402             if strcmpi(bindingSite,'NW')
-0403                 x=xpos;
-0404                 y=ypos;
-0405                 break;
-0406             end
-0407             if strcmpi(bindingSite,'NNW')
-0408                 x=xpos+0.25*w;
-0409                 y=ypos;
-0410                 break;
-0411             end
-0412         end
-0413         
-0414         %Species marked as "SIMPLE_MOLECULE" should be drawn as ellipses.
-0415         %There is one binding site in each extreme point and three in
-0416         %between on each side
-0417         if strcmpi(pathway.listOfSpecies(i).type,'SIMPLE_MOLECULE')
-0418             %Find the center of the ellipse
-0419             centerX=xpos+0.5*w;
-0420             centerY=ypos+0.5*h;
-0421             
-0422             %The binding sites clockwise from the top position
-0423             if strcmpi(bindingSite,'N')
-0424                 angle=(4/8)*pi;
-0425             end
-0426             if strcmpi(bindingSite,'NNE')
-0427                 angle=(5/8)*pi;
-0428             end
-0429             if strcmpi(bindingSite,'NE')
-0430                 angle=(6/8)*pi;
-0431             end
-0432             if strcmpi(bindingSite,'ENE')
-0433                 angle=(7/8)*pi;
-0434             end
-0435             if strcmpi(bindingSite,'E')
-0436                 angle=(8/8)*pi;
-0437             end
-0438             if strcmpi(bindingSite,'ESE')
-0439                 angle=(9/8)*pi;
-0440             end
-0441             if strcmpi(bindingSite,'SE')
-0442                 angle=(10/8)*pi;
-0443             end
-0444             if strcmpi(bindingSite,'SSE')
-0445                 angle=(11/8)*pi;
-0446             end
-0447             if strcmpi(bindingSite,'S')
-0448                 angle=(12/8)*pi;
-0449             end
-0450             if strcmpi(bindingSite,'SSW')
-0451                 angle=(13/8)*pi;
-0452             end
-0453             if strcmpi(bindingSite,'SW')
-0454                 angle=(14/8)*pi;
-0455             end
-0456             if strcmpi(bindingSite,'WSW')
-0457                 angle=(15/8)*pi;
-0458             end
-0459             if strcmpi(bindingSite,'W')
-0460                 angle=(16/8)*pi;
-0461             end
-0462             if strcmpi(bindingSite,'WNW')
-0463                 angle=(1/8)*pi;
-0464             end
-0465             if strcmpi(bindingSite,'NW')
-0466                 angle=(2/8)*pi;
-0467             end
-0468             if strcmpi(bindingSite,'NNW')
-0469                 angle=(3/8)*pi;
-0470             end
-0471             x=centerX-(0.5*w)*cos(angle);
-0472             y=centerY-(0.5*h)*sin(angle);
-0473             break;
-0474         end
-0475     end
-0476 end
-0477 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/legacy/external/index.html b/doc/legacy/external/index.html deleted file mode 100644 index 91f40e6db..000000000 --- a/doc/legacy/external/index.html +++ /dev/null @@ -1,29 +0,0 @@ - - - - Index for Directory legacy\external - - - - - - - - - - -
< Master indexIndex for legacy\external >
- -

Index for legacy\external

- -

Matlab files in this directory:

- -
 constructPathwayFromCelldesignerconstructPathwayFromCelldesigner
- - - - -
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/linux.png b/doc/linux.png deleted file mode 100644 index 42c0c328ee43a884158a8363682c493d4a4c335f..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 272 zcmV+r0q_2aP)z zQ4WJ342H|%(dbp$Gu5lqySaxtLO>W(rpx%_LnVK(UrGTT5y42B06;|UPU9jm^JJ0Z z`TTUN(6TJ&=lPPn_WX zId~2>0yJfGb3Up-MDlH7S}Vx-I*N`iO3-5Ff$K-Ed9Nepzm`zojRl WMtq7>mNL`;0000slDkd7sMUhm~nn@(#}qULHtXTzoc}*_9Non9cn|mMot$6xao(HD{Btemfo7KftJ(gq<~Y~G z@qZoHkA=+tS8)7W&Uw9q`Tr8me+#(&&u0HSm+S9Tw*NEO-*s^O@8dn4!TPz8qu!P4 zK_1Jw46grGoai}Etj@tK_}C@RCk z%#`S6Zs-xzlqxAD$1kf8AM0wN?c%>SMNC?Phc6~Pz{yO{A+R?kRa_)AA;iir?(CQ-4ncIv-nB)Nx{hL?F`wWg|rwizO*(ixxOASOWm3r><21 diff --git a/doc/mex.png b/doc/mex.png deleted file mode 100644 index 396f1bc943e311539c64aa839ba14242c3b1493c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 242 zcmeAS@N?(olHy`uVBq!ia0vp^GC<7D!VDzmefZDNn{1``2&1H zT>k^XH6VupNCU}&+~7Mvim@cfFPOpM*^M+1C&}C0g`tC0)&t1lEbxdd1{y2`!i<;h z*8KqrvX^-Jy0Ty9km3|#4DWEh2o&=1ba4!+m=oK_$albigXt^#BmNKn`(>_}oOavV zHb=Afht|Vg%9B``@)jwvpOrK#Ny(Hf&TUq{A5ne4dvCr*%)z?JLGp XX&kFA6^pR}&1LX(^>bP0l+XkK#Yar! diff --git a/doc/pathway/colorPathway.html b/doc/pathway/colorPathway.html deleted file mode 100644 index e9632c9f6..000000000 --- a/doc/pathway/colorPathway.html +++ /dev/null @@ -1,143 +0,0 @@ - - - - Description of colorPathway - - - - - - - - - -
Home > pathway > colorPathway.m
- - - -

colorPathway -

- -

PURPOSE ^

-
colorPathway
- -

SYNOPSIS ^

-
function returnPathway = colorPathway(pathway, reactionIDs, fluxes, referenceFluxes,cutOff, defaultColor, upColor, downColor)
- -

DESCRIPTION ^

-
 colorPathway
-    Calculates the color for those reactions that should be marked in the
-    map and returns an updated pathway structure.
-
-   pathway         pathway structure of the metabolic network
-   reactionsIDs    cell array with the names of the reactions in the model
-   fluxes          vector with flux values from the simulation
-   referenceFluxes vector with fluxes for the reference simulation
-   cutOff          a reaction is only colored if the absolute value of 
-                   at least one of the fluxes is above the cutoff value
-                   (optional, default 0)
-   defaultColor    a color in Matlab format to be used if there are no
-                   changes between the fluxes. This color is also used to 
-                   calculate the transition between the colors for up and
-                   down regulated fluxes (optional, default [1 1 1])
-   upColor         a color in Matlab format to be used if the flux is 
-                   larger than the reference flux (optional, default [0 1 0])
-   downColor       a color in Matlab format to be used if the flux is 
-                   smaller than the reference flux (optional, default [1 0 0])
-
-   returnPathway   updated pathway structure which contains coloring data
-       color       array indicating the coloring of the enzyme
-       signChange  true if the reaction has changed direction
-
-    Usage: returnPathway = colorPathway(pathway, reactionIDs, fluxes, referenceFluxes, ...
-           cutOff, defaultColor, upColor, downColor)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function returnPathway = colorPathway(pathway, reactionIDs, fluxes, referenceFluxes, ...
-0002     cutOff, defaultColor, upColor, downColor)
-0003 % colorPathway
-0004 %    Calculates the color for those reactions that should be marked in the
-0005 %    map and returns an updated pathway structure.
-0006 %
-0007 %   pathway         pathway structure of the metabolic network
-0008 %   reactionsIDs    cell array with the names of the reactions in the model
-0009 %   fluxes          vector with flux values from the simulation
-0010 %   referenceFluxes vector with fluxes for the reference simulation
-0011 %   cutOff          a reaction is only colored if the absolute value of
-0012 %                   at least one of the fluxes is above the cutoff value
-0013 %                   (optional, default 0)
-0014 %   defaultColor    a color in Matlab format to be used if there are no
-0015 %                   changes between the fluxes. This color is also used to
-0016 %                   calculate the transition between the colors for up and
-0017 %                   down regulated fluxes (optional, default [1 1 1])
-0018 %   upColor         a color in Matlab format to be used if the flux is
-0019 %                   larger than the reference flux (optional, default [0 1 0])
-0020 %   downColor       a color in Matlab format to be used if the flux is
-0021 %                   smaller than the reference flux (optional, default [1 0 0])
-0022 %
-0023 %   returnPathway   updated pathway structure which contains coloring data
-0024 %       color       array indicating the coloring of the enzyme
-0025 %       signChange  true if the reaction has changed direction
-0026 %
-0027 %    Usage: returnPathway = colorPathway(pathway, reactionIDs, fluxes, referenceFluxes, ...
-0028 %           cutOff, defaultColor, upColor, downColor)
-0029 
-0030 if nargin<8
-0031     downColor=[1 0 0];
-0032 end
-0033 if nargin<7
-0034     upColor=[0 1 0];
-0035 end
-0036 if nargin<6
-0037     defaultColor=[1 1 1];
-0038 end
-0039 if nargin<5
-0040     cutOff=0;
-0041 end
-0042 
-0043 %Loop through the components in the pathway. Check if any component has a
-0044 %note and then check for the corresponding reaction id
-0045 returnPathway=pathway;
-0046 
-0047 for i=1:length(pathway.listOfSpecies)
-0048     if strcmpi(pathway.listOfSpecies(i).type,'PROTEIN')
-0049         if isfield(pathway.listOfSpecies(i),'note')
-0050             if ~isempty(pathway.listOfSpecies(i).note)
-0051                 %If there is a note check if there is a corresponding
-0052                 %reaction id
-0053                 correspondingReaction=find(strcmpi(reactionIDs,pathway.listOfSpecies(i).note));
-0054                 if correspondingReaction>0
-0055                     %Check if either flux is above the cutoff value
-0056                     if abs(referenceFluxes(correspondingReaction))>=cutOff ||...
-0057                             abs(fluxes(correspondingReaction))>=cutOff
-0058                         %Calculate the corresponding color
-0059                         [color, signChange]=getColorCodes(referenceFluxes(correspondingReaction)...
-0060                             ,fluxes(correspondingReaction),1 , defaultColor, upColor, downColor);
-0061                         if ~isempty(color)
-0062                             returnPathway.listOfSpecies(i).color=color{1,1};
-0063                             returnPathway.listOfSpecies(i).signChange=signChange{1,1};
-0064                         end
-0065                     end
-0066                 end
-0067             end
-0068         end
-0069     end
-0070 end
-0071 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/pathway/getPathwayDimensions.html b/doc/pathway/getPathwayDimensions.html deleted file mode 100644 index a9db91aaa..000000000 --- a/doc/pathway/getPathwayDimensions.html +++ /dev/null @@ -1,109 +0,0 @@ - - - - Description of getPathwayDimensions - - - - - - - - - -
Home > pathway > getPathwayDimensions.m
- - - -

getPathwayDimensions -

- -

PURPOSE ^

-
getPathwayDimensions
- -

SYNOPSIS ^

-
function dimensions=getPathwayDimensions(pathway)
- -

DESCRIPTION ^

-
 getPathwayDimensions 
-   Retrieves the dimensions of metabolic network in a pathway structure.
-   Returns the position of the upper left corner, width and height.
-
-   pathway         pathway structure representing the pathway to be drawn
-
-   dimension       a 1x4 vector with x and y for the upper left corner,
-                   height and width
-
- Usage: dimensions=getPathwayDimensions(pathway)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function dimensions=getPathwayDimensions(pathway)
-0002 % getPathwayDimensions
-0003 %   Retrieves the dimensions of metabolic network in a pathway structure.
-0004 %   Returns the position of the upper left corner, width and height.
-0005 %
-0006 %   pathway         pathway structure representing the pathway to be drawn
-0007 %
-0008 %   dimension       a 1x4 vector with x and y for the upper left corner,
-0009 %                   height and width
-0010 %
-0011 % Usage: dimensions=getPathwayDimensions(pathway)
-0012 
-0013 right=0;
-0014 left=inf;
-0015 top=inf;
-0016 bottom=0;
-0017 
-0018 %Loops through the compartments to find the right and bottom border and the
-0019 %position of the upper left corner
-0020 for i=1:length(pathway.listOfCompartments)
-0021     if pathway.listOfCompartments(1,i).x<left
-0022         left=pathway.listOfCompartments(1,i).x;
-0023     end
-0024     if pathway.listOfCompartments(1,i).y<top
-0025         top=pathway.listOfCompartments(1,i).y;
-0026     end
-0027     if (pathway.listOfCompartments(1,i).x+pathway.listOfCompartments(1,i).w)>right
-0028         right=pathway.listOfCompartments(1,i).x+pathway.listOfCompartments(1,i).w;
-0029     end
-0030     if (pathway.listOfCompartments(1,i).y+pathway.listOfCompartments(1,i).h)>bottom
-0031         bottom=pathway.listOfCompartments(1,i).y+pathway.listOfCompartments(1,i).h;
-0032     end
-0033 end
-0034 
-0035 %Loops through the species to find the object furthest to the right, left,
-0036 %top and bottom
-0037 for i=1:length(pathway.listOfSpecies)
-0038     if pathway.listOfSpecies(1,i).x<left
-0039         left=pathway.listOfSpecies(1,i).x;
-0040     end
-0041     if pathway.listOfSpecies(1,i).y<top
-0042         top=pathway.listOfSpecies(1,i).y;
-0043     end
-0044     if (pathway.listOfSpecies(1,i).x+pathway.listOfSpecies(1,i).w)>right
-0045         right=pathway.listOfSpecies(1,i).x+pathway.listOfSpecies(1,i).w;
-0046     end
-0047     if (pathway.listOfSpecies(1,i).y+pathway.listOfSpecies(1,i).h)>bottom
-0048         bottom=pathway.listOfSpecies(1,i).y+pathway.listOfSpecies(1,i).h;
-0049     end
-0050 end
-0051 
-0052 dimensions=[left,top,right-left,bottom-top];
-0053 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/pathway/index.html b/doc/pathway/index.html deleted file mode 100644 index b2c907cb4..000000000 --- a/doc/pathway/index.html +++ /dev/null @@ -1,29 +0,0 @@ - - - - Index for Directory pathway - - - - - - - - - - -
< Master indexIndex for pathway >
- -

Index for pathway

- -

Matlab files in this directory:

- -
 colorPathwaycolorPathway
 getPathwayDimensionsgetPathwayDimensions
 mapPathwayRxnNamesmapPathwayRxnNames
 markPathwayWithExpressionmarkPathwayWithExpression
 markPathwayWithFluxesmarkPathwayWithFluxes
 trimPathwaytrimPathway
- - - - -
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/pathway/mapPathwayRxnNames.html b/doc/pathway/mapPathwayRxnNames.html deleted file mode 100644 index 7c7c0132b..000000000 --- a/doc/pathway/mapPathwayRxnNames.html +++ /dev/null @@ -1,98 +0,0 @@ - - - - Description of mapPathwayRxnNames - - - - - - - - - -
Home > pathway > mapPathwayRxnNames.m
- - - -

mapPathwayRxnNames -

- -

PURPOSE ^

-
mapPathwayRxnNames
- -

SYNOPSIS ^

-
function [pathway, notMapped]=mapPathwayRxnNames(pathway,originalLabels,newLabels)
- -

DESCRIPTION ^

-
 mapPathwayRxnNames
-   For mapping labels in the pathway object. Useful if you want to change
-   what is shown in the reaction boxes.
-
-   pathway         pathway structure representing the pathway to be drawn
-   originalLabels  cell array with the original reaction labels
-   newLabels       cell array with the new reaction labels
-
-   pathway         an updated pathway structure
-   notMapped       a cell array with labels that could not be found in the
-                   pathway object
-
- Usage: [pathway, notMapped]=mapPathwayRxnNames(pathway,originalLabels,newLabels)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function [pathway, notMapped]=mapPathwayRxnNames(pathway,originalLabels,newLabels)
-0002 % mapPathwayRxnNames
-0003 %   For mapping labels in the pathway object. Useful if you want to change
-0004 %   what is shown in the reaction boxes.
-0005 %
-0006 %   pathway         pathway structure representing the pathway to be drawn
-0007 %   originalLabels  cell array with the original reaction labels
-0008 %   newLabels       cell array with the new reaction labels
-0009 %
-0010 %   pathway         an updated pathway structure
-0011 %   notMapped       a cell array with labels that could not be found in the
-0012 %                   pathway object
-0013 %
-0014 % Usage: [pathway, notMapped]=mapPathwayRxnNames(pathway,originalLabels,newLabels)
-0015 
-0016 if numel(originalLabels)~=numel(newLabels)
-0017     EM='The new label cell array must have the same length as the old label cell array';
-0018     dispEM(EM);
-0019 end
-0020 
-0021 mapped=false(numel(originalLabels),1);
-0022 
-0023 for i=1:numel(pathway.listOfSpecies)
-0024     if strcmpi(pathway.listOfSpecies(i).type,'PROTEIN')
-0025         I=find(ismember(originalLabels,pathway.listOfSpecies(i).name));
-0026         if any(I)
-0027             if numel(I)==1
-0028                 pathway.listOfSpecies(i).name=newLabels{I};
-0029                 mapped(I)=true;
-0030             else
-0031                 EM=['The label "' pathway.listOfSpecies(i).name '" was found in several positions in oldLabels'];
-0032                 dispEM(EM);
-0033             end
-0034         end
-0035     end
-0036 end
-0037 
-0038 notMapped=originalLabels(~mapped);
-0039 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/pathway/markPathwayWithExpression.html b/doc/pathway/markPathwayWithExpression.html deleted file mode 100644 index bfd985f1d..000000000 --- a/doc/pathway/markPathwayWithExpression.html +++ /dev/null @@ -1,118 +0,0 @@ - - - - Description of markPathwayWithExpression - - - - - - - - - -
Home > pathway > markPathwayWithExpression.m
- - - -

markPathwayWithExpression -

- -

PURPOSE ^

-
markPathwayWithExpression
- -

SYNOPSIS ^

-
function pathway=markPathwayWithExpression(pathway,model,experiment,experimentOrder)
- -

DESCRIPTION ^

-
 markPathwayWithExpression
-   Adds gene expression data to a pathway object
-
-   pathway           map structure as generated by constructPathwayFromCelldesigner
-   model             a model structure
-   experiment        experiment structure as generated by getExpressionStructure
-   experimentOrder   cell array with two experiment names as defined in
-                     'experiment'
-
-   pathway           updated pathway object
-
- Usage: pathway=markPathwayWithExpression(pathway,model,experiment,experimentOrder)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function pathway=markPathwayWithExpression(pathway,model,experiment,experimentOrder)
-0002 % markPathwayWithExpression
-0003 %   Adds gene expression data to a pathway object
-0004 %
-0005 %   pathway           map structure as generated by constructPathwayFromCelldesigner
-0006 %   model             a model structure
-0007 %   experiment        experiment structure as generated by getExpressionStructure
-0008 %   experimentOrder   cell array with two experiment names as defined in
-0009 %                     'experiment'
-0010 %
-0011 %   pathway           updated pathway object
-0012 %
-0013 % Usage: pathway=markPathwayWithExpression(pathway,model,experiment,experimentOrder)
-0014 
-0015 if numel(experimentOrder)~=2
-0016     EM='This can only be done for two cases at the moment (experimentOrder must be two elements)';
-0017     dispEM(EM);
-0018 end
-0019 
-0020 %Check that experiment fit with experimentOrder
-0021 [present, expIds]=ismember(experimentOrder,experiment.experiments);
-0022 
-0023 if ~all(present)
-0024     EM='Not all experiments could be found in the experiment structure';
-0025     dispEM(EM);
-0026 end
-0027 
-0028 experiment.data=experiment.data(:,expIds);
-0029 experiment.experiments=experiment.experiments(:,expIds);
-0030 
-0031 %Go through each species in pathway and if it's a reaction, get it's genes
-0032 %and log2-fold change in expression from model and experiment
-0033 for i=1:numel(pathway.listOfSpecies)
-0034     if strcmp('PROTEIN', pathway.listOfSpecies(i).type)
-0035         if isfield(pathway.listOfSpecies(i),'note')
-0036             if ~isempty(pathway.listOfSpecies(i).note)
-0037                 %Get the reaction if present in model
-0038                 [present, index]=ismember(pathway.listOfSpecies(i).note,model.rxns);
-0039                 
-0040                 %If present, then get the genes
-0041                 if any(present)
-0042                     [~, genes]=find(model.rxnGeneMat(index,:));
-0043                     
-0044                     %If it was associated with genes match them to the ORFs
-0045                     if any(genes)
-0046                         [present, experimentIndexes]=ismember(model.genes(genes),experiment.orfs);
-0047                         
-0048                         %Add annotation to pathway structure
-0049                         if any(present)
-0050                             pathway.listOfSpecies(i).orfs=experiment.orfs(experimentIndexes(present));
-0051                             pathway.listOfSpecies(i).expA=experiment.data(experimentIndexes(present),1);
-0052                             pathway.listOfSpecies(i).expB=experiment.data(experimentIndexes(present),2);
-0053                         end
-0054                     end
-0055                 end
-0056             end
-0057         end
-0058     end
-0059 end
-0060 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/pathway/markPathwayWithFluxes.html b/doc/pathway/markPathwayWithFluxes.html deleted file mode 100644 index 10c86f548..000000000 --- a/doc/pathway/markPathwayWithFluxes.html +++ /dev/null @@ -1,111 +0,0 @@ - - - - Description of markPathwayWithFluxes - - - - - - - - - -
Home > pathway > markPathwayWithFluxes.m
- - - -

markPathwayWithFluxes -

- -

PURPOSE ^

-
markPathwayWithFluxes
- -

SYNOPSIS ^

-
function [returnPathway, errorFlag]= markPathwayWithFluxes(pathway, reactionIDs, fluxes, referenceFluxes)
- -

DESCRIPTION ^

-
 markPathwayWithFluxes
-   Marks each enzyme in a pathway structure with the corresponding fluxes
-   from two simulation results. This is done for enzymes that has the name
-   of a reaction in the note field. The reaction has to be present in
-   reactionIDs.
-
-   pathway         pathway structure of the metabolic network
-   reactionsIDs    cell array with the names of the reactions in the model
-   fluxes          vector with flux values
-   referenceFluxes vector with fluxes to compare to
-
-   returnPathway   updates the original pathway structure by adding the
-                   fields flux and referenceFlux for each marked reaction
-   errorFlag       true if there has been an error
-
- Usage: [returnPathway, errorFlag] = markPathwayWithFluxes(pathway, reactionIDs,
-   fluxes, referenceFluxes)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function [returnPathway, errorFlag]= markPathwayWithFluxes(pathway, reactionIDs, fluxes, referenceFluxes)
-0002 % markPathwayWithFluxes
-0003 %   Marks each enzyme in a pathway structure with the corresponding fluxes
-0004 %   from two simulation results. This is done for enzymes that has the name
-0005 %   of a reaction in the note field. The reaction has to be present in
-0006 %   reactionIDs.
-0007 %
-0008 %   pathway         pathway structure of the metabolic network
-0009 %   reactionsIDs    cell array with the names of the reactions in the model
-0010 %   fluxes          vector with flux values
-0011 %   referenceFluxes vector with fluxes to compare to
-0012 %
-0013 %   returnPathway   updates the original pathway structure by adding the
-0014 %                   fields flux and referenceFlux for each marked reaction
-0015 %   errorFlag       true if there has been an error
-0016 %
-0017 % Usage: [returnPathway, errorFlag] = markPathwayWithFluxes(pathway, reactionIDs,
-0018 %   fluxes, referenceFluxes)
-0019 
-0020 %Check if all variables are of the correct dimension
-0021 if length(reactionIDs)~=length(fluxes) || length(reactionIDs)~=length(referenceFluxes)
-0022     returnPathway=pathway;
-0023     errorFlag=1;
-0024     fprintf('reactionIDs, fluxes, and referenceFluxes do not have the same number of elements.');
-0025     return;
-0026 end
-0027 
-0028 %Loop through the components in the pathway. Check if any component has a
-0029 %note and then check for the corresponding reaction id
-0030 returnPathway=pathway;
-0031 
-0032 for i=1:length(pathway.listOfSpecies)
-0033     if strcmpi(pathway.listOfSpecies(i).type,'PROTEIN')
-0034         if isfield(pathway.listOfSpecies(i),'note')
-0035             if ~isempty(pathway.listOfSpecies(i).note)
-0036                 %If there is a note check if there is a corresponding
-0037                 %reaction id
-0038                 index=find(strcmpi(reactionIDs,pathway.listOfSpecies(i).note));
-0039                 %If there is a match
-0040                 if any(index)
-0041                     returnPathway.listOfSpecies(i).flux=fluxes(index);
-0042                     returnPathway.listOfSpecies(i).referenceFlux=referenceFluxes(index);
-0043                 end
-0044             end
-0045         end
-0046     end
-0047 end
-0048 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/pathway/trimPathway.html b/doc/pathway/trimPathway.html deleted file mode 100644 index 84d26ee25..000000000 --- a/doc/pathway/trimPathway.html +++ /dev/null @@ -1,146 +0,0 @@ - - - - Description of trimPathway - - - - - - - - - -
Home > pathway > trimPathway.m
- - - -

trimPathway -

- -

PURPOSE ^

-
trimPathway
- -

SYNOPSIS ^

-
function pathway=trimPathway(pathway, rxnsToKeep, deleteUnconnectedMets)
- -

DESCRIPTION ^

-
 trimPathway
-   Delete reactions from a pathway object
-
-   pathway                   map structure as generated by 
-                             constructPathwayFromCelldesigner
-   rxnsToKeep                cell array with the IDs of the reactions to
-                             keep
-   deleteUnconnectedMets     delete metabolites that are no longer connected
-                             by any reactions (optional, default true)
-
-     pathway                   an updated pathway object
-
- Usage: pathway=trimPathway(pathway, rxnsToKeep, deleteUnconnectedMets)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function pathway=trimPathway(pathway, rxnsToKeep, deleteUnconnectedMets)
-0002 % trimPathway
-0003 %   Delete reactions from a pathway object
-0004 %
-0005 %   pathway                   map structure as generated by
-0006 %                             constructPathwayFromCelldesigner
-0007 %   rxnsToKeep                cell array with the IDs of the reactions to
-0008 %                             keep
-0009 %   deleteUnconnectedMets     delete metabolites that are no longer connected
-0010 %                             by any reactions (optional, default true)
-0011 %
-0012 %     pathway                   an updated pathway object
-0013 %
-0014 % Usage: pathway=trimPathway(pathway, rxnsToKeep, deleteUnconnectedMets)
-0015 
-0016 if nargin<3
-0017     deleteUnconnectedMets=true;
-0018 end
-0019 
-0020 %First find the aliases and indexes of all reactions that should be deleted
-0021 indexesToDelete=false(numel(pathway.listOfSpecies),1);
-0022 aliasesToDelete={};
-0023 
-0024 for i=1:numel(pathway.listOfSpecies)
-0025     if strcmpi(pathway.listOfSpecies(i).type,'PROTEIN')
-0026         %Check if the name is in the list of reactions to delete
-0027         if ~ismember(pathway.listOfSpecies(i).name,rxnsToKeep)
-0028             indexesToDelete(i)=true;
-0029             aliasesToDelete=[aliasesToDelete;pathway.listOfSpecies(i).alias];
-0030         end
-0031     end
-0032 end
-0033 
-0034 %Then go through each of the reactions and delete the ones that only have
-0035 %modifiers that are in the aliasesToDelete list
-0036 rxnsToDelete=false(numel(pathway.listOfReactions),1);
-0037 
-0038 for i=1:numel(pathway.listOfReactions)
-0039     %Keeps track of which components to delete. -1=enzyme to delete,
-0040     %0=metabolite, 1=enzyme to keep
-0041     componentsToDelete=zeros(numel(pathway.listOfReactions(i).componentList),1);
-0042     for j=1:numel(pathway.listOfReactions(i).componentList)
-0043         if strcmpi(pathway.listOfReactions(i).componentList(j).type,'ENZYME')
-0044             %If the enzyme alias is not in the list then should it not be
-0045             %deleted
-0046             if ismember(pathway.listOfReactions(i).componentList(j).alias,aliasesToDelete)
-0047                 componentsToDelete(j)=-1;
-0048             else
-0049                 componentsToDelete(j)=1;
-0050             end
-0051         end
-0052     end
-0053     %If all enzymes should be deleted then should the whole reacction be
-0054     %deleted. Otherwise only delete those enzymes
-0055     if ~any(componentsToDelete==1)
-0056         rxnsToDelete(i)=true;
-0057     else
-0058         pathway.listOfReactions(i).componentList(componentsToDelete==-1)=[];
-0059     end
-0060 end
-0061 
-0062 %Delete the reactions and components that should be deleted
-0063 pathway.listOfSpecies(indexesToDelete)=[];
-0064 pathway.listOfReactions(rxnsToDelete)=[];
-0065 
-0066 %This is not neat but it goes through all the reactions and adds the
-0067 %aliases that should be kept. All other are deleted
-0068 aliasesToKeeep={};
-0069 if deleteUnconnectedMets==true
-0070     for i=1:numel(pathway.listOfReactions)
-0071         for j=1:numel(pathway.listOfReactions(i).componentList)
-0072             aliasesToKeeep=[aliasesToKeeep;pathway.listOfReactions(i).componentList(j).alias];
-0073         end
-0074     end
-0075     
-0076     %Go through the species again and only keep those that are in the
-0077     %aliasesToKeeep list
-0078     indexesToDelete=true(numel(pathway.listOfSpecies),1);
-0079     for i=1:numel(pathway.listOfSpecies)
-0080         if ismember(pathway.listOfSpecies(i).alias,aliasesToKeeep)
-0081             indexesToDelete(i)=false;
-0082         end
-0083     end
-0084     
-0085     pathway.listOfSpecies(indexesToDelete)=[];
-0086 end
-0087 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/pcode.png b/doc/pcode.png deleted file mode 100644 index 6801bd9a259131e6de7d7957789598a451c04334..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 212 zcmeAS@N?(olHy`uVBq!ia0vp^Qb5ej!3-qBCsR(zDBw1As!D z1s;*bKxKj;%vhfiKM^R%lJ4m1$iT3%pZiZDD@aj*Pl)S(AYk|pNdQueB|(0{ z3=Yq3qyagOo-U3d6}OTT4lqj`WYF%P$jKq`kl`G&cO%P#Bm=oF5vkS`g - - - Description of colorSubsystem - - - - - - - - - -
Home > plotting > colorSubsystem.m
- - - -

colorSubsystem -

- -

PURPOSE ^

-
Modified from colorSubsystemCD as distributed through COBRA Toolbox
- -

SYNOPSIS ^

-
function newMap = colorSubsystem(map, model, subsystem, color)
- -

DESCRIPTION ^

-
 Modified from colorSubsystemCD as distributed through COBRA Toolbox
- https://github.com/opencobra/cobratoolbox/blob/src/visualization/metabolicCartography/colorSubsystemCD.m
-
- Color every reaction in a specific subsystem
-
- USAGE:
-
-   [newMap] = colorSubsystemCD(map, model, subsystem, color, areaWidth);
-
- INPUTS:
-   map:            File from CellDesigner parsed to MATLAB format
-   model:          COBRA model structure
-   subsystem:      Name of a subsystem as a String
-
- OPTIONAL INPUTS:
-   color:          Color desired for reactions in CAPITALS
-   areaWidth:          Width desired for reactions
-
- OUTPUT:
-   newMap          MATLAB structure of map with reaction modifications
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function newMap = colorSubsystem(map, model, subsystem, color)
-0002 % Modified from colorSubsystemCD as distributed through COBRA Toolbox
-0003 % https://github.com/opencobra/cobratoolbox/blob/src/visualization/metabolicCartography/colorSubsystemCD.m
-0004 %
-0005 % Color every reaction in a specific subsystem
-0006 %
-0007 % USAGE:
-0008 %
-0009 %   [newMap] = colorSubsystemCD(map, model, subsystem, color, areaWidth);
-0010 %
-0011 % INPUTS:
-0012 %   map:            File from CellDesigner parsed to MATLAB format
-0013 %   model:          COBRA model structure
-0014 %   subsystem:      Name of a subsystem as a String
-0015 %
-0016 % OPTIONAL INPUTS:
-0017 %   color:          Color desired for reactions in CAPITALS
-0018 %   areaWidth:          Width desired for reactions
-0019 %
-0020 % OUTPUT:
-0021 %   newMap          MATLAB structure of map with reaction modifications
-0022 if nargin < 4
-0023     color = 'RED';
-0024 end
-0025 
-0026 newMap = map;
-0027 rxnList = model.rxns(ismember([model.subSystems{:}]', subsystem));
-0028 colors = createColorsMap;
-0029 
-0030 index = find(ismember(newMap.rxnName, rxnList));
-0031 for j = index'
-0032     newMap.rxnColor{j, 1} = colors(color);
-0033     %newMap.rxnWidth{j, 1} = areaWidth;
-0034 end
-0035 
-0036 % Use the existence of reactant lines to check if the map has the
-0037 % complete structure, and if so change also secondary lines.
-0038 if any(strcmp('rxnReactantLineColor', fieldnames(newMap))) == 1
-0039     for j = index'
-0040         if ~isempty(newMap.rxnReactantLineColor{j})
-0041             for k = 1:length(newMap.rxnReactantLineColor{j})
-0042                 newMap.rxnReactantLineColor{j, 1}{k, 1} = colors(color);
-0043                 %newMap.rxnReactantLineWidth{j, 1}{k, 1} = areaWidth;
-0044             end
-0045         end
-0046         if ~isempty(newMap.rxnProductLineColor{j})
-0047             for m = 1:1:length(newMap.rxnProductLineColor{j})
-0048                 newMap.rxnProductLineColor{j, 1}{m, 1} = colors(color);
-0049                 %newMap.rxnProductLineWidth{j, 1}{m, 1} = areaWidth;
-0050             end
-0051         end
-0052     end
-0053 end
-0054 
-0055 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/plotting/drawMap.html b/doc/plotting/drawMap.html deleted file mode 100644 index 8175725c3..000000000 --- a/doc/plotting/drawMap.html +++ /dev/null @@ -1,211 +0,0 @@ - - - - Description of drawMap - - - - - - - - - -
Home > plotting > drawMap.m
- - - -

drawMap -

- -

PURPOSE ^

-
drawMap
- -

SYNOPSIS ^

-
function notMapped=drawMap(title,pathway,modelA,conditionA,conditionB,modelB,filename,cutOff,supressOpen)
- -

DESCRIPTION ^

-
 drawMap
-   Imports a previously drawn map of the metabolic network and plots
-   the fluxes on that map. If the pathway contains expression data the log-fold
-   changes are plotted as well
-
-   title           title to be printed on the map
-   pathway         map structure as generated by
-                   constructPathwayFromCelldesigner
-   modelA            model structure for condition A
-   conditionA      flux vector for condition A
-   conditionB        flux vector for condition B (optional)
-   modelB            model structure for condition B (optional, default modelA)
-   filename        exports the map as a pdf (optional)
-   cutOff          only print fluxes where one of the fluxes are above this
-                   value (optional, default 10^-7)
-   supressOpen     true if the pdf file should not be opened (optional, default
-                   false)
-
-   notMapped         the reaction ids that carried a flux in either of the
-                   conditions but that were not present in the metabolic map
-
-   The objective function in modelA is assumed to be the objective function
-   in both cases. If only one flux is supplied then that flux is printed two
-   times in each box.
-
- Usage: notMapped=drawMap(title,pathway,modelA,conditionA,...
-           conditionB,modelB,filename,cutOff,supressOpen)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function notMapped=drawMap(title,pathway,modelA,conditionA,conditionB,modelB,filename,cutOff,supressOpen)
-0002 % drawMap
-0003 %   Imports a previously drawn map of the metabolic network and plots
-0004 %   the fluxes on that map. If the pathway contains expression data the log-fold
-0005 %   changes are plotted as well
-0006 %
-0007 %   title           title to be printed on the map
-0008 %   pathway         map structure as generated by
-0009 %                   constructPathwayFromCelldesigner
-0010 %   modelA            model structure for condition A
-0011 %   conditionA      flux vector for condition A
-0012 %   conditionB        flux vector for condition B (optional)
-0013 %   modelB            model structure for condition B (optional, default modelA)
-0014 %   filename        exports the map as a pdf (optional)
-0015 %   cutOff          only print fluxes where one of the fluxes are above this
-0016 %                   value (optional, default 10^-7)
-0017 %   supressOpen     true if the pdf file should not be opened (optional, default
-0018 %                   false)
-0019 %
-0020 %   notMapped         the reaction ids that carried a flux in either of the
-0021 %                   conditions but that were not present in the metabolic map
-0022 %
-0023 %   The objective function in modelA is assumed to be the objective function
-0024 %   in both cases. If only one flux is supplied then that flux is printed two
-0025 %   times in each box.
-0026 %
-0027 % Usage: notMapped=drawMap(title,pathway,modelA,conditionA,...
-0028 %           conditionB,modelB,filename,cutOff,supressOpen)
-0029 
-0030 if nargin<4
-0031     conditionB=conditionA;
-0032 end
-0033 
-0034 if nargin<5
-0035     modelB=modelA;
-0036 end
-0037 
-0038 if nargin<8
-0039     cutOff=10^-7;
-0040 end
-0041 
-0042 if nargin<9
-0043     supressOpen=false;
-0044 end
-0045 
-0046 if isempty(conditionB)
-0047     conditionB=conditionA;
-0048 end
-0049 
-0050 if isempty(modelB)
-0051     modelB=modelA;
-0052 end
-0053 
-0054 objectiveNames=modelA.rxns(modelA.c~=0);
-0055 objectiveValues=modelA.c(modelA.c~=0);
-0056 
-0057 %Replace all values which are below the cut-off with 0.0
-0058 conditionA(abs(conditionA)<cutOff)=0;
-0059 conditionB(abs(conditionB)<cutOff)=0;
-0060 
-0061 %Get the reactions that could not be mapped
-0062 carriesFlux=union(modelA.rxns,modelB.rxns);
-0063 
-0064 rxnsInModel={};
-0065 %Loop through the pathway structure and get the reaction that can be mapped
-0066 for i=1:numel(pathway.listOfSpecies)
-0067     if strcmp(pathway.listOfSpecies(i).type,'PROTEIN')
-0068         if ~isempty(pathway.listOfSpecies(i).note)
-0069             rxnsInModel=[rxnsInModel;pathway.listOfSpecies(i).note(1)];
-0070         end
-0071     end
-0072 end
-0073 
-0074 %Find all reaction bounds that are "non-standard". Since the default bounds
-0075 %are not indicated in the model structure it is assumed that the maximal
-0076 %bound value is the default one.
-0077 rxnBoundsA=find(modelA.ub~=max(modelA.ub) | (modelA.lb~=-max(modelA.ub) & modelA.rev==1) | (modelA.lb~=0 & modelA.rev==0));
-0078 rxnBoundsB=find(modelB.ub~=max(modelB.ub) | (modelB.lb~=-max(modelB.ub) & modelB.rev==1) | (modelB.lb~=0 & modelB.rev==0));
-0079 
-0080 notMapped=setdiff(carriesFlux,rxnsInModel);
-0081 
-0082 pathway=colorPathway(pathway,modelA.rxns,conditionA,conditionB,cutOff);
-0083 pathway=markPathwayWithFluxes(pathway,modelA.rxns,conditionA,conditionB);
-0084 
-0085 h=figure('Visible','Off');
-0086 drawPathway(pathway,h,cutOff);
-0087 
-0088 %Plot labels and title at pathway map
-0089 plotLabels(h,pathway);
-0090 setTitle(h,pathway,title);
-0091 
-0092 %Plot example box, color example and additional information
-0093 exampleBoxText(1)={'Reaction ID'};
-0094 exampleBoxText(2)={'Condition A'};
-0095 exampleBoxText(3)={'Condition B'};
-0096 if nargin>7
-0097     exampleBoxText(4)={'Other data'};
-0098 end
-0099 
-0100 additionalText={};
-0101 additionalText=[additionalText;{'Objective function'}];
-0102 
-0103 additionalText=[additionalText;{getObjectiveString(true, objectiveNames, objectiveValues)}];
-0104 additionalText=[additionalText;{''}];
-0105 additionalText=[additionalText;{'Constraints (condition A)'}];
-0106 
-0107 counter=numel(additionalText)+1;
-0108 for i=1:length(rxnBoundsA)
-0109     additionalText{counter}=[modelA.rxns{rxnBoundsA(i)} '  [' ...
-0110         num2str([modelA.lb(rxnBoundsA(i)) modelA.ub(rxnBoundsA(i))]) ']'];
-0111     counter=counter+1;
-0112 end
-0113 
-0114 additionalText=[additionalText;{''}];
-0115 additionalText=[additionalText;{'Constraints (condition B)'}];
-0116 
-0117 counter=numel(additionalText)+1;
-0118 for i=1:length(rxnBoundsB)
-0119     additionalText{counter}=[modelB.rxns{rxnBoundsB(i)} '  [' ...
-0120         num2str([modelB.lb(rxnBoundsB(i)) modelB.ub(rxnBoundsB(i))]) ']'];
-0121     counter=counter+1;
-0122 end
-0123 
-0124 plotAdditionalInfo(h, pathway, additionalText, exampleBoxText, 1);
-0125 
-0126 if nargin>5
-0127     if any(filename)
-0128         set(gcf, 'PaperType', 'A4');
-0129         orient landscape;
-0130         print('-dpdf', '-r600', filename);
-0131         fprintf('File saved as %s\n',filename);
-0132     end
-0133 end
-0134 
-0135 if supressOpen==false
-0136     open(filename);
-0137 end
-0138 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/plotting/drawPathway.html b/doc/plotting/drawPathway.html deleted file mode 100644 index 3328522f8..000000000 --- a/doc/plotting/drawPathway.html +++ /dev/null @@ -1,481 +0,0 @@ - - - - Description of drawPathway - - - - - - - - - -
Home > plotting > drawPathway.m
- - - -

drawPathway -

- -

PURPOSE ^

-
drawPathway
- -

SYNOPSIS ^

-
function drawPathway(pathway, h, cutOff, defaultColor)
- -

DESCRIPTION ^

-
 drawPathway
-    Draws a metabolic network to a figure.
-
-   pathway         pathway structure representing the pathway to be drawn
-   handle          handle to a figure (optional)
-   cutOff          the fluxes are only printed if the absolute value of
-                   at least one of the fluxes is above the cutoff value
-                   (optional, default 0)
-   defaultColor    color in Matlab format to be used as the background
-                   color for enzymes if no color is specified in the
-                   pathway structure (optional, default [1 1 1])
-
-   NOTE:   At the moment all text sizes and some positions are hard coded.
-           This means that this code is not appliable for any map
-
- Usage: drawPathway(pathway, handle, cutOff, defaultColor)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 function drawPathway(pathway, h, cutOff, defaultColor)
-0002 % drawPathway
-0003 %    Draws a metabolic network to a figure.
-0004 %
-0005 %   pathway         pathway structure representing the pathway to be drawn
-0006 %   handle          handle to a figure (optional)
-0007 %   cutOff          the fluxes are only printed if the absolute value of
-0008 %                   at least one of the fluxes is above the cutoff value
-0009 %                   (optional, default 0)
-0010 %   defaultColor    color in Matlab format to be used as the background
-0011 %                   color for enzymes if no color is specified in the
-0012 %                   pathway structure (optional, default [1 1 1])
-0013 %
-0014 %   NOTE:   At the moment all text sizes and some positions are hard coded.
-0015 %           This means that this code is not appliable for any map
-0016 %
-0017 % Usage: drawPathway(pathway, handle, cutOff, defaultColor)
-0018 
-0019 if nargin<4
-0020     defaultColor=[1 1 1];
-0021 end
-0022 if nargin<3
-0023     cutOff=0;
-0024 end
-0025 if nargin<2
-0026     if ishandle(gcf)
-0027         h=gcf;
-0028     else
-0029         h=figure();
-0030     end
-0031 end
-0032 
-0033 %Will contain all metabolite info and where to print them
-0034 metText={};
-0035 metX=[];
-0036 metY=[];
-0037 metRec=[];
-0038 
-0039 %Same for reaction text (names, fluxes and maybe other)
-0040 rxnText={};
-0041 rxnX=[];
-0042 rxnY=[];
-0043 rxnLinesX=[];
-0044 rxnLinesY=[];
-0045 rxnRec=[];
-0046 rxnFace=[];
-0047 rxnEdge=[];
-0048 rxnArrows=[];
-0049 rxnArrowsColor=[];
-0050 
-0051 %Expression boxes
-0052 expRec=[];
-0053 expFace=[];
-0054 
-0055 %Lines to enzymes
-0056 enzLinesX=[];
-0057 enzLinesY=[];
-0058 
-0059 %Same for compartments
-0060 compText={};
-0061 compX=[];
-0062 compY=[];
-0063 compRec=[];
-0064 
-0065 %Check if it should plot expression data
-0066 if isfield(pathway.listOfSpecies(1),'orfs')
-0067     drawExpression=true;
-0068 else
-0069     drawExpression=false;
-0070 end
-0071 
-0072 %Get the dimensions of the network
-0073 dimension=getPathwayDimensions(pathway);
-0074 
-0075 %Specify the properties of the figure
-0076 set(h, 'PaperOrientation', 'landscape');
-0077 set(h, 'Color', [1 1 1]);
-0078 xmargin=0.83;
-0079 ymargin=1.32;
-0080 set(h, 'PaperPosition', [xmargin ymargin 29.67743169791-2*xmargin 20.98404194812-2*ymargin]);
-0081 set(h, 'Renderer', 'painters');
-0082 set(h, 'Position', [10 10 1000 700]);
-0083 
-0084 %The height has to be at least the height of the information panel
-0085 %(approximately 3000)
-0086 height=dimension(2)+dimension(4)+200;
-0087 height=max(height,3000);
-0088 
-0089 axes('ytick',[],'ydir','reverse','xtick',[],'ycolor',[1 1 1], 'xcolor',...
-0090     [1 1 1],'position',[0 0 1 1], 'xLim',[dimension(1)-40 dimension(1)+dimension(3)+800],...
-0091     'yLim', [dimension(2)-200 height]);
-0092 daspect([1,1,1]);
-0093 
-0094 %Loops through the compartments.
-0095 for i=1:length(pathway.listOfCompartments)
-0096     position=[pathway.listOfCompartments(1,i).x pathway.listOfCompartments(1,i).y...
-0097         pathway.listOfCompartments(1,i).w pathway.listOfCompartments(1,i).h];
-0098     compRec=[compRec;position];
-0099     compText=[compText;upper(pathway.listOfCompartments(i).name)];
-0100     compX=[compX;position(1)+0.5*position(3)];
-0101     compY=[compY;position(2)+position(4)-70];
-0102 end
-0103 
-0104 %Get positions of lines
-0105 for i=1:length(pathway.listOfReactions)
-0106     for j=1:length(pathway.listOfReactions(i).componentList)
-0107         %The line is always drawn from the middle to the component
-0108         middle=pathway.listOfReactions(i).middlePoint;
-0109         x(1)=middle(1);
-0110         y(1)=middle(2);
-0111         x(2)=pathway.listOfReactions(i).componentList(j).anchor(1);
-0112         y(2)=pathway.listOfReactions(i).componentList(j).anchor(2);
-0113         
-0114         %Check to see if a line or an arrow should be drawn
-0115         if strcmpi(pathway.listOfReactions(i).componentList(j).toArrow,'true')
-0116             rxnArrows=[rxnArrows;x(1) y(1) x(2) y(2)];
-0117             
-0118             %Draw a red arrow if it's a base product
-0119             if strcmpi(pathway.listOfReactions(i).componentList(j).baseProduct,'true')
-0120                 rxnArrowsColor=[rxnArrowsColor;1 0 0];
-0121             else
-0122                 rxnArrowsColor=[rxnArrowsColor;0 0 0];
-0123             end
-0124         else
-0125             %If the component is an enzyme then a different line should be
-0126             %used
-0127             if strcmpi(pathway.listOfReactions(i).componentList(j).type,'ENZYME')
-0128                 enzLinesX=[enzLinesX;x(1) x(2)];
-0129                 enzLinesY=[enzLinesY;y(1) y(2)];
-0130             else
-0131                 rxnLinesX=[rxnLinesX;x(1) x(2)];
-0132                 rxnLinesY=[rxnLinesY;y(1) y(2)];
-0133             end
-0134         end
-0135     end
-0136 end
-0137 
-0138 %Loops through the species
-0139 for i=1:length(pathway.listOfSpecies)
-0140     %Species should be represented with ellipses and enzymes with
-0141     %rectangles
-0142     position=[pathway.listOfSpecies(i).x pathway.listOfSpecies(i).y...
-0143         pathway.listOfSpecies(i).w pathway.listOfSpecies(i).h];
-0144     if strcmpi(pathway.listOfSpecies(i).type, 'SIMPLE_MOLECULE')
-0145         metRec=[metRec;position];
-0146         metText=[metText;pathway.listOfSpecies(i).name];
-0147         metX=[metX;position(1)+0.3*position(3)];
-0148         metY=[metY;position(2)+0.5*position(4)];
-0149     end
-0150     if strcmpi(pathway.listOfSpecies(i).type, 'PROTEIN')
-0151         %The color of the enzyme can be specified in the pathway object.
-0152         %The default color is used if there is no 'color' field present.
-0153         %If neither of the fluxes are above the cutoff value, then use the
-0154         %default color
-0155         faceColor=defaultColor;
-0156         if isfield(pathway.listOfSpecies(i),'color')
-0157             if any(pathway.listOfSpecies(i).color)
-0158                 %Check that the fluxes are specified
-0159                 if isfield(pathway.listOfSpecies(i),'flux') && isfield(pathway.listOfSpecies(i),'referenceFlux')
-0160                     %Check that the value of one of the fluxes is above the cutoff value
-0161                     if abs(pathway.listOfSpecies(i).referenceFlux)>=cutOff || abs(pathway.listOfSpecies(i).flux)>=cutOff
-0162                         faceColor=pathway.listOfSpecies(i).color;
-0163                     end
-0164                 end
-0165             end
-0166         end
-0167         
-0168         %If the reaction is associated with a sign change and either of the
-0169         %fluxes are larger than the cutoff value, then use a different frame
-0170         edgeColor=[0 0 0];
-0171         if isfield(pathway.listOfSpecies(i),'signChange')
-0172             if any(pathway.listOfSpecies(i).signChange)
-0173                 if (pathway.listOfSpecies(i).signChange==true) && (abs(pathway.listOfSpecies(i).referenceFlux)>=cutOff || abs(pathway.listOfSpecies(i).flux)>=cutOff)
-0174                     edgeColor=[1 0.6 0.2];
-0175                 end
-0176             end
-0177         end
-0178         
-0179         rxnFace=[rxnFace;faceColor];
-0180         rxnEdge=[rxnEdge;edgeColor];
-0181         
-0182         %Draw smaller boxes if expression data should also be printed
-0183         if drawExpression==true
-0184             rxnRec=[rxnRec;position-[0 0 40 0]];
-0185             
-0186             %Draw rectangles representing each gene. Max 8 circles are used.
-0187             %Their width is hardcoded and so is the width of the area where
-0188             %they are printed (40)
-0189             if any(pathway.listOfSpecies(i).expA)
-0190                 %Calculate the position of the dots. 4 in each column.
-0191                 firstFourX=pathway.listOfSpecies(i).x+pathway.listOfSpecies(i).w-34;
-0192                 fourY=pathway.listOfSpecies(i).y:pathway.listOfSpecies(i).h/4:pathway.listOfSpecies(i).y+pathway.listOfSpecies(i).h;
-0193                 
-0194                 nExp=numel(pathway.listOfSpecies(i).expA);
-0195                 
-0196                 %One log10-fold change is total up or down
-0197                 colorCodes=getColorCodes(pathway.listOfSpecies(i).expA, pathway.listOfSpecies(i).expB);
-0198                 
-0199                 %Plot the circles
-0200                 for j=1:min(nExp,4)
-0201                     expRec=[expRec;firstFourX fourY(j) 16 pathway.listOfSpecies(i).h/4];
-0202                     expFace=[expFace;colorCodes{j}];
-0203                 end
-0204                 
-0205                 %If a second row is needed
-0206                 if nExp>4
-0207                     secondFourX=pathway.listOfSpecies(i).x+pathway.listOfSpecies(i).w-16;
-0208                     for j=5:min(nExp,8)
-0209                         expRec=[expRec;secondFourX fourY(j-4) 16 pathway.listOfSpecies(i).h/4];
-0210                         expFace=[expFace;colorCodes{j}];
-0211                     end
-0212                 end
-0213             end
-0214         else
-0215             rxnRec=[rxnRec;position];
-0216         end
-0217         
-0218         %If no fluxes are specified then should only the name be printed.
-0219         %Flux values should only be printed if at least one of the fluxes
-0220         %is above the cutoff value
-0221         textToPrint={};
-0222         
-0223         %NOTE:  This is done since I know that I have names including '_' which is a reserved
-0224         %       character in LaTeX. This should be done more systematically
-0225         
-0226         %NOTE:  The notation used means that only flux values with with less than
-0227         %       nine characters can be used
-0228         
-0229         textToPrint{1,1}=strrep(pathway.listOfSpecies(i).name,'_','\_');
-0230         
-0231         %Check that the fluxes are specified
-0232         %NOTE: Should you only print if there are two fluxes?
-0233         if isfield(pathway.listOfSpecies(i),'flux') && isfield(pathway.listOfSpecies(i),'referenceFlux')
-0234             %Check that the value of one of the fluxes is above the cutoff value
-0235             if ~isempty(pathway.listOfSpecies(i).flux) && ~isempty(pathway.listOfSpecies(i).referenceFlux)
-0236                 if abs(pathway.listOfSpecies(i).referenceFlux)>=cutOff || abs(pathway.listOfSpecies(i).flux)>=cutOff
-0237                     textToPrint{2,1}=num2str(pathway.listOfSpecies(i).flux,'%0.4g');
-0238                     textToPrint{3,1}=num2str(pathway.listOfSpecies(i).referenceFlux,'%0.4g');
-0239                 end
-0240             end
-0241         end
-0242         
-0243         xPos=ones(numel(textToPrint),1)*(position(1)+3);
-0244         distance=position(4)/(numel(textToPrint)+1);
-0245         yPos=position(2)+distance:distance:(position(2)+position(4)-distance);
-0246         
-0247         rxnText=[rxnText;textToPrint];
-0248         rxnX=[rxnX;xPos];
-0249         rxnY=[rxnY;yPos'];
-0250     end
-0251 end
-0252 
-0253 %*** Print everything ***
-0254 
-0255 %Compartment rectangles
-0256 for i=1:size(compRec,1)
-0257     rectangle('edgecolor',[1 0.8 0.2], 'facecolor', [1 0.91 0.55], 'linewidth', 2, 'curvature', [0.05 0.05],...
-0258         'position',compRec(i,:));
-0259     rectangle('edgecolor',[1 0.8 0.2], 'facecolor', [1 1 1], 'linewidth', 1, 'curvature', [0.05 0.05],...
-0260         'position',compRec(i,:)+[12 12 -24 -24]);
-0261 end
-0262 
-0263 %Reaction lines
-0264 line(rxnLinesX',rxnLinesY','linewidth',0.1,'color',[0 0 0]);
-0265 
-0266 %Arrow lines
-0267 hold on;
-0268 for i=1:size(rxnArrows,1)
-0269     plotArrow(rxnArrows(i,1),rxnArrows(i,2),rxnArrows(i,3),rxnArrows(i,4),'linewidth',0.1,'edgecolor',rxnArrowsColor(i,:),'facecolor',rxnArrowsColor(i,:));
-0270 end
-0271 hold off;
-0272 
-0273 %Enzyme lines
-0274 line(enzLinesX',enzLinesY','marker','o','markeredgecolor',[0 0 0],'markersize',0.5,...
-0275     'markerfacecolor',[1 0.969 0.922],'linewidth',0.1,'color',[0 0 0]);
-0276 
-0277 %Metabolite rectangles
-0278 for i=1:size(metRec,1)
-0279     rectangle('edgecolor', [0 0 0], 'facecolor', [1 1 0.78], 'curvature', [0.8 0.8],...
-0280         'position',metRec(i,:),'linewidth',0.1);
-0281 end
-0282 
-0283 %Reaction rectangles
-0284 for i=1:size(rxnRec,1)
-0285     rectangle('edgecolor', rxnEdge(i,:), 'facecolor', rxnFace(i,:), 'linewidth',0.1,...
-0286         'curvature', [0.1 0.1], 'position',rxnRec(i,:));
-0287 end
-0288 
-0289 %Expression rectangles
-0290 for i=1:size(expRec,1)
-0291     rectangle('facecolor', expFace(i,:), 'linewidth',0.1, 'curvature', [0.1 0.1],...
-0292         'position',expRec(i,:));
-0293 end
-0294 
-0295 %Metabolite text
-0296 %Temporary thing to get it right for small networks as well. Should be
-0297 %calculated better!
-0298 if dimension(3)<5000
-0299     textSize=3;
-0300 else
-0301     textSize=0.5;
-0302 end
-0303 
-0304 text(metX,metY,metText,'fontname','Small Fonts','fontsize',textSize,'interpreter','tex',...
-0305     'HorizontalAlignment','center','verticalalignment','middle');
-0306 
-0307 %Reaction text
-0308 text(rxnX,rxnY,rxnText,'fontname','Small Fonts','fontsize',textSize,'interpreter','tex',...
-0309     'verticalalignment','middle','HorizontalAlignment','left');
-0310 
-0311 %Compartment text. The text is centered and at the bottom of the compartment
-0312 text(compX, compY,compText,'fontname','Small Fonts','fontsize',7,'interpreter','none',...
-0313     'HorizontalAlignment','center','verticalalignment','middle');
-0314 end
-0315 
-0316 function handles = plotArrow( x1,y1,x2,y2,varargin )
-0317 %
-0318 % plotArrow - plots an arrow to the current plot
-0319 %
-0320 % format:   handles = plotArrow( x1,y1,x2,y2 [,options...] )
-0321 %
-0322 % input:    x1,y1   - starting point
-0323 %           x2,y2   - end point
-0324 %           options - come as pairs of "property","value" as defined for "line" and "patch"
-0325 %                     controls, see matlab help for listing of these properties.
-0326 %                     note that not all properties where added, one might add them at the end of this file.
-0327 %
-0328 %                     additional options are:
-0329 %                     'headwidth':  relative to complete arrow size, default value is 0.07
-0330 %                     'headheight': relative to complete arrow size, default value is 0.15
-0331 %                     (encoded are maximal values if pixels, for the case that the arrow is very long)
-0332 %
-0333 % output:   handles - handles of the graphical elements building the arrow
-0334 %
-0335 % Example:  plotArrow( -1,-1,15,12,'linewidth',2,'color',[0.5 0.5 0.5],'facecolor',[0.5 0.5 0.5] );
-0336 %           plotArrow( 0,0,5,4,'linewidth',2,'headwidth',0.25,'headheight',0.33 );
-0337 %           plotArrow;   % will launch demo
-0338 
-0339 % =============================================
-0340 % constants (can be edited)
-0341 % =============================================
-0342 %NOTE: These should be 100 times smaller
-0343 alpha       = 15;   % head length
-0344 beta        = 7;   % head width
-0345 max_length  = 11;
-0346 %max_width   = 7;
-0347 
-0348 % =============================================
-0349 % check if head properties are given
-0350 % =============================================
-0351 % if ratio is always fixed, this section can be removed!
-0352 if ~isempty( varargin )
-0353     for c = 1:floor(length(varargin)/2)
-0354         switch lower(varargin{c*2-1})
-0355             % head properties - do nothing, since handled above already
-0356             case 'headheight',alpha = max( min( varargin{c*2},1 ),0.01 );
-0357             case 'headwidth', beta = max( min( varargin{c*2},1 ),0.01 );
-0358         end
-0359     end
-0360 end
-0361 
-0362 % =============================================
-0363 % calculate the arrow head coordinates
-0364 % =============================================
-0365 den         = x2 - x1 + eps;                                % make sure no devision by zero occurs
-0366 teta        = atan( (y2-y1)/den ) + pi*(x2<x1) - pi/2;      % angle of arrow
-0367 cs          = cos(teta);                                    % rotation matrix
-0368 ss          = sin(teta);
-0369 R           = [cs -ss;ss cs];
-0370 line_length = sqrt( (y2-y1)^2 + (x2-x1)^2 );                % sizes
-0371 head_length = min( line_length*alpha,max_length );
-0372 head_width  = min( line_length*beta,max_length );
-0373 x0          = x2*cs + y2*ss;                                % build head coordinats
-0374 y0          = -x2*ss + y2*cs;
-0375 coords      = R*[x0 x0+head_width/2 x0-head_width/2; y0 y0-head_length y0-head_length];
-0376 
-0377 % =============================================
-0378 % plot arrow  (= line + patch of a triangle)
-0379 % =============================================
-0380 h1          = plot( [x1,x2],[y1,y2],'k' );
-0381 h2          = patch( coords(1,:),coords(2,:),[0 0 0] );
-0382 
-0383 % =============================================
-0384 % return handles
-0385 % =============================================
-0386 handles = [h1 h2];
-0387 
-0388 % =============================================
-0389 % check if styling is required
-0390 % =============================================
-0391 % if no styling, this section can be removed!
-0392 if ~isempty( varargin )
-0393     for c = 1:floor(length(varargin)/2)
-0394         switch lower(varargin{c*2-1})
-0395             
-0396             % only patch properties
-0397             case 'edgecolor',   set( h2,'EdgeColor',varargin{c*2} );
-0398             case 'facecolor',   set( h2,'FaceColor',varargin{c*2} );
-0399             case 'facelighting',set( h2,'FaceLighting',varargin{c*2} );
-0400             case 'edgelighting',set( h2,'EdgeLighting',varargin{c*2} );
-0401                 
-0402                 % only line properties
-0403             case 'color'    , set( h1,'Color',varargin{c*2} );
-0404                 
-0405                 % shared properties
-0406             case 'linestyle', set( handles,'LineStyle',varargin{c*2} );
-0407             case 'linewidth', set( handles,'LineWidth',varargin{c*2} );
-0408             case 'parent',    set( handles,'parent',varargin{c*2} );
-0409                 
-0410                 % head properties - do nothing, since handled above already
-0411             case 'headwidth',
-0412             case 'headheight',
-0413                 
-0414         end
-0415     end
-0416 end
-0417 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/plotting/getColorCodes.html b/doc/plotting/getColorCodes.html deleted file mode 100644 index 67b68cb5e..000000000 --- a/doc/plotting/getColorCodes.html +++ /dev/null @@ -1,208 +0,0 @@ - - - - Description of getColorCodes - - - - - - - - - -
Home > plotting > getColorCodes.m
- - - -

getColorCodes -

- -

PURPOSE ^

-
getColorCodes
- -

SYNOPSIS ^

-
function [colorCodes, signChange, errorFlag]= getColorCodes(referenceFluxes, fluxes, maxChange, defaultColor, upColor, downColor)
- -

DESCRIPTION ^

-
 getColorCodes
-    Calculates the coloring for a number of fluxes by comparing them to
-   reference fluxes.
-
-   referenceFluxes     vector of reference fluxes
-   fluxes              vector of fluxes. The number of elements in fluxes
-                       and referenceFluxes must be equal
-   maxChange           the logfold increase or decrease that corresponds
-                       to full negative or full positive coloring. Must
-                       be a positive value (optional, default 1)
-   defaultColor        a color in Matlab format to be used if there are no
-                       changes between the fluxes. This color is also used to
-                       calculate the transition between the colors for up and
-                       down regulated fluxes (optional, default [1 1 1])
-   upColor             a color in Matlab format to be used if the flux is
-                       larger than the reference flux (optional, default [0 1 0])
-   downColor           a color in Matlab format to be used if the flux is
-                       smaller than the reference flux (optional, default [1 0 0])
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 function [colorCodes, signChange, errorFlag]= getColorCodes(referenceFluxes, fluxes, maxChange, defaultColor, upColor, downColor)
-0002 % getColorCodes
-0003 %    Calculates the coloring for a number of fluxes by comparing them to
-0004 %   reference fluxes.
-0005 %
-0006 %   referenceFluxes     vector of reference fluxes
-0007 %   fluxes              vector of fluxes. The number of elements in fluxes
-0008 %                       and referenceFluxes must be equal
-0009 %   maxChange           the logfold increase or decrease that corresponds
-0010 %                       to full negative or full positive coloring. Must
-0011 %                       be a positive value (optional, default 1)
-0012 %   defaultColor        a color in Matlab format to be used if there are no
-0013 %                       changes between the fluxes. This color is also used to
-0014 %                       calculate the transition between the colors for up and
-0015 %                       down regulated fluxes (optional, default [1 1 1])
-0016 %   upColor             a color in Matlab format to be used if the flux is
-0017 %                       larger than the reference flux (optional, default [0 1 0])
-0018 %   downColor           a color in Matlab format to be used if the flux is
-0019 %                       smaller than the reference flux (optional, default [1 0 0])
-0020 
-0021 %   colorCodes          array list of colors in Matlab format in the same
-0022 %                       order as the fluxes
-0023 %   signChange          array list of boolean values where true indicates
-0024 %                       that there has been a sign change between the
-0025 %                       fluxes. Reactions with sign changes are not
-0026 %                       colored, but rather marked in another way. The
-0027 %                       order correspondes to the order of the fluxes
-0028 %   errorFlag           true if there has been an error
-0029 %
-0030 % Usage: [colorCodes, signChange, errorFlag]=getColorCodes(referenceFluxes,...
-0031 %           fluxes, maxChange, defaultColor, upColor, downColor)
-0032 
-0033 if nargin<6
-0034     downColor=[1 0 0];
-0035 end
-0036 if nargin<5
-0037     upColor=[0 1 0];
-0038 end
-0039 if nargin<4
-0040     defaultColor=[1 1 1];
-0041 end
-0042 if nargin<3
-0043     maxChange=1;
-0044 end
-0045 
-0046 %Checks that the flux vector and the reference flux vector have the same
-0047 %number of elements
-0048 if length(fluxes)~=length(referenceFluxes)
-0049     colorCodes={};
-0050     signChange={};
-0051     errorFlag=1;
-0052     fprintf('fluxes and referenceFluxes must have the same dimensions');
-0053     return;
-0054 end
-0055 
-0056 %Loops through the fluxes. If the reference flux is 0, then mark as
-0057 %upColor, if the flux is 0 then mark as downColor, and if both fluxes are 0
-0058 %then mark as defaultColor
-0059 for i=1:length(fluxes)
-0060     signChange{i}=false;
-0061     
-0062     if referenceFluxes(i)==0 || fluxes(i)==0
-0063         if referenceFluxes(i)==0 && fluxes(i)==0
-0064             colorCodes{i}=defaultColor;
-0065         else
-0066             if referenceFluxes(i)==0
-0067                 colorCodes{i}=upColor;
-0068             else
-0069                 colorCodes{i}=downColor;
-0070             end
-0071         end
-0072     else
-0073         %At the moment a negative flux that gets more negative is counted
-0074         %as being upregulated. This might be counter intuitive.
-0075         logvalue=log10(abs(fluxes(i))/abs(referenceFluxes(i)));
-0076         
-0077         %If there is a sign change
-0078         if fluxes(i)*referenceFluxes(i)<0
-0079             colorCodes{i}=defaultColor;
-0080             signChange{i}=true;
-0081         else
-0082             colorCodes{i}=getColor(logvalue, defaultColor, upColor, downColor, maxChange);
-0083         end
-0084     end
-0085 end
-0086 end
-0087 
-0088 function colorValue=getColor(logvalue, defaultColor, upColor, downColor, maxChange)
-0089 % getColor
-0090 %   Calculates the color for a specified logvalue.
-0091 %
-0092 %   logvalue            the logfold increase or desrease of a flux
-0093 %   compared to the
-0094 %                       corresponding reference flux. Must be a
-0095 %                       positive value
-0096 %   defaultColor        a color in Matlab format to be used if
-0097 %   there are no
-0098 %                       changes between the fluxes. This color is
-0099 %                       also used to calculate the transition
-0100 %                       between the colors for up and down
-0101 %                       regulated fluxes
-0102 %   upColor             a color in Matlab format to be used if the
-0103 %   flux is
-0104 %                       larger than the reference flux
-0105 %   downColor           a color in Matlab format to be used if the
-0106 %   flux is
-0107 %                       smaller than the reference flux
-0108 %   maxChange           the logfold increase or decrease that
-0109 %   corresponds
-0110 %                       to full negative or full positive coloring
-0111 %
-0112 %   colorValue          vector with the calculated color
-0113 %
-0114 % Usage: colorValue=getColor(logvalue, defaultColor, upColor,
-0115 %   downColor, maxChange)
-0116 
-0117 %If the flux has decreased
-0118 if logvalue<0
-0119     %If the flux is lower than 10^-maxChange of the original then
-0120     %color as downColor
-0121     if logvalue<-maxChange
-0122         colorValue=downColor;
-0123     else
-0124         %The color is linear from defaultColor to downColor
-0125         colorValue=[defaultColor(1)+(downColor(1)-defaultColor(1))*logvalue/(-maxChange)...
-0126             defaultColor(2)+(downColor(2)-defaultColor(2))*logvalue/(-maxChange)...
-0127             defaultColor(3)+(downColor(3)-defaultColor(3))*logvalue/(-maxChange)];
-0128     end
-0129     %If it has increased
-0130 else
-0131     %If the flux is higher than 10^maxChange times the original
-0132     %then color green
-0133     if logvalue>maxChange
-0134         colorValue=upColor;
-0135     else
-0136         %The color is linear from defaultColor to upColor
-0137         colorValue=[defaultColor(1)+(upColor(1)-defaultColor(1))*logvalue/(maxChange)...
-0138             defaultColor(2)+(upColor(2)-defaultColor(2))*logvalue/(maxChange)...
-0139             defaultColor(3)+(upColor(3)-defaultColor(3))*logvalue/(maxChange)];
-0140     end
-0141 end
-0142 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/plotting/getObjectiveString.html b/doc/plotting/getObjectiveString.html deleted file mode 100644 index 190f91cf5..000000000 --- a/doc/plotting/getObjectiveString.html +++ /dev/null @@ -1,114 +0,0 @@ - - - - Description of getObjectiveString - - - - - - - - - -
Home > plotting > getObjectiveString.m
- - - -

getObjectiveString -

- -

PURPOSE ^

-
getObjectiveString
- -

SYNOPSIS ^

-
function objectiveString = getObjectiveString(max, objectiveNames, objectiveValues)
- -

DESCRIPTION ^

-
 getObjectiveString
-   Returns a string representing the objective function (e.g. 'MAX Growth
-   - 0.5 HXT4').
-
-   max                 true if the objective function should be maximized
-   objectiveNames      cell array of reaction names
-   objectiveValues     the corresponding coefficients for each reaction
-
-   objectiveString     the calculated objective function
-
- Usage: objectiveString = getObjectiveString(max, objectiveNames,
-           objectiveValues)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function objectiveString = getObjectiveString(max, objectiveNames, objectiveValues)
-0002 % getObjectiveString
-0003 %   Returns a string representing the objective function (e.g. 'MAX Growth
-0004 %   - 0.5 HXT4').
-0005 %
-0006 %   max                 true if the objective function should be maximized
-0007 %   objectiveNames      cell array of reaction names
-0008 %   objectiveValues     the corresponding coefficients for each reaction
-0009 %
-0010 %   objectiveString     the calculated objective function
-0011 %
-0012 % Usage: objectiveString = getObjectiveString(max, objectiveNames,
-0013 %           objectiveValues)
-0014 
-0015 objectiveString='';
-0016 
-0017 if max==true
-0018     objectiveString=[objectiveString 'MAX: '];
-0019 else
-0020     objectiveString=[objectiveString 'MIN: '];
-0021 end
-0022 
-0023 %Loops through the reactions
-0024 for i=1:length(objectiveNames)
-0025     %Add no sign if it's the first reaction
-0026     if i>1
-0027         if objectiveValues(i)==1
-0028             objectiveString=[objectiveString ' + ' objectiveNames{i}];
-0029             continue;
-0030         end
-0031         if objectiveValues(i)==-1
-0032             objectiveString=[objectiveString ' - ' objectiveNames{i}];
-0033             continue;
-0034         end
-0035         if objectiveValues(i)>=0
-0036             objectiveString=[objectiveString ' + ' num2str(objectiveValues(i)) ' ' objectiveNames{i}];
-0037         else
-0038             objectiveString=[objectiveString ' - ' num2str(abs(objectiveValues(i))) ' ' objectiveNames{i}];
-0039         end
-0040     else
-0041         if objectiveValues(i)==1
-0042             objectiveString=[objectiveString objectiveNames{i}];
-0043             continue;
-0044         end
-0045         if objectiveValues(i)==-1
-0046             objectiveString=[objectiveString '- ' objectiveNames{i}];
-0047             continue;
-0048         end
-0049         if objectiveValues(i)>=0
-0050             objectiveString=[objectiveString num2str(objectiveValues(i)) ' ' objectiveNames{i}];
-0051         else
-0052             objectiveString=[objectiveString '- ' num2str(abs(objectiveValues(i))) ' ' objectiveNames{i}];
-0053         end
-0054     end
-0055 end
-0056 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/plotting/index.html b/doc/plotting/index.html deleted file mode 100644 index 60a564fa0..000000000 --- a/doc/plotting/index.html +++ /dev/null @@ -1,29 +0,0 @@ - - - - Index for Directory plotting - - - - - - - - - - -
< Master indexIndex for plotting >
- -

Index for plotting

- -

Matlab files in this directory:

- -
 colorSubsystemModified from colorSubsystemCD as distributed through COBRA Toolbox
 drawMapdrawMap
 drawPathwaydrawPathway
 getColorCodesgetColorCodes
 getObjectiveStringgetObjectiveString
 plotAdditionalInfoplotAdditionalInfo
 plotLabelsplotLabels
 setColorToMapRxnsUSAGE:
 setOmicDataToRxnsUSAGE:
 setTitleplotLabels
- - - - -
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/plotting/plotAdditionalInfo.html b/doc/plotting/plotAdditionalInfo.html deleted file mode 100644 index 5cd902259..000000000 --- a/doc/plotting/plotAdditionalInfo.html +++ /dev/null @@ -1,189 +0,0 @@ - - - - Description of plotAdditionalInfo - - - - - - - - - -
Home > plotting > plotAdditionalInfo.m
- - - -

plotAdditionalInfo -

- -

PURPOSE ^

-
plotAdditionalInfo
- -

SYNOPSIS ^

-
function plotAdditionalInfo(handle, pathway, additionalText, exampleBoxText,maxChange, defaultColor, upColor, downColor)
- -

DESCRIPTION ^

-
 plotAdditionalInfo
-    Plots some additional information in a figure.
-
-   handle              handle to the figure to plot the information on
-   pathway             pathway structure of the metabolic network
-   additionalText      array list with additional text to print (e.g.
-                       fluxes or constraints)
-   exampleBoxText      array list of text to put in an example box. The
-                       text should explain what is printed in the enzyme
-                       boxes
-   maxChange           the logfold increase or decrease that corresponds
-                       to full negative or full positive coloring. Must
-                       be a positive value (optional, default 1)
-   defaultColor        a color in Matlab format to be used if there are no
-                       changes between the fluxes. This color is also used to 
-                       calculate the transition between the colors for up and
-                       down regulated fluxes (optional, default [1 1 1])
-   upColor             a color in Matlab format to be used if the flux is 
-                       larger than the reference flux (optional, default [0 1 0])
-   downColor           a color in Matlab format to be used if the flux is 
-                       smaller than the reference flux (optional, default [1 0
-                       0])
-
-   NOTE: At the moment the positions of the text/figures are (semi-)hard
-           coded.
-
- Usage:  errorFlag = plotAdditionalInfo(handle, additionalText, exampleBoxText,...
-               maxChange, defaultColor, upColor, downColor)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function plotAdditionalInfo(handle, pathway, additionalText, exampleBoxText,...
-0002     maxChange, defaultColor, upColor, downColor)
-0003 % plotAdditionalInfo
-0004 %    Plots some additional information in a figure.
-0005 %
-0006 %   handle              handle to the figure to plot the information on
-0007 %   pathway             pathway structure of the metabolic network
-0008 %   additionalText      array list with additional text to print (e.g.
-0009 %                       fluxes or constraints)
-0010 %   exampleBoxText      array list of text to put in an example box. The
-0011 %                       text should explain what is printed in the enzyme
-0012 %                       boxes
-0013 %   maxChange           the logfold increase or decrease that corresponds
-0014 %                       to full negative or full positive coloring. Must
-0015 %                       be a positive value (optional, default 1)
-0016 %   defaultColor        a color in Matlab format to be used if there are no
-0017 %                       changes between the fluxes. This color is also used to
-0018 %                       calculate the transition between the colors for up and
-0019 %                       down regulated fluxes (optional, default [1 1 1])
-0020 %   upColor             a color in Matlab format to be used if the flux is
-0021 %                       larger than the reference flux (optional, default [0 1 0])
-0022 %   downColor           a color in Matlab format to be used if the flux is
-0023 %                       smaller than the reference flux (optional, default [1 0
-0024 %                       0])
-0025 %
-0026 %   NOTE: At the moment the positions of the text/figures are (semi-)hard
-0027 %           coded.
-0028 %
-0029 % Usage:  errorFlag = plotAdditionalInfo(handle, additionalText, exampleBoxText,...
-0030 %               maxChange, defaultColor, upColor, downColor)
-0031 
-0032 if nargin<8
-0033     downColor=[1 0 0];
-0034 end
-0035 if nargin<7
-0036     upColor=[0 1 0];
-0037 end
-0038 if nargin<6
-0039     defaultColor=[1 1 1];
-0040 end
-0041 if nargin<5
-0042     maxChange=1;
-0043 end
-0044 
-0045 %Finds the the dimensions of the metabolic network. The additional
-0046 %information will be positioned relative to that object.
-0047 dimension=getPathwayDimensions(pathway);
-0048 
-0049 %Plots the example box
-0050 rectangle('edgecolor',[0 0 0], 'facecolor', defaultColor, 'linewidth', 1,...
-0051     'position', [dimension(1)+dimension(3)+100 100 700 320],'curvature', [0.1 0.1]);
-0052 handle=text(dimension(1)+dimension(3)+100+6, 100+0.5*320,...
-0053     exampleBoxText,'fontname','Small Fonts','fontsize',2,...
-0054     'interpreter', 'tex','verticalalignment','middle','HorizontalAlignment','left');
-0055 handle=text(dimension(1)+dimension(3)+300+126, 20,...
-0056     'EXAMPLE:','fontname','Small Fonts','fontsize',4,...
-0057     'interpreter', 'tex','HorizontalAlignment','center','verticalalignment','middle');
-0058 
-0059 %Calculates 10 colors between upColor and defaultColor The color is linear
-0060 %from the upColor to the defaultColor
-0061 colorValues=[];
-0062 for i=1:11
-0063     logvalue=maxChange-(i-1)*0.1*maxChange;
-0064     colorValues=[colorValues;...
-0065         [defaultColor(1)+(upColor(1)-defaultColor(1))*logvalue/(maxChange)...
-0066         defaultColor(2)+(upColor(2)-defaultColor(2))*logvalue/(maxChange)...
-0067         defaultColor(3)+(upColor(3)-defaultColor(3))*logvalue/(maxChange)]];
-0068 end
-0069 %The color is linear from the defaultColor to downColor
-0070 for i=1:10
-0071     logvalue=i*0.1*maxChange;
-0072     colorValues=[colorValues;...
-0073         [defaultColor(1)+(downColor(1)-defaultColor(1))*logvalue/(maxChange)...
-0074         defaultColor(2)+(downColor(2)-defaultColor(2))*logvalue/(maxChange)...
-0075         defaultColor(3)+(downColor(3)-defaultColor(3))*logvalue/(maxChange)]];
-0076 end
-0077 
-0078 %Draw lines that represent the different colors
-0079 handle=text(dimension(1)+dimension(3)+100, 560,...
-0080     'log10(|condition A|/|condition B|)','fontname','Small Fonts','fontsize',3,...
-0081     'interpreter', 'tex','HorizontalAlignment','left','verticalalignment','middle');
-0082 lengthLine=40;
-0083 startX=dimension(1)+dimension(3)+150;
-0084 
-0085 startY=650;
-0086 width=6;
-0087 for i=1:size(colorValues,1)
-0088     line([startX; startX],[startY+(i-1)*lengthLine; startY+i*lengthLine],'color',colorValues(i,:),'linewidth',width);
-0089 end
-0090 
-0091 handle=text(startX+3*width, startY,...
-0092     ['-  ' num2str(maxChange)],'fontname','Small Fonts','fontsize',3,...
-0093     'interpreter', 'tex','HorizontalAlignment','left','verticalalignment','middle');
-0094 
-0095 handle=text(startX+3*width, startY+5.5*lengthLine,...
-0096     ['-  ' num2str(maxChange/2)],'fontname','Small Fonts','fontsize',3,...
-0097     'interpreter', 'tex','HorizontalAlignment','left','verticalalignment','middle');
-0098 
-0099 handle=text(startX+3*width, startY+10.5*lengthLine,...
-0100     ['-  0'],'fontname','Small Fonts','fontsize',3,...
-0101     'interpreter', 'tex','HorizontalAlignment','left','verticalalignment','middle');
-0102 
-0103 handle=text(startX+3*width, startY+15.5*lengthLine,...
-0104     ['-  -' num2str(maxChange/2)],'fontname','Small Fonts','fontsize',3,...
-0105     'interpreter', 'tex','HorizontalAlignment','left','verticalalignment','middle');
-0106 
-0107 handle=text(startX+3*width, startY+20.5*lengthLine,...
-0108     ['-  -' num2str(maxChange)],'fontname','Small Fonts','fontsize',3,...
-0109     'interpreter', 'tex','HorizontalAlignment','left','verticalalignment','middle');
-0110 
-0111 %Plots the additional text
-0112 handle=text(dimension(1)+dimension(3)+100, 1800,...
-0113     additionalText,'fontname','Small Fonts','fontsize',3,...
-0114     'interpreter', 'none','verticalalignment','top','HorizontalAlignment','left');
-0115 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/plotting/plotLabels.html b/doc/plotting/plotLabels.html deleted file mode 100644 index 1d1334079..000000000 --- a/doc/plotting/plotLabels.html +++ /dev/null @@ -1,76 +0,0 @@ - - - - Description of plotLabels - - - - - - - - - -
Home > plotting > plotLabels.m
- - - -

plotLabels -

- -

PURPOSE ^

-
plotLabels
- -

SYNOPSIS ^

-
function plotLabels(handle,pathway)
- -

DESCRIPTION ^

-
 plotLabels
-   Plots labels on the pathway map.
-
-   handle      handle to the figure on which to print the labels
-   pathway     pathway structure of the metabolic network
-
-   NOTE: Since there is not dedicated shape for labels the PHENOTYPE
-           shape is used. The name of the PHENOTYPE object is used.
-
- Usage: plotLabels(handle,pathway)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function plotLabels(handle,pathway)
-0002 % plotLabels
-0003 %   Plots labels on the pathway map.
-0004 %
-0005 %   handle      handle to the figure on which to print the labels
-0006 %   pathway     pathway structure of the metabolic network
-0007 %
-0008 %   NOTE: Since there is not dedicated shape for labels the PHENOTYPE
-0009 %           shape is used. The name of the PHENOTYPE object is used.
-0010 %
-0011 % Usage: plotLabels(handle,pathway)
-0012 
-0013 for i=1:numel(pathway.listOfSpecies)
-0014     if strcmp(pathway.listOfSpecies(i).type,'PHENOTYPE')
-0015         handle=text(pathway.listOfSpecies(i).x+pathway.listOfSpecies(i).w/2, pathway.listOfSpecies(i).y,...
-0016             pathway.listOfSpecies(i).name,'fontname','Small Fonts','fontsize',4,...
-0017             'interpreter', 'tex','HorizontalAlignment','center','verticalalignment','middle');
-0018     end
-0019 end
-0020 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/plotting/setColorToMapRxns.html b/doc/plotting/setColorToMapRxns.html deleted file mode 100644 index be20ac415..000000000 --- a/doc/plotting/setColorToMapRxns.html +++ /dev/null @@ -1,659 +0,0 @@ - - - - Description of setColorToMapRxns - - - - - - - - - -
Home > plotting > setColorToMapRxns.m
- - - -

setColorToMapRxns -

- -

PURPOSE ^

-
USAGE:
- -

SYNOPSIS ^

-
function [modifiedMap, xmlMap, model2] = setColorToMapRxns (mapFileName, model, v1, rxnsFluxTask, rxnLineWidth, rxnLineColor, molFillColor)
- -

DESCRIPTION ^

-
 USAGE:
- [modifiedMap, xmlMap, model2] =
-   setColorToMapRxns (mapFileName, model, v1, rxnsFluxTask, rxnLineWidth, rxnLineColor, molFillColor)
-
- INPUTS:
- mapFileName           relative path to XML map (e.g. 'yeastMap1.0.xml')
- model                 model structure
- v1                    vector of fluxes
- rxnsFluxTask          1 = Flux
-                       2 = Flux essentiality; map reactions causing any
-                           effect on growth (i.e. obj function)
-                       3 = Flux essentiality; map reactions causing no
-                           growth(i.e. obj function) when deleted, i.e.
-                           essential reactions
-                       4 = Flux essentiality; map reactions with not any
-                           effect on growth (i.e. obj function) when
-                           deleted
-                       5 = Omics
- ADDITIONAL INPUTS:
- rxnLineWidth          reaction line width; default = 5
- rxnLineColor          reaction line color; default = Pathways; write
-                       'Subsystems' to color five subsystems only (central,
-                       AA, lipids, cofactors, nuclotides and energy).
-                       'Subsystems' option is the deault option at task 5
- molFillColor          molecule fill color; default = true (i.e. white)
-                       molecule fill color; true (i.e. like CellDesigner default)
- OUTPUTS:
- modifiedMap           map with MATLAB structure, and modified reactions' line color and width
- xmlMap                xml structure of the original map obtained from mapFileName
- model2                model with modified subsystems
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
  • colorSubsystem Modified from colorSubsystemCD as distributed through COBRA Toolbox
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function [modifiedMap, xmlMap, model2] = setColorToMapRxns (mapFileName, model, v1, rxnsFluxTask, rxnLineWidth, rxnLineColor, molFillColor)
-0002 % USAGE:
-0003 % [modifiedMap, xmlMap, model2] =
-0004 %   setColorToMapRxns (mapFileName, model, v1, rxnsFluxTask, rxnLineWidth, rxnLineColor, molFillColor)
-0005 %
-0006 % INPUTS:
-0007 % mapFileName           relative path to XML map (e.g. 'yeastMap1.0.xml')
-0008 % model                 model structure
-0009 % v1                    vector of fluxes
-0010 % rxnsFluxTask          1 = Flux
-0011 %                       2 = Flux essentiality; map reactions causing any
-0012 %                           effect on growth (i.e. obj function)
-0013 %                       3 = Flux essentiality; map reactions causing no
-0014 %                           growth(i.e. obj function) when deleted, i.e.
-0015 %                           essential reactions
-0016 %                       4 = Flux essentiality; map reactions with not any
-0017 %                           effect on growth (i.e. obj function) when
-0018 %                           deleted
-0019 %                       5 = Omics
-0020 % ADDITIONAL INPUTS:
-0021 % rxnLineWidth          reaction line width; default = 5
-0022 % rxnLineColor          reaction line color; default = Pathways; write
-0023 %                       'Subsystems' to color five subsystems only (central,
-0024 %                       AA, lipids, cofactors, nuclotides and energy).
-0025 %                       'Subsystems' option is the deault option at task 5
-0026 % molFillColor          molecule fill color; default = true (i.e. white)
-0027 %                       molecule fill color; true (i.e. like CellDesigner default)
-0028 % OUTPUTS:
-0029 % modifiedMap           map with MATLAB structure, and modified reactions' line color and width
-0030 % xmlMap                xml structure of the original map obtained from mapFileName
-0031 % model2                model with modified subsystems
-0032 
-0033 if ~(exist('transformXML2Map')==2)
-0034     error('COBRA Toolbox is required, go to https://opencobra.github.io/cobratoolbox/')
-0035 end
-0036 
-0037 if nargin < 5 || rxnLineWidth == 0
-0038     rxnLineWidth = 0;
-0039     rxnLineColor = '';
-0040     molFillColor = true;
-0041 elseif nargin < 6
-0042     rxnLineColor = '';
-0043     molFillColor = true;
-0044 elseif nargin < 7
-0045     molFillColor = true;
-0046 end
-0047 if rxnsFluxTask == 5
-0048     rxnLineColor = 'Subsystems';
-0049 end
-0050 
-0051 [xmlMap, mapMap] = transformXML2Map(mapFileName);
-0052 if molFillColor == true
-0053     modifiedMap = unifyMetabolicMapCD(mapMap); % molColor whrite and rxnColor = ligthgray
-0054 elseif molFillColor == false
-0055     modifiedMap = mapMap; % like CellDesigner default
-0056 end
-0057 
-0058 %%%%%%%% Gettin reactions line width with normalized fluxes %%%%%%%%%%%%%
-0059 model2 = model; % to not overwrite model
-0060 flxs(:, 1) = v1; % to not overwrite v1
-0061 absFlxs = abs(flxs);
-0062 rxnLineWidthInMap = absFlxs / max(absFlxs); %normalize fluxes line width
-0063 if rxnsFluxTask == 1 && rxnLineWidth == 0
-0064     rxnLineWidthInMap(rxnLineWidthInMap > 0.1 & rxnLineWidthInMap <=  1) = 50;
-0065     rxnLineWidthInMap(rxnLineWidthInMap > 0.01 & rxnLineWidthInMap <= 0.1) = 25;
-0066     rxnLineWidthInMap(rxnLineWidthInMap > 0.001 & rxnLineWidthInMap <= 0.01) = 16;
-0067     rxnLineWidthInMap(rxnLineWidthInMap > 0.0001 & rxnLineWidthInMap <= 0.001) = 10;
-0068     rxnLineWidthInMap(rxnLineWidthInMap > 0.00001 & rxnLineWidthInMap <= 0.0001) = 6;
-0069 elseif rxnsFluxTask == 2 && rxnLineWidth == 0
-0070     rxnLineWidthInMap(rxnLineWidthInMap > 0.90 & rxnLineWidthInMap <=  0.95) =  6;
-0071     rxnLineWidthInMap(rxnLineWidthInMap > 0.80 & rxnLineWidthInMap <= 0.90) =  8;
-0072     rxnLineWidthInMap(rxnLineWidthInMap > 0.50 & rxnLineWidthInMap <= 0.80) = 11;
-0073     rxnLineWidthInMap(rxnLineWidthInMap > 0.25 & rxnLineWidthInMap <= 0.50) = 15;
-0074     rxnLineWidthInMap(rxnLineWidthInMap >= 0.00 & rxnLineWidthInMap <= 0.25) = 20;
-0075 elseif rxnsFluxTask == 1 && rxnLineWidth ~= 0.0
-0076     rxnLineWidthInMap(rxnLineWidthInMap == 1.0) = rxnLineWidth;
-0077 elseif rxnsFluxTask == 2 && rxnLineWidth ~= 0.0
-0078     rxnLineWidthInMap(rxnLineWidthInMap < 0.95) = rxnLineWidth;
-0079 elseif rxnsFluxTask == 3 && rxnLineWidth == 0.0
-0080     rxnLineWidthInMap(rxnLineWidthInMap == 0.0) = 5;
-0081 elseif rxnsFluxTask == 3 && rxnLineWidth ~= 0.0
-0082     rxnLineWidthInMap(rxnLineWidthInMap == 0.0) = rxnLineWidth;
-0083 elseif rxnsFluxTask == 4 && rxnLineWidth == 0.0
-0084     rxnLineWidthInMap(rxnLineWidthInMap > 0.95 & rxnLineWidthInMap <= 1.0) = 5.0;
-0085 elseif rxnsFluxTask == 4 && rxnLineWidth ~= 0.0
-0086     rxnLineWidthInMap(rxnLineWidthInMap > 0.95 & rxnLineWidthInMap <= 1.0) = rxnLineWidth;
-0087 elseif rxnsFluxTask == 5 && rxnLineWidth == 0.0
-0088     cutValue = 2.0; % transcriptomics minimum cut value of log change
-0089     rxnLineWidthInMap = absFlxs;
-0090     rxnLineWidthInMap(rxnLineWidthInMap > 5.0) = 30;
-0091     rxnLineWidthInMap(rxnLineWidthInMap > 4.0 & rxnLineWidthInMap <= 5.0) = 25;
-0092     rxnLineWidthInMap(rxnLineWidthInMap > 3.0 & rxnLineWidthInMap <= 4.0) = 20;
-0093     rxnLineWidthInMap(rxnLineWidthInMap > 2.0 & rxnLineWidthInMap <= 3.0) = 15;
-0094     rxnLineWidthInMap(rxnLineWidthInMap > 1.0 & rxnLineWidthInMap <= 2.0) = 10;
-0095     rxnLineWidthInMap(rxnLineWidthInMap >= 0.5 & rxnLineWidthInMap <= 1.0) =  5;
-0096 end
-0097 for i = 1:length(modifiedMap.rxnName)
-0098     a = find(ismember(model2.rxns, modifiedMap.rxnName{i}));
-0099     if isempty(a)
-0100         modifiedMap.rxnWidth{i} = 1;
-0101     else
-0102         modifiedMap.rxnWidth{i} = rxnLineWidthInMap(a);
-0103     end
-0104 end
-0105 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-0106 
-0107 %%%%%%%%% Cofactors not included in the analyses %%%%%%%%%%%%%%%%%%%%%%%%
-0108 %%%%%%%%% Compartments included in the analyses %%%%%%%%%%%%%%%%%%%%%%%%%
-0109 
-0110 % propossed cofactors list for PART A
-0111 cofactorsListA ={'h'; 'h2o'; 'nad'; 'nadh'; 'nadp'; 'nadph';...
-0112     'fad'; 'fadh'; 'ppi'; 'adp'; 'gtp'; 'gdp'; 'gmp'; ...
-0113     'utp'; 'udp'; 'ump'; 'ctp'; 'cdp'; 'cmp'};
-0114 
-0115 % propossed cofactors list for PART B
-0116 cofactorsListB ={'h'; 'h2o'; 'co2'; 'coa'; 'accoa'; 'nad'; 'nadh'; 'nadp'; 'nadph';...
-0117     'fad'; 'fadh'; 'pi'; 'ppi'; 'atp'; 'adp'; 'amp'; 'gtp'; 'gdp'; 'gmp';...
-0118     'utp'; 'udp'; 'ump'; 'ctp'; 'cdp'; 'cmp'; 'gthox'; 'gthrd_c'; 'amet_c';...
-0119     'ahcys_c'; 'glu__L'; 'gln__L'; 'akg'; 'nh4'};
-0120 
-0121 % compartments list
-0122 compartmentsList = {'_e'; '_c'; '_m'; '_n'; '_x'; '_v'; '_r'; '_g'};
-0123 
-0124 % include compartment to cofactor lists A and B
-0125 cofactorsListWcompA = cell(length(cofactorsListA), 1);
-0126 c = 1; % general counter
-0127 for i = 1:length(cofactorsListA)
-0128     for j = 1:length(compartmentsList)
-0129         cofactorsListWcompA{c, 1} = horzcat(cofactorsListA{i},compartmentsList{j});
-0130         c = c + 1;
-0131     end
-0132 end
-0133 cofactorsListWcompB = cell(length(cofactorsListB), 1);
-0134 c = 1;
-0135 for i = 1:length(cofactorsListB)
-0136     for j = 1:length(compartmentsList)
-0137         cofactorsListWcompB{c, 1}= horzcat(cofactorsListB{i},compartmentsList{j});
-0138         c = c + 1;
-0139     end
-0140 end
-0141 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-0142 
-0143 
-0144 %%%%%%%%%%%%%%%%%%%%%%%%%%%% PART A %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-0145 
-0146 % getting transport reactions
-0147 [nrxns,~] = size(model2.rxns);
-0148 transRxns = cell(nrxns, 1);
-0149 for j = 1:size(model2.rxns)
-0150     if true(contains(model2.subSystems {j}, 'S_Transport'))
-0151         transRxns{j, 1} = model2.rxns{j};
-0152     end
-0153 end
-0154 transRxns = transRxns(~cellfun('isempty',transRxns));
-0155 
-0156 % getting subStystems without transport
-0157 SubSystems = (unique(getModelSubSystems(model2)));
-0158 [nSubSystems, ~] = size(SubSystems);
-0159 subSystemsNoTrans = cell(nSubSystems, 1);
-0160 for i = 1:nSubSystems
-0161     if ~contains(SubSystems{i,1},'S_Transport')&& ...
-0162             ~contains(SubSystems{i, 1},'Extracellular exchange') &&...
-0163             ~contains(SubSystems{i, 1},'S_tRNA_charging')
-0164         subSystemsNoTrans{i, 1} = SubSystems{i, 1};
-0165     else
-0166         subSystemsNoTrans{i, 1} = {};
-0167     end
-0168 end
-0169 subSystemsNoTrans = subSystemsNoTrans(~cellfun('isempty',subSystemsNoTrans));
-0170 
-0171 % defining subSystems of trasnport reactions to be colored, these
-0172 % transport reactions complete reaction conections in subSystems which
-0173 % require conexions among diferents compartments
-0174 [nTransRxns,~] = size(transRxns);
-0175 [nSubSystemsNoTrans, ~] = size (subSystemsNoTrans);
-0176 totalRxnsToIncludeA = cell(nTransRxns,1);
-0177 for i = 1:nSubSystemsNoTrans
-0178     subSystemRxns = findRxnsFromSubSystem(model2, subSystemsNoTrans(i));
-0179     metsSubSystemRxns = findMetsFromRxns(model2, subSystemRxns);
-0180     [nMetsSubSystemRxns, ~] = size (metsSubSystemRxns);
-0181     % getting unique compartments
-0182     metsCompartment = cell(nMetsSubSystemRxns,1);
-0183     for j = 1:nMetsSubSystemRxns
-0184         str = metsSubSystemRxns{j};
-0185         [~, s] = size(str);
-0186         metsCompartment{j,1} = str(s-1:s);
-0187     end
-0188     metsCompartment = (unique(metsCompartment));
-0189     [nUniqueMetsComp, ~] = size(metsCompartment);
-0190     
-0191     if nUniqueMetsComp > 1
-0192         % getting duplicated mets like 'pyr_c' and 'pyr_m' which are 'pyr'
-0193         % and pyr after erasing the compartment signature
-0194         metsFromSubSystemRxnsNoComp = cell(nMetsSubSystemRxns,1);
-0195         for j = 1:nMetsSubSystemRxns
-0196             str = metsSubSystemRxns{j};
-0197             [z, s] = size(str);
-0198             metsFromSubSystemRxnsNoComp{j, 1} = str(1:s-2); % erasing comp signature
-0199         end
-0200         [~, o, ~] = unique(metsFromSubSystemRxnsNoComp,'first');
-0201         indexToDupes = find(not(ismember(1:numel(metsFromSubSystemRxnsNoComp),o)));
-0202         [~, nIndexToDupes] = size(indexToDupes);
-0203         duplicatedMets = cell(nIndexToDupes,1);
-0204         for j = 1:nIndexToDupes
-0205             duplicatedMets(j, 1) = metsFromSubSystemRxnsNoComp (indexToDupes(1, j));
-0206         end
-0207         
-0208         % getting reactions from duplicated mets
-0209         dulicatedRxnMets = cell(nIndexToDupes * nUniqueMetsComp,1);
-0210         c = 1; % duplicatedRxnMets counter
-0211         for j = 1:nIndexToDupes
-0212             str = duplicatedMets{j, 1};
-0213             if ~ismember(str, cofactorsListA)
-0214                 for k = 1:nUniqueMetsComp
-0215                     str1 = metsCompartment{k};
-0216                     if ~ismember(str1, compartmentsList(2)) % compartment '_c'
-0217                         dulicatedRxnMets{c, 1} = {horzcat(str, '_c'), horzcat(str, str1)};
-0218                         c = c + 1;
-0219                     end
-0220                 end
-0221             end
-0222         end
-0223         dulicatedRxnMets = dulicatedRxnMets(~cellfun('isempty',dulicatedRxnMets));
-0224         [ndulicatedRxnMets, ~] = size(dulicatedRxnMets);
-0225         % from duplicated reactions, get reactions to subscribe a reactions
-0226         % subsystem from non transport subsystems
-0227         rxnsToInclude = cell(ndulicatedRxnMets, 1);
-0228         for j = 1:ndulicatedRxnMets
-0229             metsToFindInTrasnportRxns = dulicatedRxnMets{j, 1};
-0230             for k = 1:nTransRxns
-0231                 rxnFormula = printRxnFormula(model2, transRxns{k, 1}, false);
-0232                 if true(contains(string(rxnFormula), metsToFindInTrasnportRxns (1, 1)))
-0233                     if true(contains(rxnFormula, metsToFindInTrasnportRxns (1, 2)))
-0234                         rxnsToInclude{j, 1} = transRxns{k, 1};
-0235                     end
-0236                 end
-0237             end
-0238         end
-0239         rxnsToInclude = rxnsToInclude(~cellfun('isempty',rxnsToInclude));
-0240         rxnsToInclude = unique(rxnsToInclude);
-0241         [s, ~] = size(rxnsToInclude);
-0242         totalRxnsToIncludeA = [totalRxnsToIncludeA; rxnsToInclude];
-0243         
-0244         for j = 1:s
-0245             rxnID = findRxnIDs(model2, rxnsToInclude{j});
-0246             model2.subSystems(rxnID) = {subSystemsNoTrans(i)};
-0247         end
-0248         
-0249     end
-0250 end
-0251 totalRxnsToIncludeA = totalRxnsToIncludeA(~cellfun('isempty',totalRxnsToIncludeA));
-0252 totalRxnsToIncludeA = unique(totalRxnsToIncludeA);
-0253 
-0254 %%%%%%%%%%%%%%%%%%%%%%%%%%%% PART B %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-0255 
-0256 % Get subsystems category. This is based on the number of conexions that a
-0257 % subsystem includes in the genome scale metabolic model2
-0258 subsLength ={};
-0259 for i = 1:length(subSystemsNoTrans)
-0260     rxnsSubs = findRxnsFromSubSystem(model2,subSystemsNoTrans(i));
-0261     metsSubsRxns = findMetsFromRxns(model2, rxnsSubs);
-0262     metsSubsRxnsNoCof = {};
-0263     for j = 1:length(metsSubsRxns)
-0264         if ~ismember(metsSubsRxns(j),cofactorsListWcompB)
-0265             metsSubsRxnsNoCof{j,1} = char(metsSubsRxns(j));
-0266         end
-0267     end
-0268     metsSubsRxnsNoCof = metsSubsRxnsNoCof(~cellfun('isempty',metsSubsRxnsNoCof));
-0269     
-0270     metsRxns = findRxnsFromMets(model2, metsSubsRxnsNoCof);
-0271     metsRxnsSubs = {};
-0272     for j = 1:length(metsRxns)
-0273         rxnID = findRxnIDs(model2,metsRxns(j));
-0274         metsRxnsSubs{j,1} = string(model2.subSystems(rxnID));
-0275     end
-0276     metsRxnsSubs = unique(string(metsRxnsSubs));
-0277     subsLength{i,1} = length(metsRxnsSubs);
-0278     subsLength{i,2} = subSystemsNoTrans{i};
-0279 end
-0280 
-0281 % Get  remaining transport reacctions, namely, reactions not included in
-0282 % PART A
-0283 
-0284 [nTransRxns, ~] = size(transRxns);
-0285 remainingTransRxns = cell(nTransRxns, 1);
-0286 for i = 1:nTransRxns
-0287     if ~ismember(transRxns(i),totalRxnsToIncludeA)
-0288         remainingTransRxns{i,1} = transRxns{i, 1};
-0289     end
-0290 end
-0291 remainingTransRxns = remainingTransRxns(~cellfun('isempty',remainingTransRxns));
-0292 
-0293 % Assign remaining transport reactions
-0294 nonIncludSubs = {'S_tRNA_charging', 'S_Other',...
-0295     'Biomass and maintenance functions', };
-0296 totalRxnsToIncludeAB = totalRxnsToIncludeA;
-0297 remTransRxnsWnewSubs = {};
-0298 remTransRxnsSubs = {};
-0299 rxnsToInclude = cell(length(remainingTransRxns), 1);
-0300 subSToInclude = cell(length(remainingTransRxns), 1);
-0301 for i = 1:length(remainingTransRxns)
-0302     metsRemTransRxns = findMetsFromRxns(model2, remainingTransRxns(i));
-0303     metsRxns = {};
-0304     for j = 1:length(metsRemTransRxns)
-0305         if true(contains(metsRemTransRxns{j},'_c') &&...
-0306                 ~ismember(metsRemTransRxns(j), cofactorsListWcompB))
-0307             metsRxns = findRxnsFromMets(model2,metsRemTransRxns(j));
-0308         end
-0309     end
-0310     metsRxns = metsRxns(~cellfun('isempty',metsRxns));
-0311     
-0312     rxnSubs = {};
-0313     for j = 1:length(metsRxns)
-0314         rxnID = findRxnIDs(model2, metsRxns(j));
-0315         rxnSubs{j,1} = model2.subSystems{rxnID};
-0316     end
-0317     rxnSubs = rxnSubs(~cellfun('isempty',rxnSubs));
-0318     
-0319     r = [];
-0320     rankMax = 0;
-0321     subSToUseStr = cell(1,1);
-0322     for j = 1:length(rxnSubs)
-0323         if true(~ismember(string(metsRxns(j)),totalRxnsToIncludeA))
-0324             for k = 1:length(subsLength)
-0325                 if true(and(ismember(rxnSubs{j}, subsLength{k,2}),...
-0326                         ~ismember(rxnSubs{j}, nonIncludSubs)))
-0327                     r(k, 1) = subsLength{k, 1};
-0328                     subSToUseStr{1, 1} = string(subsLength(k,2));
-0329                     if k > 1
-0330                         if true(rankMax < r(k, 1))
-0331                             rankMax = r(k, 1);
-0332                             subSToUseStr{1, 1} = string(subsLength(k,2));
-0333                         end
-0334                     end
-0335                 end
-0336             end
-0337         end
-0338     end
-0339     if ~isempty(subSToUseStr(1,1))
-0340         rxnsToInclude{i} = remainingTransRxns{i};
-0341         subSToInclude{i} = char(subSToUseStr{1, 1});
-0342         remTransRxnsWnewSubs{i,1} = remainingTransRxns(i);
-0343         remTransRxnsSubs{i,1} = subSToUseStr(1, 1);
-0344         totalRxnsToIncludeAB = [totalRxnsToIncludeAB; rxnsToInclude];
-0345     end
-0346 end
-0347 totalRxnsToIncludeAB = totalRxnsToIncludeAB(~cellfun('isempty',totalRxnsToIncludeAB));
-0348 totalRxnsToIncludeAB = unique(totalRxnsToIncludeAB);
-0349 
-0350 for j = 1:length(rxnsToInclude)
-0351     rxnID = findRxnIDs(model2, rxnsToInclude{j});
-0352     model2.subSystems(rxnID) = {subSToInclude(j)};
-0353 end
-0354 
-0355 %%%%%%%%%%%%%%%%%%%%%%%% ASIGN SUBSYSTEMS' COLOR %%%%%%%%%%%%%%%%%%%%%%%%%%%
-0356 
-0357 % Selection of reactions to include in the map
-0358 if rxnsFluxTask == 1
-0359     for i = 1:length(model2.rxns)
-0360         if absFlxs(i)==0 % zero flux reactions are not included
-0361             model2.subSystems(i) = {{'NonIncluded'}};  % included at the end
-0362         end
-0363     end
-0364 elseif rxnsFluxTask == 2
-0365     for i = 1:length(model2.rxns)
-0366         if absFlxs(i) > 0.95 * max(absFlxs)% reactions causing growth (i.e. obj function) defect when deleting
-0367             model2.subSystems(i) = {{'NonIncluded'}};   % included at the end
-0368         end
-0369     end
-0370 elseif rxnsFluxTask == 3
-0371     for i = 1:length(model2.rxns)
-0372         if absFlxs(i) > 0.0 % zero flux reactions only, i.e. essential reations
-0373             model2.subSystems(i) = {{'NonIncluded'}};   % included at the end
-0374         end
-0375     end
-0376 elseif rxnsFluxTask == 4
-0377     for i = 1:length(model2.rxns)
-0378         if absFlxs(i) < 0.95 * max(absFlxs)% reactions fluxes causing no growth (i.e. obj function) defect when deleting
-0379             model2.subSystems(i) = {{'NonIncluded'}};   % included at the end
-0380         end
-0381     end
-0382 elseif rxnsFluxTask == 5
-0383     for i = 1:length(model2.rxns)
-0384         if absFlxs(i) < cutValue % zero flux reactions are not included
-0385             model2.subSystems(i) = {{'NonIncluded'}};  % included at the end
-0386         end
-0387     end
-0388 end
-0389 
-0390 %See colors letter-code at:
-0391 %la.mathworks.com/matlabcentral/mlc-downloads/downloads/submissions/24497/versions/2/screenshot.PNG
-0392 %[xmlMap, mapMap] = transformXML2Map('YeastMapUnified1.0b.xml');
-0393 centralPathsList = {'S_GlycolysisGluconeogenesis', 'S_Pentose_Phosphate_Pathway',...
-0394     'S_Pyruvate_Metabolism', 'S_Citric_Acid_Cycle', 'S_Taurine_Metabolism',...
-0395     'S_Starch_and_Sucrose_Metabolism', 'S_Xylose_Metabolism',...
-0396     'S_Fructose_and_Mannose_Metabolism', 'S_Galactose_metabolism',...
-0397     'S_Arabinose_Metabolism', 'S_Alternate_Carbon_Metabolism', 'S_Methane_Metabolism'};
-0398 aminoacPathsList = {'S_Glutamate_metabolism', 'S_Glutamine_Metabolism',...
-0399     'S_Alanine_and_Aspartate_Metabolism', 'S_Histidine_Metabolism',...
-0400     'S_Threonine_and_Lysine_Metabolism', 'S_Glycine_and_Serine_Metabolism',...
-0401     'S_Tyrosine__Tryptophan__and_Phenylalanine_Metabolism',...
-0402     'S_Arginine_and_Proline_Metabolism', 'S_Cysteine_Metabolism',...
-0403     'S_Methionine_Metabolism', 'S_Valine__Leucine__and_Isoleucine_Metabolism',...
-0404     'S_Other_Amino_Acid_Metabolism', 'S_Asparagine_metabolism', 'S_Nitrogen_Metabolism'};
-0405 cofactorsPathsList = {'S_NAD_Biosynthesis', 'S_Pantothenate_and_CoA_Biosynthesis',...
-0406     'S_Folate_Metabolism', 'S_Riboflavin_Metabolism', 'S_Quinone_Biosynthesis',...
-0407     'S_Porphyrin_and_Chlorophyll_Metabolism'};
-0408 lipidsPathsList = {'S_Fatty_Acid__Biosynthesis', 'S_Fatty_Acid_Degradation',...
-0409     'S_Fatty_Acid_Metabolism', 'S_Glycerolipid_Metabolism', 'S_Glycoprotein_Metabolism',...
-0410     'S_Phospholipid_Biosynthesis', 'S_Phospholipid_Metabolism',...
-0411     'S_Sphingolipid_Metabolism', 'S_Sterol_Metabolism'};
-0412 nucleotidsPathsList = {'S_Purine_and_Pyrimidine_Biosynthesis',...
-0413     'S_Nucleotide_Salvage_Pathway', 'S_Thiamine_Metabolism', 'S_Pyridoxine_Metabolism'};
-0414 enrgyPathsList = {'Biomass and maintenance functions', 'S_Anaplerotic_reactions',...
-0415     'S_Oxidative_Phosphorylation'};
-0416 colors = createColorsMap;
-0417 
-0418 if isempty(rxnLineColor)||rxnLineColor == "Pathways"
-0419     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_GlycolysisGluconeogenesis', 'DARKBLUE');
-0420     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Pentose_Phosphate_Pathway', 'STEELBLUE');
-0421     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Pyruvate_Metabolism', 'DODGERBLUE');
-0422     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Citric_Acid_Cycle', 'MEDIUMBLUE');
-0423     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Taurine_Metabolism', 'MEDIUMBLUE');
-0424     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Starch_and_Sucrose_Metabolism', 'BLUE');
-0425     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Xylose_Metabolism', 'STEELBLUE');
-0426     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Fructose_and_Mannose_Metabolism', 'DODGERBLUE');
-0427     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Galactose_metabolism', 'MEDIUMBLUE');
-0428     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Arabinose_Metabolism', 'BLUE');
-0429     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Alternate_Carbon_Metabolism', 'DARKBLUE');
-0430     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Methane_Metabolism', 'DARKBLUE');
-0431     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Taurine_Metabolism', 'DARKBLUE');
-0432     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Anaplerotic_reactions', 'CRIMSON');
-0433     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Complex_Alcohol_Metabolism', 'MAROON');
-0434     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Oxidative_Phosphorylation', 'RED');
-0435     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Purine_and_Pyrimidine_Biosynthesis', 'PINK');
-0436     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Nucleotide_Salvage_Pathway', 'HOTPINK');
-0437     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Thiamine_Metabolism', 'MAGENTA');
-0438     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Pyridoxine_Metabolism', 'PINK');
-0439     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_NAD_Biosynthesis', 'PLUM');
-0440     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Pantothenate_and_CoA_Biosynthesis', 'VIOLET');
-0441     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Folate_Metabolism', 'DARKORCHID');
-0442     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Riboflavin_Metabolism', 'PURPLE');
-0443     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Quinone_Biosynthesis', 'MEDIUMORCHID');
-0444     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Porphyrin_and_Chlorophyll_Metabolism', 'PLUM');
-0445     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Glutamate_metabolism', 'ORANGE');
-0446     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Glutamine_Metabolism', 'DARKORANGE');
-0447     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Alanine_and_Aspartate_Metabolism', 'CORAL');
-0448     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Histidine_Metabolism', 'GOLD');
-0449     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Threonine_and_Lysine_Metabolism', 'ORANGE');
-0450     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Glycine_and_Serine_Metabolism', 'DARKORANGE');
-0451     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Tyrosine__Tryptophan__and_Phenylalanine_Metabolism', 'CORAL');
-0452     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Arginine_and_Proline_Metabolism', 'GOLD');
-0453     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Cysteine_Metabolism', 'ORANGE');
-0454     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Methionine_Metabolism', 'DARKORANGE');
-0455     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Valine__Leucine__and_Isoleucine_Metabolism', 'CORAL');
-0456     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Other_Amino_Acid_Metabolism', 'GOLD');
-0457     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Asparagine_metabolism', 'ORANGE');
-0458     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Nitrogen_Metabolism', 'DARKORANGE');
-0459     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Fatty_Acid__Biosynthesis', 'FORESTGREEN');
-0460     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Fatty_Acid_Degradation', 'MEDIUMSEAGREEN');
-0461     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Fatty_Acid_Metabolism', 'DARKGREEN');
-0462     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Glycerolipid_Metabolism', 'SEAGREEN');
-0463     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Glycoprotein_Metabolism', 'FORESTGREEN');
-0464     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Phospholipid_Biosynthesis', 'MEDIUMSEAGREEN');
-0465     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Phospholipid_Metabolism', 'DARKGREEN');
-0466     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Sphingolipid_Metabolism', 'SEAGREEN');
-0467     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Sterol_Metabolism', 'FORESTGREEN');
-0468     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Other', 'BLACK');
-0469     modifiedMap = colorSubsystem(modifiedMap, model2, 'Biomass and maintenance functions', 'RED');
-0470 elseif rxnLineColor == "Subsystems"
-0471     modifiedMap = colorSubsystem(modifiedMap, model2, centralPathsList, 'BLUE'); %mapMap to fluxMap
-0472     modifiedMap = colorSubsystem(modifiedMap, model2, aminoacPathsList, 'ORANGE');
-0473     modifiedMap = colorSubsystem(modifiedMap, model2, cofactorsPathsList, 'ORCHID');
-0474     modifiedMap = colorSubsystem(modifiedMap, model2, lipidsPathsList, 'LIME');
-0475     modifiedMap = colorSubsystem(modifiedMap, model2, nucleotidsPathsList, 'MAGENTA');
-0476     modifiedMap = colorSubsystem(modifiedMap, model2, enrgyPathsList, 'RED');
-0477     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Complex_Alcohol_Metabolism', 'GOLDENROD');
-0478     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Other', 'GOLDENROD');
-0479 elseif ~(rxnLineColor == "Subsystems" || rxnLineColor == "Payhways" || isempty(rxnLineColor))
-0480     for i = 1:length(modifiedMap.rxnName)
-0481         a = find(ismember(model2.rxns, modifiedMap.rxnName{i}));
-0482         if ~isempty(a) & string(model2.subSystems(a)) ~= "NonIncluded"
-0483             modifiedMap.rxnColor(i, 1) = {colors(rxnLineColor)};
-0484         end
-0485     end
-0486 end
-0487 if rxnLineColor == "Subsystems" || rxnLineColor == "Payhways" || isempty(rxnLineColor)
-0488     h2o = {'H2Ot', 'H2Otm',    'H2Otn', 'H2Otv', 'H2Otp', 'H2Oter'};
-0489     for i = 1:length(modifiedMap.rxnName)
-0490         a = find(ismember(model2.rxns, modifiedMap.rxnName{i}));
-0491         for j = 1:length(h2o)
-0492             if ~isempty(a) & string(modifiedMap.rxnName{i}) == string(h2o(j))...
-0493                     & string(model2.subSystems(a)) ~= "NonIncluded"
-0494                 modifiedMap.rxnColor(i, 1) = {colors('CYAN')};
-0495             end
-0496         end
-0497     end
-0498     o2 = {'O2t', 'O2tm', 'O2ter', 'O2tp'};
-0499     for i = 1:length(modifiedMap.rxnName)
-0500         a = find(ismember(model2.rxns, modifiedMap.rxnName{i}));
-0501         for j = 1:length(o2)
-0502             if ~isempty(a) & string(modifiedMap.rxnName{i}) == string(o2(j))...
-0503                     & string(model2.subSystems(a)) ~= "NonIncluded"
-0504                 modifiedMap.rxnColor(i, 1) = {colors('CYAN')};
-0505             end
-0506         end
-0507     end
-0508     Pi = {'PIt2r', 'PIt2m', 'PIt5m', 'PIt2n', 'PIt2v', 'PIt2p', 'ATPtm_H', 'ATPtp_H', ...
-0509         'ATP2tp_H', 'ATPS3g', 'ATPS3v', 'UTPtm', 'CTPtm', 'GTPt2m', 'ATPS'};
-0510     for i = 1:length(modifiedMap.rxnName)
-0511         a = find(ismember(model2.rxns, modifiedMap.rxnName{i}));
-0512         for j = 1:length(Pi)
-0513             if ~isempty(a) & string(modifiedMap.rxnName{i}) == string(Pi(j))...
-0514                     & string(model2.subSystems(a)) ~= "NonIncluded"
-0515                 modifiedMap.rxnColor(i, 1) = {colors('RED')};
-0516             end
-0517         end
-0518     end
-0519     co2 = {'CO2t', 'CO2tg', 'CO2tm', 'CO2tn', 'HCO3tn', 'CO2tv', 'CO2tp'};
-0520     for i = 1:length(modifiedMap.rxnName)
-0521         a = find(ismember(model2.rxns, modifiedMap.rxnName{i}));
-0522         for j = 1:length(co2)
-0523             if ~isempty(a) & string(modifiedMap.rxnName{i}) == string(co2(j))...
-0524                     & string(model2.subSystems(a)) ~= "NonIncluded"
-0525                 modifiedMap.rxnColor(i, 1) = {colors('SLATEGRAY')};
-0526             end
-0527         end
-0528     end
-0529     aa = {'MMETt2', 'GLUt2r', 'GLNt2r', 'GLNt7', 'GLUt7', 'LCYSTintv', 'NH4t', 'TCHOLAabcv'};
-0530     for i = 1:length(modifiedMap.rxnName)
-0531         a = find(ismember(model2.rxns, modifiedMap.rxnName{i}));
-0532         for j = 1:length(aa)
-0533             if ~isempty(a) & string(modifiedMap.rxnName{i}) == string(aa(j))...
-0534                     & string(model2.subSystems(a)) ~= "NonIncluded"
-0535                 modifiedMap.rxnColor(i, 1) = {colors('ORANGE')};
-0536             end
-0537         end
-0538     end
-0539     cenMet = {'COAtim', 'NAt3_1', 'MALS'};
-0540     for i = 1:length(modifiedMap.rxnName)
-0541         a = find(ismember(model2.rxns, modifiedMap.rxnName{i}));
-0542         for j = 1:length(cenMet)
-0543             if ~isempty(a) & string(modifiedMap.rxnName{i}) == string(cenMet(j))...
-0544                     & string(model2.subSystems(a)) ~= "NonIncluded"
-0545                 modifiedMap.rxnColor(i, 1) = {colors('BLUE')};
-0546             end
-0547         end
-0548     end
-0549     lip = {'G3PIt'};
-0550     for i = 1:length(modifiedMap.rxnName)
-0551         a = find(ismember(model2.rxns, modifiedMap.rxnName{i}));
-0552         for j = 1:length(lip)
-0553             if ~isempty(a) & string(modifiedMap.rxnName{i}) == string(lip(j))...
-0554                     & string(model2.subSystems(a)) ~= "NonIncluded"
-0555                 modifiedMap.rxnColor(i, 1) = {colors('LIME')};
-0556             end
-0557         end
-0558     end
-0559 end
-0560 
-0561 if rxnsFluxTask == 5 % change color to dark-color in negative values
-0562     for i = 1:length(modifiedMap.rxnName)
-0563         valueskeys = values(colors)';
-0564         valueskeys (:,2) = keys(colors)';
-0565         a = find(ismember(valueskeys, modifiedMap.rxnColor{i, 1}));
-0566         b = find(ismember(model2.rxns, modifiedMap.rxnName{i}));
-0567         if ~isempty(b) & v1(b) < 0 & string(model2.subSystems(b)) ~= "NonIncluded"
-0568             if string(valueskeys (a,2)) == 'LIME'
-0569                 modifiedMap.rxnColor(i, 1) = {colors('GREEN')};
-0570             else
-0571                 rxnColor =strcat('DARK', char(valueskeys (a(1,1),2)));
-0572                 if string(rxnColor) == 'DARKAQUA'
-0573                     rxnColor = 'DARKCYAN';
-0574                 elseif string(rxnColor) == 'DARKFUCHSIA'
-0575                     rxnColor = 'DARKMAGENTA';
-0576                 end
-0577                 modifiedMap.rxnColor(i, 1) = {colors(rxnColor)};
-0578             end
-0579         end
-0580     end
-0581 end
-0582 
-0583 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/plotting/setOmicDataToRxns.html b/doc/plotting/setOmicDataToRxns.html deleted file mode 100644 index 7f65dc6c8..000000000 --- a/doc/plotting/setOmicDataToRxns.html +++ /dev/null @@ -1,103 +0,0 @@ - - - - Description of setOmicDataToRxns - - - - - - - - - -
Home > plotting > setOmicDataToRxns.m
- - - -

setOmicDataToRxns -

- -

PURPOSE ^

-
USAGE:
- -

SYNOPSIS ^

-
function v1 = setOmicDataToRxns(omics, model)
- -

DESCRIPTION ^

-
 USAGE:
- v1 = setOmicDataToRxns(omics, model)
- INPUTS:
- omics     two column cell array with genes and log-fold expression changes
- model     model structure
- OUTPUTS:
- v1       vector with expression changes in metabolic genes
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function v1 = setOmicDataToRxns(omics, model)
-0002 % USAGE:
-0003 % v1 = setOmicDataToRxns(omics, model)
-0004 % INPUTS:
-0005 % omics     two column cell array with genes and log-fold expression changes
-0006 % model     model structure
-0007 % OUTPUTS:
-0008 % v1       vector with expression changes in metabolic genes
-0009 
-0010 j = 1;
-0011 for i = 1:length(model.genes)
-0012     a = find(ismember(omics(:,1), model.genes{i}));
-0013     if ~isempty(a)
-0014         genesList{j,1} = omics{a,1};
-0015         genesList{j,2} = omics{a,2};
-0016         j = j + 1;
-0017     end
-0018 end
-0019 rxnsFromGenes = findRxnsFromGenes(model, genesList(:,1));
-0020 s = struct2cell(rxnsFromGenes);
-0021 k = 1;
-0022 for i = 1:length(s)
-0023     s1 = s{i};
-0024     [l,~]=size(s1);
-0025     for j = 1:l
-0026         s2=s1{j};
-0027         rxnsList{k,1}=s2;
-0028         k = k + 1;
-0029     end
-0030 end
-0031 rxnsList = (unique(rxnsList));
-0032 
-0033 for i = 1:length(rxnsList)
-0034     rxnsList {i,2} = findGenesFromRxns(model, rxnsList{i});
-0035 end
-0036 v1 = zeros(length(model.rxns),1);
-0037 for i = 1:length(rxnsList)
-0038     rxnGenes = rxnsList{i,2};
-0039     indRxnGene = rxnGenes{1,1};
-0040     c = 0.0;
-0041     for j = 1:length(indRxnGene)
-0042         a = find(ismember(genesList(:,1),indRxnGene{j,1}));
-0043         if ~isempty(a) && abs(cell2mat(genesList(a,2))) >= c
-0044             c = cell2mat(genesList(a,2));
-0045         end
-0046     end
-0047     rxnID = findRxnIDs(model,rxnsList{i,1});
-0048     v1(rxnID,1) = c;
-0049 end
-0050 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/plotting/setTitle.html b/doc/plotting/setTitle.html deleted file mode 100644 index 4b738c81a..000000000 --- a/doc/plotting/setTitle.html +++ /dev/null @@ -1,70 +0,0 @@ - - - - Description of setTitle - - - - - - - - - -
Home > plotting > setTitle.m
- - - -

setTitle -

- -

PURPOSE ^

-
plotLabels
- -

SYNOPSIS ^

-
function setTitle(handle, pathway, title)
- -

DESCRIPTION ^

-
 plotLabels
-   Prints a title on on a map drawn by drawPathway.
-
-   handle      handle to the figure on which to print the labels
-   pathway     pathway structure representing the pathway to be drawn
-   title       the title
-
- Usage: setTitle(handle, pathway, title)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function setTitle(handle, pathway, title)
-0002 % plotLabels
-0003 %   Prints a title on on a map drawn by drawPathway.
-0004 %
-0005 %   handle      handle to the figure on which to print the labels
-0006 %   pathway     pathway structure representing the pathway to be drawn
-0007 %   title       the title
-0008 %
-0009 % Usage: setTitle(handle, pathway, title)
-0010 
-0011 dimension=getPathwayDimensions(pathway);
-0012 
-0013 handle=text(dimension(1)+0.5*dimension(3), -150,...
-0014     title,'fontname','Small Fonts','fontsize',5,...
-0015     'interpreter', 'tex','HorizontalAlignment','center','verticalalignment','middle');
-0016 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/right.png b/doc/right.png deleted file mode 100644 index 067c5baf250318b85ede9047ea56e394244a8712..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 136 zcmeAS@N?(olHy`uVBq!ia0vp^{2ujP)z zZ3@F642I+A(ex_uOz|q|-Q16CA~DKXHy!h#6nPc#A=(dzh_Dj}01(mYWlSQ*cu32| zbbY!^c%J9=dA@}A9sq8umob~|g)?E>&V+Ie#O(HQu@+QR?< N002ovPDHLkV1hx>d=3Br diff --git a/doc/simulinkicon.gif b/doc/simulinkicon.gif deleted file mode 100644 index 1386ddd4ce654071015610e81fdea82461d8e28b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 977 zcmbu8u}_m>5XK)83^3Uu8;SX77?CI^3B-XItA?P13elB7PXr>Q5E~tEP-6{~F%D-K z)WpFqI=OT~2IKIO5C(b~XFmOKi{R_TBlgr&b_q*r5UY@)(Ha=TG0e=CHm)y-= z-NhXdrR2#xsVDJ-NLq3;H+2&?M6D)Qb5&PyMYKwCF&A|a7f{KO9Oh7mI2cfy($r!z zs}XbJSxTCcq=XpD$Sj#AlVk`ACe@N^Qb~${Vy##bO(ID^Mz$tcf+k1;r;?gtgeE1i znB!n-Q<_?AMl2LDpPGpoVn2>$q-rXrh;>Q9q^OCQfZG#_wFWhaf$Px^VzQfdaDPH@ zLsCc`!iKu|Sa$Qm|sSpKyq|-EjTr8*2+?H0- z4`Q;Lc94k+b3;;7jL_^P7CAVW+LT6|D5{xe%m-eKMsh!nWh97?BYe&89m)KJVRL?! zsLhQI*K_ZpHMb*1{#n2u&8oRKvdcS(-_QHDh{>=FJST?;-$*#_> zFWg+IF0Bn^lXvHav-8W#Szfc2RV!b=VRFa{1fJ1Bvn_=*1$x~u5G{^07%?ML0m zHxB3bGCb|+8kyh!`1T@vWbw!Thc`P>6y|3Oo@O9$!+|lO2pBq=~ z?6HkkzgKp4CuH{I*7l2^yRRR1_MTc?@7vp&8a;gcZ2H%?cU{-M_dgh2`cl7D{M1<} G;M_lk-mF{z diff --git a/doc/solaris.png b/doc/solaris.png deleted file mode 100644 index e31e8a2a48078233e65bf10502de055609469206..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 286 zcmV+(0pb3MP)LJX0GRn|87F~=qO=0d z$LTWTx~|80zJzI-0N{4DjI%Mk;moMpnNcohj7EB(iPVo~iqGKm_8{s|W(+hpPU=N2 zz2$E5rj(XtF(bOm8L*eKNAeVg;o46LO1s$e-HK3o_b;p)l_XJ5>4v`(0TG#bkaL)bhCi169@`rB kx1WB<=i4tMjP|#52ZwT~UP>&M!~g&Q07*qoM6N<$g3~#GJpcdz diff --git a/doc/solver/checkSolution.html b/doc/solver/checkSolution.html deleted file mode 100644 index 157e5b3e9..000000000 --- a/doc/solver/checkSolution.html +++ /dev/null @@ -1,83 +0,0 @@ - - - - Description of checkSolution - - - - - - - - - -
Home > solver > checkSolution.m
- - - -

checkSolution -

- -

PURPOSE ^

-
Checks if a solution from Mosek is feasible and optimal
- -

SYNOPSIS ^

-
function [isFeasible, isOptimal]=checkSolution(res)
- -

DESCRIPTION ^

-
   Checks if a solution from Mosek is feasible and optimal
-
-   res             the output structure from mosekopt
-
-   isFeasible      true if the solution is feasible
-   isoptimal       true if the solution is optimal
-
-   This function also throws an error if the license has expired.
-
- Usage: [isFeasible, isOptimal]=checkSolution(res)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function [isFeasible, isOptimal]=checkSolution(res)
-0002 %   Checks if a solution from Mosek is feasible and optimal
-0003 %
-0004 %   res             the output structure from mosekopt
-0005 %
-0006 %   isFeasible      true if the solution is feasible
-0007 %   isoptimal       true if the solution is optimal
-0008 %
-0009 %   This function also throws an error if the license has expired.
-0010 %
-0011 % Usage: [isFeasible, isOptimal]=checkSolution(res)
-0012 
-0013 isFeasible=false;
-0014 isOptimal=false;
-0015 
-0016 switch res.stat
-0017     case 1
-0018         isOptimal=true;
-0019         isFeasible=true;
-0020     case 2
-0021         isOptimal=false;
-0022         isFeasible=true;
-0023     otherwise
-0024         isOptimal=false;
-0025         isFeasible=false;
-0026 end
-0027 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/solver/index.html b/doc/solver/index.html deleted file mode 100644 index e42468a9a..000000000 --- a/doc/solver/index.html +++ /dev/null @@ -1,29 +0,0 @@ - - - - Index for Directory solver - - - - - - - - - - -
< Master indexIndex for solver >
- -

Index for solver

- -

Matlab files in this directory:

- -
 checkSolutionChecks if a solution from Mosek is feasible and optimal
 optimizeProboptimizeProb
 qMOMAqMOMA
 setRavenSolversetRavenSolver
 solveLPsolveLP
 solveQPsolveQP
- - - - -
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/solver/optimizeProb.html b/doc/solver/optimizeProb.html deleted file mode 100644 index a6ec84623..000000000 --- a/doc/solver/optimizeProb.html +++ /dev/null @@ -1,344 +0,0 @@ - - - - Description of optimizeProb - - - - - - - - - -
Home > solver > optimizeProb.m
- - - -

optimizeProb -

- -

PURPOSE ^

-
optimizeProb
- -

SYNOPSIS ^

-
function res = optimizeProb(prob,params,verbose)
- -

DESCRIPTION ^

-
 optimizeProb
-   Optimize an LP or MILP formulated in cobra terms.
-
-   prob    cobra style LP/MILP problem struct to be optimised
-   params    solver specific parameters (optional)
-   verbose if true MILP progress is shown (optional, default true)
-
-   res        the output structure from the selected solver RAVENSOLVER
-           (cobra style)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 function res = optimizeProb(prob,params,verbose)
-0002 % optimizeProb
-0003 %   Optimize an LP or MILP formulated in cobra terms.
-0004 %
-0005 %   prob    cobra style LP/MILP problem struct to be optimised
-0006 %   params    solver specific parameters (optional)
-0007 %   verbose if true MILP progress is shown (optional, default true)
-0008 %
-0009 %   res        the output structure from the selected solver RAVENSOLVER
-0010 %           (cobra style)
-0011 
-0012 if nargin<2 || isempty(params)
-0013     params=struct();
-0014 end
-0015 if nargin<3 || isempty(verbose)
-0016     verbose = true;
-0017 end
-0018 
-0019 %Set as global variable for speed improvement if optimizeProb is run many times
-0020 global RAVENSOLVER;
-0021 if isempty(RAVENSOLVER)
-0022     if(~ispref('RAVEN','solver'))
-0023         dispEM('RAVEN solver not defined or unknown. Try using setRavenSolver(''solver'').');
-0024     else
-0025         RAVENSOLVER = getpref('RAVEN','solver');
-0026     end
-0027 end
-0028 solver=RAVENSOLVER;
-0029 if ~all(lower(prob.vartype) == 'c')
-0030     milp=true;
-0031     errorText = 'glpk is not suitable for solving MILPs, ';
-0032     switch solver
-0033         case 'glpk'
-0034             error([errorText 'select a different solver with setRavenSolver().'])
-0035         case 'cobra'
-0036             if strcmp(CBT_MILP_SOLVER,'glpk')
-0037                 error([errorText 'select a different solver with changeCobraSolver() or setRavenSolver().'])
-0038             end
-0039     end
-0040 else
-0041     milp=false;
-0042 end
-0043 
-0044 %% Define default parameters, which will then be used to make solver-
-0045 % specific solverparams structures
-0046 defaultparams.feasTol        = 1e-9;
-0047 defaultparams.optTol         = 1e-9;
-0048 defaultparams.objTol         = 1e-6;
-0049 defaultparams.timeLimit      = 1000;
-0050 %defaultparams.iterationLimit = 1000;
-0051 defaultparams.intTol         = 1e-12;
-0052 defaultparams.relMipGapTol   = 1e-12;
-0053 defaultparams.absMipGapTol   = 1e-12;
-0054 if milp
-0055     defaultparams.MIPGap     = 1e-12;
-0056     defaultparams.Seed       = 1;
-0057 end
-0058 res.obj=[];
-0059 switch solver
-0060     %% Use whatever solver is set by COBRA Toolbox changeCobraSolver
-0061     case 'cobra'
-0062         if milp
-0063             cparams=struct('timeLimit',1e9,'printLevel',0,'intTol',1e-6,'relMipGapTol',1e-9);
-0064             cparams=structUpdate(cparams,params);
-0065             res=solveCobraMILP(prob,cparams);
-0066         else
-0067             res=solveCobraLP(prob);
-0068         end
-0069         if isfield(res,{'dual','rcost'})
-0070             res.dual=res.dual;
-0071             res.rcost=res.rcost;
-0072         end
-0073 
-0074         %% Use Gurobi in a MATLAB environment
-0075     case 'gurobi'
-0076         if milp
-0077             if verbose
-0078                 solverparams.OutputFlag = 1;
-0079             else
-0080                 solverparams.OutputFlag = 0;
-0081             end
-0082             solverparams.IntFeasTol = 10^-9; %min val for gurobi
-0083             solverparams.MIPGap = defaultparams.MIPGap;
-0084             solverparams.Seed = defaultparams.Seed;
-0085         else
-0086             solverparams.OutputFlag = 0;
-0087         end
-0088         solverparams.DisplayInterval= 1; % Level of verbosity
-0089         solverparams.TimeLimit      = defaultparams.timeLimit;
-0090         solverparams.FeasibilityTol = defaultparams.feasTol;
-0091         solverparams.OptimalityTol  = defaultparams.optTol;
-0092         solverparams.Presolve       = 2;
-0093         % If run in parallel, then one thread per gurobi. getCurrentTask
-0094         % requires the Parallel Computing Toolbox.
-0095         try
-0096             inParallel = ~isempty(getCurrentTask);
-0097         catch
-0098             inParallel = false;
-0099         end
-0100         if inParallel
-0101             solverparams.Threads=1;
-0102         end
-0103         solverparams = structUpdate(solverparams,params);
-0104 
-0105         % Restructering problem according to gurobi format
-0106         if isfield(prob, 'csense')
-0107             prob.sense = renameparams(prob.csense, {'L','G','E'}, {'<','>','='});
-0108             prob = rmfield(prob, {'csense'});
-0109         end
-0110         if isfield(prob, 'osense')
-0111             osense = prob.osense;
-0112             prob.modelsense = renameparams(num2str(prob.osense), {'1','-1'}, {'min','max'});
-0113             prob = rmfield(prob, {'osense'});
-0114         end
-0115         [prob.obj, prob.rhs, prob.vtype] = deal(prob.c, prob.b, prob.vartype);
-0116         prob = rmfield(prob, {'c','b','vartype'});
-0117 
-0118         resG = gurobi(prob,solverparams);
-0119 
-0120         try
-0121             % Name output fields the same as COBRA does
-0122             res.full     = resG.x;
-0123             res.obj      = resG.objval;
-0124             res.origStat = resG.status;
-0125             if isfield(resG,{'pi','rc'})
-0126                 res.dual     = -resG.pi*osense;
-0127                 res.rcost    = -resG.rc*osense;
-0128             end
-0129             if milp && strcmp(resG.status, 'TIME_LIMIT')
-0130                 % If res has the objval field, it succeeded, regardless of
-0131                 % time_limit status
-0132                 resG.status = 'OPTIMAL';
-0133             end
-0134             switch resG.status
-0135                 case 'OPTIMAL'
-0136                     res.stat = 1;
-0137                 case 'UNBOUNDED'
-0138                     res.stat = 2;
-0139                 otherwise
-0140                     res.stat = 0;
-0141             end
-0142             if ~milp
-0143                 res.vbasis = resG.vbasis;
-0144                 res.cbasis = resG.cbasis;
-0145             else
-0146                 res.mipgap = resG.mipgap;
-0147             end
-0148         catch
-0149             res.stat = 0;
-0150             res.origStat = resG.status;  % useful information to have
-0151         end
-0152         %% Use GLPK using RAVEN-provided binary
-0153     case 'glpk'
-0154         solverparams.scale   = 1; % Auto scaling
-0155         %solverparams.tmlim   = defaultparams.timeLimit;
-0156         solverparams.tolbnd  = defaultparams.feasTol;
-0157         solverparams.toldj   = defaultparams.optTol;
-0158         solverparams.tolint  = defaultparams.intTol;
-0159         solverparams.tolobj  = defaultparams.objTol;
-0160         solverparams.msglev  = 0; % Level of verbosity
-0161         solverparams = structUpdate(solverparams,params);
-0162 
-0163         prob.csense = renameparams(prob.csense, {'L','G','E'}, {'U','L','S'});
-0164 
-0165         if milp
-0166             solverparams.tmlim   = solverparams.tmlim*10;
-0167             solverparams.msglev  = 1; % Level of verbosity
-0168             disp('Issues have been observed when using GLPK for MILP solving. Be advised to carefully observe the results, or us another solver.')
-0169         end
-0170 
-0171         % Ensure that RAVEN glpk binary is used, return to original
-0172         % directory afterwards
-0173         [ravenDir,currDir]=findRAVENroot();
-0174         cd(fullfile(ravenDir,'software','GLPKmex'))
-0175         [xopt, fmin, errnum, extra] = glpk(prob.c, prob.A, prob.b, prob.lb, prob.ub, prob.csense, prob.vartype, prob.osense, solverparams);
-0176         cd(currDir)
-0177 
-0178         switch errnum % 1 = undefined; 2 = feasible; 3 = infeasible; 4 = no feasible solution; 5 = optimal; 6 = no unbounded solution
-0179             case 5
-0180                 res.stat = 1; % Optimal
-0181             case 2
-0182                 res.stat = 2; % Feasible, but not optimal
-0183             otherwise
-0184                 res.stat = 0;
-0185         end
-0186         res.origStat = errnum;
-0187         res.full     = xopt;
-0188         res.obj      = fmin;
-0189         res.dual     = -extra.lambda*prob.osense;
-0190         res.rcost    = -extra.redcosts*prob.osense;
-0191         %% Use scip
-0192     case {'soplex','scip'} % Old 'soplex' option also allowed
-0193         [xopt,fval,exitflag] = scip([], prob.c, prob.A,-prob.b, prob.b, prob.lb, prob.ub, prob.vartype);
-0194 
-0195         %   [x,fval,exitflag,stats] = scip(H, f, A, rl, ru, lb, ub, xtype, sos, qc, nl, x0, opts)
-0196         %
-0197         %   Input arguments*:
-0198         %       H - quadratic objective matrix (sparse, optional [NOT TRIL / TRIU])
-0199         %       f - linear objective vector
-0200         %       A - linear constraint matrix (sparse)
-0201         %       rl - linear constraint lhs
-0202         %       ru - linear constraint rhs
-0203         %       lb - decision variable lower bounds
-0204         %       ub - decision variable upper bounds
-0205         %       xtype - string of variable integrality ('c' continuous, 'i' integer, 'b' binary)
-0206         %       sos - SOS structure with fields type, index and weight (see below)
-0207         %       qc - Quadratic Constraints structure with fields Q, l, qrl and qru (see below)
-0208         %       nl - Nonlinear Objective and Constraints structure (see below)
-0209         %       x0 - primal solution
-0210         %       opts - solver options (see below)
-0211         %
-0212         %   Return arguments:
-0213         %       x - solution vector
-0214         %       fval - objective value at the solution
-0215         %       exitflag - exit status (see below)
-0216         %       stats - statistics structure
-0217         %
-0218         %   Option Fields (all optional, see also optiset for a list):
-0219         %       solverOpts - specific SCIP options (list of pairs of parameter names and values)
-0220         %       maxiter - maximum LP solver iterations
-0221         %       maxnodes - maximum nodes to explore
-0222         %       maxtime - maximum execution time [s]
-0223         %       tolrfun - primal feasibility tolerance
-0224         %       display - solver display level [0-5]
-0225         %       probfile - write problem to given file
-0226         %       presolvedfile - write presolved problem to file
-0227         %
-0228         %   Return Status:
-0229         %       0 - Unknown
-0230         %       1 - User Interrupted
-0231         %       2 - Node Limit Reached
-0232         %       3 - Total Node Limit Reached
-0233         %       4 - Stall Node Limit Reached
-0234         %       5 - Time Limit Reached
-0235         %       6 - Memory Limit Reached
-0236         %       7 - Gap Limit Reached
-0237         %       8 - Solution Limit Reached
-0238         %       9 - Solution Improvement Limit Reached
-0239         %      10 - Restart Limit Reached
-0240         %      11 - Problem Solved to Optimality
-0241         %      12 - Problem is Infeasible
-0242         %      13 - Problem is Unbounded
-0243         %      14 - Problem is Either Infeasible or Unbounded
-0244         
-0245         res.origStat = exitflag;
-0246         res.full = xopt;
-0247         res.obj  = fval;
-0248 
-0249         switch exitflag
-0250             case 11
-0251                 res.stat = 1;
-0252             case {1, 5, 6, 7, 8, 9, 10, 13} % If user-interrupted, not sure if optimal
-0253                 res.stat = 2;
-0254             otherwise
-0255                 res.stat = 0;
-0256         end
-0257     otherwise
-0258         error('RAVEN solver not defined or unknown. Try using setRavenSolver(''solver'').');
-0259 end
-0260 if res.stat>0
-0261     res.full=res.full(1:size(prob.a,2));
-0262 end
-0263 end
-0264 
-0265 function s_merged=structUpdate(s_old,s_new)
-0266 %Remove overlapping fields from first struct;
-0267 %Obtain all unique names of remaining fields;
-0268 %Merge both structs
-0269 s_merged = rmfield(s_old, intersect(fieldnames(s_old), fieldnames(s_new)));
-0270 names = [fieldnames(s_merged); fieldnames(s_new)];
-0271 s_merged = cell2struct([struct2cell(s_merged); struct2cell(s_new)], names, 1);
-0272 end
-0273 
-0274 function paramlist = renameparams(paramlist,old,new)
-0275 if ~iscell(paramlist)
-0276     wasNoCell = true;
-0277     paramlist={paramlist};
-0278 else
-0279     wasNoCell = false;
-0280 end
-0281 for i=1:numel(old)
-0282     paramlist = regexprep(paramlist,old{i},new{i});
-0283 end
-0284 if wasNoCell
-0285     paramlist=paramlist{1};
-0286 end
-0287 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/solver/qMOMA.html b/doc/solver/qMOMA.html deleted file mode 100644 index 8308a3365..000000000 --- a/doc/solver/qMOMA.html +++ /dev/null @@ -1,150 +0,0 @@ - - - - Description of qMOMA - - - - - - - - - -
Home > solver > qMOMA.m
- - - -

qMOMA -

- -

PURPOSE ^

-
qMOMA
- -

SYNOPSIS ^

-
function [fluxA,fluxB, flag]=qMOMA(modelA,modelB,fluxMinWeight)
- -

DESCRIPTION ^

-
 qMOMA
-   Uses quadratic programming to minimize the sum((fluxAi - fluxBi)^2)
-
-   modelA        a model structure for the test case. This model must be a
-                 subset of modelB (no reactions that are not in modelB)
-   modelB        a model structure for the reference case
-   fluxMinWeight a double >=1 that determines whether minimization of the
-                 sum of fluxes should also be taken into account in the
-                 optimization. A value of 2.0 means that sum(fluxAi)^2 +
-                 sum(fluxBi)^2 has equal weight as sum((fluxAi - fluxBi)^2).
-                 Values of around 1.01 should be enough to get rid of loops
-                 (optional, default 1)
-
-   fluxA         the resulting flux distribution in the test model
-   fluxB         the resulting flux distribution in the reference model
-   flag          1 if the optimization terminated successfully
-
- Usage: [fluxA,fluxB, flag]=qMOMA(modelA,modelB,fluxMinWeight)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function [fluxA,fluxB, flag]=qMOMA(modelA,modelB,fluxMinWeight)
-0002 % qMOMA
-0003 %   Uses quadratic programming to minimize the sum((fluxAi - fluxBi)^2)
-0004 %
-0005 %   modelA        a model structure for the test case. This model must be a
-0006 %                 subset of modelB (no reactions that are not in modelB)
-0007 %   modelB        a model structure for the reference case
-0008 %   fluxMinWeight a double >=1 that determines whether minimization of the
-0009 %                 sum of fluxes should also be taken into account in the
-0010 %                 optimization. A value of 2.0 means that sum(fluxAi)^2 +
-0011 %                 sum(fluxBi)^2 has equal weight as sum((fluxAi - fluxBi)^2).
-0012 %                 Values of around 1.01 should be enough to get rid of loops
-0013 %                 (optional, default 1)
-0014 %
-0015 %   fluxA         the resulting flux distribution in the test model
-0016 %   fluxB         the resulting flux distribution in the reference model
-0017 %   flag          1 if the optimization terminated successfully
-0018 %
-0019 % Usage: [fluxA,fluxB, flag]=qMOMA(modelA,modelB,fluxMinWeight)
-0020 
-0021 if nargin<3
-0022     fluxMinWeight=1;
-0023 end
-0024 
-0025 %Match the reactions and metabolites in the small model (modelA) to the
-0026 %larger model
-0027 [rxnExists,mapRxns]=ismember(modelA.rxns,modelB.rxns);
-0028 
-0029 %Check that the smaller model is a subset of the larger one
-0030 if any(~rxnExists)
-0031     dispEM('All reactions in the test model must exist in the reference model');
-0032 end
-0033 
-0034 %In order to make the calculations a little easier to formulate I reshape
-0035 %modelA.S so that it is the same dimension as modelB.S
-0036 S=modelA.S;
-0037 lb=modelA.lb;
-0038 ub=modelA.ub;
-0039 c=modelA.c;
-0040 modelA.S=sparse(numel(modelA.mets),numel(modelB.rxns));
-0041 modelA.lb=zeros(numel(modelB.rxns),1);
-0042 modelA.ub=modelA.lb;
-0043 modelA.c=modelA.lb;
-0044 modelA.S(:,mapRxns)=S;
-0045 modelA.lb(mapRxns)=lb;
-0046 modelA.ub(mapRxns)=ub;
-0047 modelA.c(mapRxns)=c;
-0048 
-0049 %Create the H matrix for the quadratic problem. Note that there are no
-0050 %linear terms in the equation
-0051 
-0052 %Equation to solve is:(xA1 - xB1)^2 + (xA2 - xB2)^2 ....
-0053 %Is equal to xA1^2 - xA1*xB1 - xB1*xA1 + xB1^2 + xA2^2 - xA2*xB2 - xB2*xA2 + xB2^2...
-0054 
-0055 %For three fluxes this would give the following H matrix (first three rows
-0056 %for A and last three rows for B)
-0057 
-0058 %   A1 A2 A3 B1 B2 B3
-0059 %A1 1  0  0  -1  0  0
-0060 %A2 0  1  0  0  -1  0
-0061 %A3 0  0  1  0  0  -1
-0062 %B1 -1  0  0  1  0  0
-0063 %B2 0  -1  0  0  1  0
-0064 %B3 0  0  -1  0  0  1
-0065 
-0066 %Create stoichiometric matrix and bounds that contain both models
-0067 fullS=[modelA.S sparse(size(modelA.S,1),size(modelA.S,2));sparse(size(modelB.S,1),size(modelB.S,2)) modelB.S];
-0068 fullLB=[modelA.lb;modelB.lb];
-0069 fullUB=[modelA.ub;modelB.ub];
-0070 fullB=zeros(size(modelA.S,1)+size(modelB.S,1),1);
-0071 
-0072 H=[eye(size(fullS,2)/2)*fluxMinWeight eye(size(fullS,2)/2)*-1;eye(size(fullS,2)/2)*-1 eye(size(fullS,2)/2)*fluxMinWeight];
-0073 
-0074 x=quadprog(H,zeros(size(H,1),1),[],[],fullS,fullB,fullLB,fullUB);
-0075 
-0076 if any(x)
-0077     fluxA=x(1:numel(modelB.rxns));
-0078     fluxA=fluxA(mapRxns);
-0079     fluxB=x(numel(modelB.rxns)+1:end);
-0080     flag=1; %Since it never converges good enough
-0081 else
-0082     fluxA=zeros(numel(modelA.rxns),1); %Still the old number
-0083     fluxB=zeros(numel(modelB.rxns),1);
-0084     flag=-1;
-0085 end
-0086 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/solver/setRavenSolver.html b/doc/solver/setRavenSolver.html deleted file mode 100644 index b81747549..000000000 --- a/doc/solver/setRavenSolver.html +++ /dev/null @@ -1,119 +0,0 @@ - - - - Description of setRavenSolver - - - - - - - - - -
Home > solver > setRavenSolver.m
- - - -

setRavenSolver -

- -

PURPOSE ^

-
setRavenSolver
- -

SYNOPSIS ^

-
function setRavenSolver(solver)
- -

DESCRIPTION ^

-
 setRavenSolver
-   Sets the solver for RAVEN and optionally saves a default value
-    to MATLAB startup.
-
-   solver  string with solver name. The following options are available:
-           glpk    uses RAVEN-provided binaries
-           gurobi  requires a working Gurobi installation
-           cobra   requires a working COBRA Toolbox installation. RAVEN
-                   parses the problem to COBRA and uses the solver that is
-                   set by changeCobraSolver.
-
- Usage: setRavenSolver(solver)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function setRavenSolver(solver)
-0002 % setRavenSolver
-0003 %   Sets the solver for RAVEN and optionally saves a default value
-0004 %    to MATLAB startup.
-0005 %
-0006 %   solver  string with solver name. The following options are available:
-0007 %           glpk    uses RAVEN-provided binaries
-0008 %           gurobi  requires a working Gurobi installation
-0009 %           cobra   requires a working COBRA Toolbox installation. RAVEN
-0010 %                   parses the problem to COBRA and uses the solver that is
-0011 %                   set by changeCobraSolver.
-0012 %
-0013 % Usage: setRavenSolver(solver)
-0014 solver=char(solver);
-0015 switch solver
-0016     case 'cobra'
-0017         global CBT_LP_SOLVER;
-0018         if isempty(CBT_LP_SOLVER)
-0019             error('COBRA toolbox is not initialized, run ''initCobraToolbox()''')
-0020         else
-0021             setpref('RAVEN','solver','cobra');
-0022         end
-0023     case 'mosek'
-0024         error('MOSEK support has been discontinued since RAVEN 2.3.0.')
-0025     case {'glpk','gurobi'}
-0026         setpref('RAVEN','solver',solver)
-0027     case 'soplex'
-0028         error('The ''soplex'' solver is replaced by ''scip''.')
-0029     case 'scip'
-0030         if ~ispc
-0031             try
-0032                 scip; % The user might have installed SCIP manually
-0033                 setpref('RAVEN','solver','scip')
-0034             catch
-0035                 error('SCIP not found. RAVEN only provides the precompiled SCIP MEX binary for Windows. Instructions on how to compile the SCIP MEX file are found at https://github.com/scipopt/MatlabSCIPInterface')
-0036             end
-0037         else
-0038             ravenDir = findRAVENroot();
-0039             if ~exist(fullfile(ravenDir,'software','scip','scip.mexw64'),'file')
-0040                 try
-0041                     disp('Downloading and installing RAVEN-provided SCIP MEX binary...')
-0042                     websave(fullfile(ravenDir,'software','scip_mex_win.zip'),'https://github.com/SysBioChalmers/RAVEN/releases/download/v2.8.6/scip_mex_win.zip'); % Should be updated to release with SCIP functionality
-0043                 catch
-0044                     error('Unable to download SCIP MEX binary from the RAVEN GitHub page.')
-0045                 end
-0046                 unzip(fullfile(ravenDir,'software','scip_mex_win.zip'),fullfile(ravenDir,'software','scip'));
-0047                 delete(fullfile(ravenDir,'software','scip_mex_win.zip'));
-0048             end
-0049             try
-0050                 scip; % The pre-compiled MEX file might fail
-0051                 setpref('RAVEN','solver','scip')
-0052             catch
-0053                 error('Unable to use the RAVEN-provided precompiled SCIP MEX binary. Instructions on how to compile the SCIP MEX file are found at https://github.com/scipopt/MatlabSCIPInterface')
-0054             end
-0055         end
-0056     otherwise
-0057         error('Invalid solver defined')
-0058 end
-0059 global RAVENSOLVER
-0060 RAVENSOLVER = solver;
-0061 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/solver/solveLP.html b/doc/solver/solveLP.html deleted file mode 100644 index 9cec93be7..000000000 --- a/doc/solver/solveLP.html +++ /dev/null @@ -1,310 +0,0 @@ - - - - Description of solveLP - - - - - - - - - -
Home > solver > solveLP.m
- - - -

solveLP -

- -

PURPOSE ^

-
solveLP
- -

SYNOPSIS ^

-
function [solution, hsSolOut]=solveLP(model,minFlux,params,hsSol)
- -

DESCRIPTION ^

-
 solveLP
-   Solves a linear programming problem
-
- Input:
-   model         a model structure
-   minFlux       determines if a second optimization should be performed
-                 in order to get rid of loops in the flux distribution
-                 0:    no such optimization is performed
-                 1:    the sum of abs(fluxes) is minimized. This is the
-                       fastest way of getting rid of loops
-                 2:    *option is deprecated*
-                 3:    the number of fluxes is minimized. This can result
-                       in the flux distributions that are the easiest to
-                       interpret. Note that this optimization can be very
-                       slow
-                 (optional, default 0)
-   params        *obsolete option*
-   hsSol         hot-start solution for the LP solver. This can
-                 significantly speed up the process if many similar
-                 optimization problems are solved iteratively. Only used
-                 if minFlux is 0 or 1 (optional)
-
- Output:
-   solution
-         f       objective value
-         x       primal (flux distribution)
-         stat    exit flag
-                 1: the optimization terminated successfully
-                 0: the solution is feasible, but not necessarily optimal
-                -1: no feasible solution found
-                -2: solution found, but flux minimization failed
-         msg     string describing the status of the optimization
-         sPrice  shadow price (only reported if minFlux was 0)
-         rCost   reduced cost (only reported if minFlux was 0)
-   hsSolOut      solution to be used as hot-start solution (see the input
-                 parameters). Only used if minFlux is 0 or 1
-
- Usage: [solution, hsSolOut] = solveLP(model, minFlux, params, hsSol)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: - - - - - -

SOURCE CODE ^

-
0001 function [solution, hsSolOut]=solveLP(model,minFlux,params,hsSol)
-0002 % solveLP
-0003 %   Solves a linear programming problem
-0004 %
-0005 % Input:
-0006 %   model         a model structure
-0007 %   minFlux       determines if a second optimization should be performed
-0008 %                 in order to get rid of loops in the flux distribution
-0009 %                 0:    no such optimization is performed
-0010 %                 1:    the sum of abs(fluxes) is minimized. This is the
-0011 %                       fastest way of getting rid of loops
-0012 %                 2:    *option is deprecated*
-0013 %                 3:    the number of fluxes is minimized. This can result
-0014 %                       in the flux distributions that are the easiest to
-0015 %                       interpret. Note that this optimization can be very
-0016 %                       slow
-0017 %                 (optional, default 0)
-0018 %   params        *obsolete option*
-0019 %   hsSol         hot-start solution for the LP solver. This can
-0020 %                 significantly speed up the process if many similar
-0021 %                 optimization problems are solved iteratively. Only used
-0022 %                 if minFlux is 0 or 1 (optional)
-0023 %
-0024 % Output:
-0025 %   solution
-0026 %         f       objective value
-0027 %         x       primal (flux distribution)
-0028 %         stat    exit flag
-0029 %                 1: the optimization terminated successfully
-0030 %                 0: the solution is feasible, but not necessarily optimal
-0031 %                -1: no feasible solution found
-0032 %                -2: solution found, but flux minimization failed
-0033 %         msg     string describing the status of the optimization
-0034 %         sPrice  shadow price (only reported if minFlux was 0)
-0035 %         rCost   reduced cost (only reported if minFlux was 0)
-0036 %   hsSolOut      solution to be used as hot-start solution (see the input
-0037 %                 parameters). Only used if minFlux is 0 or 1
-0038 %
-0039 % Usage: [solution, hsSolOut] = solveLP(model, minFlux, params, hsSol)
-0040 
-0041 if nargin<2
-0042     minFlux=0;
-0043 end
-0044 if nargin<3
-0045     params.relGap=0.4;
-0046 end
-0047 if nargin<4
-0048     hsSol=[];
-0049 end
-0050 
-0051 %Default return values
-0052 hsSolOut=[];
-0053 solution.x=[];
-0054 solution.f=[];
-0055 solution.stat=-1;
-0056 
-0057 %Check for valid lb and ub
-0058 if ~isnumeric([model.lb,model.ub])
-0059     invalidBound = true(numel(model.lb),1);
-0060 else
-0061     invalidBound = false(numel(model.lb),1);
-0062 end
-0063 invalidBound = invalidBound | model.lb>model.ub;
-0064 invalidBound = invalidBound | logical(sum(isnan([model.lb,model.ub]),2));
-0065 if any(invalidBound)
-0066     error(['Invalid set of bounds for reaction(s): ', strjoin(model.rxns(invalidBound),', '), '.'])
-0067 end
-0068 %Check for valid objective
-0069 if ~isnumeric(model.c) || any(isnan(model.c))
-0070     error('Invalid defintion of objective function in model.c.')
-0071 end
-0072 %Check for valid S-matrix
-0073 if ~allfinite(model.S)
-0074     invalidS = ~isfinite(model.S);
-0075     error(['Invalid coefficients defined for reaction(s): ', strjoin(model.rxns(any(invalidS)),', '), '.'])
-0076 end
-0077 
-0078 %Ignore the hot-start if the previous solution wasn't feasible
-0079 if isfield(hsSol,'stat')
-0080     if hsSol.stat<1
-0081         hsSol=[];
-0082     end
-0083 end
-0084 
-0085 % Setup the linear problem for glpk
-0086 prob        = [];
-0087 prob.c      = [model.c*-1;zeros(size(model.S,1),1)];
-0088 prob.b      = zeros(size(model.S,1), 1);
-0089 prob.lb     = [model.lb; model.b(:,1)];
-0090 prob.ub     = [model.ub; model.b(:,min(size(model.b,2),2))];
-0091 prob.csense = repmat('E', 1, length(prob.b)); % Equality constraints
-0092 prob.osense = 1; 
-0093 prob.vartype = repmat('C', 1, length(prob.c)); % Fluxes are continuous values
-0094 prob.A = [model.S -speye(size(model.S,1))];
-0095 prob.a = model.S;
-0096 
-0097 %If hot-start should be used
-0098 if ~isempty(hsSol)
-0099     prob.vbasis=hsSol.vbasis;
-0100     prob.cbasis=hsSol.cbasis;
-0101 end
-0102 
-0103 % Parse the problem to the LP solver
-0104 res = optimizeProb(prob,params);
-0105 % Swap the sign of the obj-value
-0106 res.obj = -res.obj;
-0107 
-0108 %Check if the problem was feasible and that the solution was optimal
-0109 [isFeasible, isOptimal]=checkSolution(res);
-0110 
-0111 %If the problem was infeasible using hot-start it is often possible to
-0112 %re-solve it without hot-start and get a feasible solution
-0113 if ~isFeasible && ~isempty(hsSol)
-0114     prob=rmfield(prob,{'vbasis','cbasis'});
-0115     res=optimizeProb(prob,params);
-0116     [isFeasible, isOptimal]=checkSolution(res);
-0117 end
-0118 
-0119 %Return without solution if the problem was infeasible
-0120 if ~isFeasible
-0121     solution.msg='The problem is infeasible';
-0122     return;
-0123 end
-0124 if ~isOptimal
-0125     solution.msg='The problem is feasible, but not necessarily optimal';
-0126     solution.stat=0;
-0127 else
-0128     %All is well
-0129     solution.stat=1;
-0130     solution.msg='Optimal solution found';
-0131 end
-0132 
-0133 %Construct the output structure
-0134 if isfield(res,'full')
-0135     solution.x=res.full;
-0136     if minFlux<=1
-0137         if(isfield(res,'vbasis')) % gurobi uses vbasis and cbasis as hotstart
-0138             hsSolOut.vbasis=res.vbasis;
-0139             hsSolOut.cbasis=res.cbasis;
-0140         end
-0141     end
-0142     solution.f=res.obj;
-0143 if isfield(res,'dual')
-0144     solution.sPrice=res.dual;
-0145 else
-0146     solution.sPrice=[];
-0147 end
-0148 if isfield(res,'rcost')
-0149     solution.rCost=res.rcost(1:numel(model.rxns));
-0150 else
-0151     solution.rCost=[];
-0152 end
-0153 
-0154 %If either the square, the number, or the sum of fluxes should be minimized
-0155 %then the objective function value should be fixed before another
-0156 %optimization. It is not correct to fix the reactions which participate in
-0157 %the objective function to their values in solution.x, as there can be
-0158 %multiple solutions with the same objective function value. In addition,
-0159 %this approach could result in numerical issues when several fluxes are
-0160 %fixed. Instead a new "fake metabolite" is added to the problem. This
-0161 %metabolite is produced by each reaction with the stoichiometry that
-0162 %reaction has in the objective function. The equality constraint of that
-0163 %"fake metabolite" is then set to be at least as good as the objective
-0164 %function value.
-0165 if minFlux~=0
-0166     model.S=[model.S;model.c'];
-0167     model.mets=[model.mets;'TEMP'];
-0168     
-0169     %If the constraint on the objective function value is exact there is a
-0170     %larger risk of numerical errors. However for the quadratic fitting
-0171     %intervals are not allowed
-0172     if minFlux~=2
-0173         if size(model.b,2)==1
-0174             model.b=[model.b model.b];
-0175         end
-0176         if solution.f>0
-0177             model.b=[model.b;[solution.f*0.999999 inf]];
-0178         else
-0179             model.b=[model.b;[solution.f*1.000001 inf]];
-0180         end
-0181     else
-0182         model.b=[model.b;ones(1,size(model.b,2))*solution.f];
-0183     end
-0184     
-0185     switch minFlux
-0186         %The sum of fluxes should be minimized
-0187         case 1
-0188             %Convert the model to the irreversible format
-0189             revRxns=find(model.rev);
-0190             if ~isempty(revRxns)
-0191                 iModel=convertToIrrev(model);
-0192             else
-0193                 iModel=model;
-0194             end
-0195             %Minimize all fluxes
-0196             iModel.c(:)=-1;
-0197             sol=solveLP(iModel,0,params);
-0198             
-0199             %Map back to reversible fluxes
-0200             if sol.stat>=0
-0201                 solution.x=sol.x(1:numel(model.c));
-0202                 solution.x(revRxns)=solution.x(revRxns)-sol.x(numel(model.c)+1:end);
-0203             else
-0204                 EM='Could not solve the problem of minimizing the sum of fluxes. Uses output from original problem';
-0205                 dispEM(EM,false);
-0206                 solution.stat=-2;
-0207             end
-0208             
-0209         case 2
-0210             error('%Minimization of square of fluxes is deprecated')
-0211             
-0212             %The number of fluxes should be minimized
-0213         case 3
-0214             [qx,I]=getMinNrFluxes(model,model.rxns,params);
-0215             qx(~I)=0;
-0216             if any(I)
-0217                 solution.x=qx;
-0218             else
-0219                 EM='Could not solve the problem of minimizing the number of fluxes. Uses output from linear program';
-0220                 dispEM(EM,false);
-0221                 solution.stat=-2;
-0222             end
-0223     end
-0224     solution=rmfield(solution,{'sPrice','rCost'});
-0225 end
-0226 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/solver/solveQP.html b/doc/solver/solveQP.html deleted file mode 100644 index 53efd240b..000000000 --- a/doc/solver/solveQP.html +++ /dev/null @@ -1,127 +0,0 @@ - - - - Description of solveQP - - - - - - - - - -
Home > solver > solveQP.m
- - - -

solveQP -

- -

PURPOSE ^

-
solveQP
- -

SYNOPSIS ^

-
function solution=solveQP(model,rxns,values,maxIter, restartIter)
- -

DESCRIPTION ^

-
 solveQP
-   Solves a quadratic fitting problem.
-
-   model         a model structure
-   rxns          either a cell array of reaction IDs, a logical vector 
-                 with the same number of elements as reactions in the model,
-                 of a vector of indexes to fit to
-   values        the values to fit the fluxes to
-   maxIter       maximal number of iterations (optional, default 1000)
-   restartIter   run the fitting up to this many times in case it does
-                 not converge (optional, default 1)
-
-   solution
-         f       Objective value
-         x       Primal
-         stat    Exit flag
-
- Usage: solution=solveQP(model,rxns,values,maxIter, restartIter)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function solution=solveQP(model,rxns,values,maxIter, restartIter)
-0002 % solveQP
-0003 %   Solves a quadratic fitting problem.
-0004 %
-0005 %   model         a model structure
-0006 %   rxns          either a cell array of reaction IDs, a logical vector
-0007 %                 with the same number of elements as reactions in the model,
-0008 %                 of a vector of indexes to fit to
-0009 %   values        the values to fit the fluxes to
-0010 %   maxIter       maximal number of iterations (optional, default 1000)
-0011 %   restartIter   run the fitting up to this many times in case it does
-0012 %                 not converge (optional, default 1)
-0013 %
-0014 %   solution
-0015 %         f       Objective value
-0016 %         x       Primal
-0017 %         stat    Exit flag
-0018 %
-0019 % Usage: solution=solveQP(model,rxns,values,maxIter, restartIter)
-0020 rxns=char(rxns);
-0021 
-0022 if nargin<4
-0023     maxIter=1000;
-0024 end
-0025 
-0026 if nargin<5
-0027     restartIter=1;
-0028 end
-0029 
-0030 %Check that it's feasible
-0031 solution=solveLP(model);
-0032 if isempty(solution.x)
-0033     return;
-0034 end
-0035 
-0036 %Get the indexes of the fluxes to fit
-0037 allIndexes=getIndexes(model,rxns,'rxns');
-0038 
-0039 f=zeros(numel(model.rxns),1);
-0040 H=zeros(numel(model.rxns));
-0041 
-0042 %Get the fitIndexes for the experiment
-0043 for j=1:numel(allIndexes) %Not that neat
-0044     H(allIndexes(j),allIndexes(j))=2;
-0045 end
-0046 
-0047 f(allIndexes)=values.*-2;
-0048 
-0049 %For a badly formulated problem it can occur that the solver stalls. This
-0050 %can sometimes be fixed by trying to solve the problem again
-0051 options=optimset('MaxIter',maxIter);
-0052 for j=1:restartIter
-0053     [x,fval,flag] = ...
-0054         quadprog(H,f,[],[],model.S,model.b,model.lb,model.ub,[],options);
-0055     if flag>0
-0056         break;
-0057     end
-0058 end
-0059 
-0060 solution.f=fval;
-0061 solution.x=x;
-0062 solution.stat=flag;
-0063 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/struct_conversion/addIdentifierPrefix.html b/doc/struct_conversion/addIdentifierPrefix.html deleted file mode 100644 index de10d34d8..000000000 --- a/doc/struct_conversion/addIdentifierPrefix.html +++ /dev/null @@ -1,128 +0,0 @@ - - - - Description of addIdentifierPrefix - - - - - - - - - -
Home > struct_conversion > addIdentifierPrefix.m
- - - -

addIdentifierPrefix -

- -

PURPOSE ^

-
addIdentifierPrefix
- -

SYNOPSIS ^

-
function [model, hasChanged]=addIdentifierPrefix(model,fields)
- -

DESCRIPTION ^

-
 addIdentifierPrefix
-   If reaction, metabolite, compartment, gene or model identifiers do not
-   start with a letter or _, which conflicts with SBML specifications,
-   prefixes are added for all identifiers in the respective model field.
-   The prefixes are:
-       "R_" for model.rxns,
-       "M_" for model.mets,
-       "C_" for model.comps;
-       "G_" for model.genes (and also represented in model.grRules)
-
- Input:
-   model           model whose identifiers should be modified
-   fields          cell array with model field names that should be
-                   checked if prefixes should be added, possible values: 
-                   'rxns', 'mets', 'comps', 'genes', 'id'. (optional, by
-                   default all listed model fields will be checked).
-
- Output:
-   model           modified model
-   hasChanged      cell array with fields and prefixes that are added
-
- Usage: [model, hasChanged]=addIdentifierPrefix(model,fields)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function [model, hasChanged]=addIdentifierPrefix(model,fields)
-0002 % addIdentifierPrefix
-0003 %   If reaction, metabolite, compartment, gene or model identifiers do not
-0004 %   start with a letter or _, which conflicts with SBML specifications,
-0005 %   prefixes are added for all identifiers in the respective model field.
-0006 %   The prefixes are:
-0007 %       "R_" for model.rxns,
-0008 %       "M_" for model.mets,
-0009 %       "C_" for model.comps;
-0010 %       "G_" for model.genes (and also represented in model.grRules)
-0011 %
-0012 % Input:
-0013 %   model           model whose identifiers should be modified
-0014 %   fields          cell array with model field names that should be
-0015 %                   checked if prefixes should be added, possible values:
-0016 %                   'rxns', 'mets', 'comps', 'genes', 'id'. (optional, by
-0017 %                   default all listed model fields will be checked).
-0018 %
-0019 % Output:
-0020 %   model           modified model
-0021 %   hasChanged      cell array with fields and prefixes that are added
-0022 %
-0023 % Usage: [model, hasChanged]=addIdentifierPrefix(model,fields)
-0024 
-0025 if nargin<2 || isempty(fields)
-0026     fields = {'rxns','mets','comps','genes','id'};
-0027 end
-0028 
-0029 modelFields = {'rxns','R_';
-0030                'mets','M_';
-0031                'comps','C_';
-0032                'genes','G_';
-0033                'id','M_'};
-0034 
-0035 toChangeIdx = find(ismember(modelFields(:,1),fields));
-0036 hasChanged  = false(numel(modelFields(:,1)),1);
-0037 for i=1:numel(toChangeIdx)
-0038     currName    = modelFields{toChangeIdx(i),1};
-0039     currPrefix  = modelFields{toChangeIdx(i),2};
-0040     if isfield(model,currName)
-0041         currField   = model.(currName);
-0042     else
-0043         continue;
-0044     end
-0045     if ~all(startsWith(currField,regexpPattern('^[a-zA-Z_]')))
-0046         currField = strcat(currPrefix, currField);
-0047         hasChanged(toChangeIdx(i)) = true;
-0048 
-0049         if strcmp(currName,'genes')
-0050                 model.grRules = regexprep(model.grRules, '(\<[0-9_a-zA-Z])', 'G_$1');
-0051                 model.grRules = regexprep(model.grRules, ' G_or ', ' or ');
-0052                 model.grRules = regexprep(model.grRules, ' G_and ', ' and ');
-0053         end
-0054         model.(currName) = currField;
-0055     end
-0056 end
-0057 
-0058 hasChanged = modelFields(hasChanged,:);
-0059 hasChanged = append('model.', hasChanged(:,1), ' (', hasChanged(:,2), ' prefix)');
-0060 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/struct_conversion/editMiriam.html b/doc/struct_conversion/editMiriam.html deleted file mode 100644 index 95cde3fb1..000000000 --- a/doc/struct_conversion/editMiriam.html +++ /dev/null @@ -1,200 +0,0 @@ - - - - Description of editMiriam - - - - - - - - - -
Home > struct_conversion > editMiriam.m
- - - -

editMiriam -

- -

PURPOSE ^

-
editMiriam
- -

SYNOPSIS ^

-
function model=editMiriam(model,type,object,miriamName,miriams,keep)
- -

DESCRIPTION ^

-
 editMiriam
-   Change MIRIAM annotation fields, one annotation type at the same time.
-
-   Input:
-       model       model structure
-       type        'met', 'rxn', 'gene' or 'comp' dependent on which
-                   objects the annotations should be assigned to
-       object      either a cell array of IDs, a logical vector with the
-                   same number of elements as the type (see above) in the
-                   model, a vector of indexes, or 'all'
-       miriamName  string specifying the namespace of the identifier, for
-                   instance 'bigg.metabolite'. Should be a valid prefix
-                   from identifiers.org (e.g.
-                   https://registry.identifiers.org/registry/bigg.metabolite)
-       miriam      string or cell array of strings with annotation
-                   identifiers, e.g. '12dgr161'
-       keep        one of the following strings, specifying what should be
-                   done if an object already has an existing MIRIAM
-                   annotations with the same miriamName:
-                   'replace'   discard all existing annotations, all will
-                               be overwritten, even if the new annotation
-                               is an empty field. Should only be used if
-                               you do not want to keep any of the old
-                               annotation with the same miriamName
-                   'fill'      only add annotations to those objects that
-                               did not yet have an annotation with that
-                               miriamName. Otherwise, the existing
-                               annotation is kept, even if it is different
-                               from the suggested new annotation
-                   'add'       keep all existing annotations, and add any
-                               new annotations, after removing duplicates
-                   
-   Ouput:
-       model       model structure with updated MIRIAM annotation field
-   
- Usage: model=editMiriam(model,type,object,miriamName,miriams,keep)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function model=editMiriam(model,type,object,miriamName,miriams,keep)
-0002 % editMiriam
-0003 %   Change MIRIAM annotation fields, one annotation type at the same time.
-0004 %
-0005 %   Input:
-0006 %       model       model structure
-0007 %       type        'met', 'rxn', 'gene' or 'comp' dependent on which
-0008 %                   objects the annotations should be assigned to
-0009 %       object      either a cell array of IDs, a logical vector with the
-0010 %                   same number of elements as the type (see above) in the
-0011 %                   model, a vector of indexes, or 'all'
-0012 %       miriamName  string specifying the namespace of the identifier, for
-0013 %                   instance 'bigg.metabolite'. Should be a valid prefix
-0014 %                   from identifiers.org (e.g.
-0015 %                   https://registry.identifiers.org/registry/bigg.metabolite)
-0016 %       miriam      string or cell array of strings with annotation
-0017 %                   identifiers, e.g. '12dgr161'
-0018 %       keep        one of the following strings, specifying what should be
-0019 %                   done if an object already has an existing MIRIAM
-0020 %                   annotations with the same miriamName:
-0021 %                   'replace'   discard all existing annotations, all will
-0022 %                               be overwritten, even if the new annotation
-0023 %                               is an empty field. Should only be used if
-0024 %                               you do not want to keep any of the old
-0025 %                               annotation with the same miriamName
-0026 %                   'fill'      only add annotations to those objects that
-0027 %                               did not yet have an annotation with that
-0028 %                               miriamName. Otherwise, the existing
-0029 %                               annotation is kept, even if it is different
-0030 %                               from the suggested new annotation
-0031 %                   'add'       keep all existing annotations, and add any
-0032 %                               new annotations, after removing duplicates
-0033 %
-0034 %   Ouput:
-0035 %       model       model structure with updated MIRIAM annotation field
-0036 %
-0037 % Usage: model=editMiriam(model,type,object,miriamName,miriams,keep)
-0038 miriamName=char(miriamName);
-0039 miriams=convertCharArray(miriams);
-0040 
-0041 %Check 'keep' input
-0042 keep=char(keep);
-0043 if ~any(strcmp(keep,{'replace','fill','add'}))
-0044     error('Invalid ''keep'', should be ''replace'',''fill'',''add''.')
-0045 end
-0046 %Check 'type' input
-0047 type=char(type);
-0048 if ~any(strcmp(type,{'met','gene','rxn','comp'}))
-0049     error('Invalid ''type'', should be ''met'', ''gene'', ''rxn'' or ''comp''.')
-0050 end
-0051 %Check 'object' input
-0052 if islogical(object)
-0053     idxInModel=find(object);
-0054 elseif isnumeric(object)
-0055     idxInModel=object;
-0056 else
-0057     object=convertCharArray(object);
-0058     if numel(object)==1 && strcmp(object{1},'all')
-0059         idxInModel=1:numel(model.([type,'s']));
-0060     else
-0061         idxInModel=getIndexes(model,object,[type,'s']);
-0062         if ~all(idxInModel)
-0063             dispEM('The following objects cannot be found in the model: ',true,object(~idxInModel))
-0064         end
-0065     end
-0066 end
-0067 %Check 'miriams' input
-0068 if numel(miriams)==1 && numel(idxInModel)~=1
-0069     miriams=repmat(miriams,numel(idxInModel),1);
-0070 elseif numel(miriams)~=numel(idxInModel)
-0071     error('The number of annotations does not match the number of objects.')
-0072 end
-0073 
-0074 miriamFieldName=[type,'Miriams'];
-0075 
-0076 if isfield(model,miriamFieldName)
-0077     [extractedMiriams,extractedMiriamNames]=extractMiriam(model.(miriamFieldName)(idxInModel),'all');
-0078 else
-0079     extractedMiriams=cell(numel(idxInModel),1);
-0080     extractedMiriamNames={miriamName};
-0081 end
-0082 
-0083 [~, midx]=ismember(miriamName,extractedMiriamNames);
-0084 if midx==0
-0085     midx=numel(extractedMiriamNames)+1;
-0086     extractedMiriamNames(end+1)={miriamName};
-0087     extractedMiriams(:,end+1)=miriams;
-0088 elseif strcmp(keep,'replace')
-0089     extractedMiriams(:,midx)=miriams;
-0090 else
-0091     noMiriam=cellfun(@isempty,extractedMiriams(:,midx));
-0092     extractedMiriams(noMiriam,midx)=miriams(noMiriam);
-0093     if strcmp(keep,'add') % Skipped when only filling empty entries
-0094         existingMiriams=[split(extractedMiriams(~noMiriam,midx),'; '), miriams(~noMiriam)];
-0095         uniqueMiriams=cell(size(existingMiriams,1),1);
-0096         for i=1:size(existingMiriams,1)
-0097             uniqueMiriams{i,1}=strjoin(unique(existingMiriams(i,:)), {'; '});
-0098         end
-0099         extractedMiriams(~noMiriam,midx)=uniqueMiriams;
-0100     end
-0101 end
-0102 
-0103 % Make Miriam field again
-0104 for i=1:numel(idxInModel)
-0105     miriam.name=cell(1,1);
-0106     miriam.value=cell(1,1);
-0107     for j=1:numel(extractedMiriamNames)
-0108         if ~isempty(extractedMiriams{i,j})
-0109             values=strsplit(extractedMiriams{i,j},'; ');
-0110             miriam.name(end+1:end+numel(values),1)=extractedMiriamNames(j);
-0111             miriam.value(end+1:end+numel(values),1)=values;
-0112         end
-0113     end
-0114     miriam.name(1)=[];
-0115     miriam.value(1)=[];
-0116     model.(miriamFieldName){idxInModel(i),1}=miriam;
-0117 end
-0118 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/struct_conversion/extractMiriam.html b/doc/struct_conversion/extractMiriam.html deleted file mode 100644 index 8bb0ae1ee..000000000 --- a/doc/struct_conversion/extractMiriam.html +++ /dev/null @@ -1,156 +0,0 @@ - - - - Description of extractMiriam - - - - - - - - - -
Home > struct_conversion > extractMiriam.m
- - - -

extractMiriam -

- -

PURPOSE ^

-
extractMiriam
- -

SYNOPSIS ^

-
function [miriams,extractedMiriamNames]=extractMiriam(modelMiriams,miriamNames)
- -

DESCRIPTION ^

-
 extractMiriam
-   This function unpacks the information kept in metMiriams, rxnMiriams,
-   geneMiriams or compMiriams to make the annotation more
-   human-readable. The obtained cell array looks the same like in Excel
-   format, just the columns are split to have particular miriam name in
-   corresponding column
-
-   modelMiriams                a miriam structure (e.g. model.metMiriams)
-                               for one or multiple metabolites
-   miriamNames                 cell array with miriam names to be
-                               extracted (optional, default 'all', meaning
-                               that annotation for all miriam names found
-                               in modelMiriams will be extracted)
-
-   miriams                     a cell array with extracted miriams. if
-                               several miriam names are requested, the
-                               corresponding information is saved in
-                               different columns. if there are several ids
-                               available for the same entity (metabolite,
-                               gene, reaction or compartment), they are
-                               concatenated into one column. the total
-                               number of column represent the number of
-                               unique miriam names per entity
-   extractedMiriamNames        cell array with extracted miriam names
-
- Usage: miriam=extractMiriam(modelMiriams,miriamName)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 function [miriams,extractedMiriamNames]=extractMiriam(modelMiriams,miriamNames)
-0002 % extractMiriam
-0003 %   This function unpacks the information kept in metMiriams, rxnMiriams,
-0004 %   geneMiriams or compMiriams to make the annotation more
-0005 %   human-readable. The obtained cell array looks the same like in Excel
-0006 %   format, just the columns are split to have particular miriam name in
-0007 %   corresponding column
-0008 %
-0009 %   modelMiriams                a miriam structure (e.g. model.metMiriams)
-0010 %                               for one or multiple metabolites
-0011 %   miriamNames                 cell array with miriam names to be
-0012 %                               extracted (optional, default 'all', meaning
-0013 %                               that annotation for all miriam names found
-0014 %                               in modelMiriams will be extracted)
-0015 %
-0016 %   miriams                     a cell array with extracted miriams. if
-0017 %                               several miriam names are requested, the
-0018 %                               corresponding information is saved in
-0019 %                               different columns. if there are several ids
-0020 %                               available for the same entity (metabolite,
-0021 %                               gene, reaction or compartment), they are
-0022 %                               concatenated into one column. the total
-0023 %                               number of column represent the number of
-0024 %                               unique miriam names per entity
-0025 %   extractedMiriamNames        cell array with extracted miriam names
-0026 %
-0027 % Usage: miriam=extractMiriam(modelMiriams,miriamName)
-0028 
-0029 if nargin<2 || (ischar(miriamNames) && strcmp(miriamNames,'all'))
-0030     extractAllTypes=true;
-0031 else
-0032     extractAllTypes=false;
-0033     miriamNames=convertCharArray(miriamNames);
-0034 end
-0035 
-0036 %The annotation for all miriam names should be extracted
-0037 if extractAllTypes
-0038     miriamNames={''};
-0039     for i=1:numel(modelMiriams)
-0040         if ~isempty(modelMiriams{i,1})
-0041             for j=1:numel(modelMiriams{i,1}.name)
-0042                 miriamNames{numel(miriamNames)+1,1}=modelMiriams{i,1}.name{j};
-0043             end
-0044         end
-0045     end
-0046     miriamNames=sort(unique(miriamNames));
-0047 end
-0048 
-0049 %Aggregate the final cell array table with extracted miriam information
-0050 miriams=cell(numel(modelMiriams),0);
-0051 for i=1:numel(miriamNames)
-0052     miriams=[miriams, extractMiriamType(modelMiriams,miriamNames{i})];
-0053 end
-0054 extractedMiriamNames=miriamNames;
-0055 
-0056 end
-0057 
-0058 function miriams=extractMiriamType(modelMiriams,miriamName)
-0059 %Create an empty cell array for ids vector
-0060 tempMiriams = cell([size(modelMiriams,1) 1]);
-0061 %Firstly obtain the list of relevant miriam ids. Several entries may have
-0062 %several miriam ids, such ids are kept in additional columns
-0063 for i=1:numel(modelMiriams)
-0064     if (~isempty(modelMiriams{i,1})) && any(strcmp(modelMiriams{i,1}.name,miriamName))
-0065         for j=1:numel(modelMiriams{i,1}.name)
-0066             if strcmp(modelMiriams{i,1}.name(j),miriamName)
-0067                 tempMiriams(i,j) = modelMiriams{i,1}.value(j);
-0068             end
-0069         end
-0070     else
-0071         modelMiriams{i,1} = '';
-0072     end
-0073 end
-0074 
-0075 %Concatenate multiple ids per miriam name in one column with semicolon as
-0076 %separator
-0077 miriams = cell([size(tempMiriams,1) 1]);
-0078 notEmpty=~cellfun(@isempty,tempMiriams);
-0079 for i=1:size(miriams,1)
-0080     miriams{i}=strjoin(tempMiriams(i,notEmpty(i,:)),{'; '});
-0081 end
-0082 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/struct_conversion/index.html b/doc/struct_conversion/index.html deleted file mode 100644 index aa35ccd6b..000000000 --- a/doc/struct_conversion/index.html +++ /dev/null @@ -1,29 +0,0 @@ - - - - Index for Directory struct_conversion - - - - - - - - - - -
< Master indexIndex for struct_conversion >
- -

Index for struct_conversion

- -

Matlab files in this directory:

- -
 addIdentifierPrefixaddIdentifierPrefix
 editMiriameditMiriam
 extractMiriamextractMiriam
 ravenCobraWrapperravenCobraWrapper
 removeIdentifierPrefixremoveIdentifierPrefix
 standardizeModelFieldOrderstandardizeModelFieldOrder
- - - - -
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/struct_conversion/ravenCobraWrapper.html b/doc/struct_conversion/ravenCobraWrapper.html deleted file mode 100644 index fdbcf58db..000000000 --- a/doc/struct_conversion/ravenCobraWrapper.html +++ /dev/null @@ -1,528 +0,0 @@ - - - - Description of ravenCobraWrapper - - - - - - - - - -
Home > struct_conversion > ravenCobraWrapper.m
- - - -

ravenCobraWrapper -

- -

PURPOSE ^

-
ravenCobraWrapper
- -

SYNOPSIS ^

-
function newModel=ravenCobraWrapper(model)
- -

DESCRIPTION ^

-
 ravenCobraWrapper
-   Converts between RAVEN and COBRA structures
-
-   Input: model          a RAVEN/COBRA-compatible model structure
-
-   Ouput: newModel       a COBRA/RAVEN-compatible model structure
-   
-   This function is a bidirectional tool to convert between RAVEN and
-   COBRA structures. It recognises COBRA structure by checking field
-   'rules' existense, which is only found in COBRA Toolbox structure. If
-   the COBRA model also has a grRules field, then this will be used
-   instead of parsing the rules field.
-
-   NOTE: During RAVEN -> COBRA -> RAVEN conversion cycle the following
-   fields are lost: annotation, compOutside, compMiriams, rxnComps,
-   geneComps, unconstrained. Boundary metabolites are lost, because COBRA
-   structure does not involve boundary metabolites, so they are removed
-   using simplifyModel before RAVEN -> COBRA conversion. The field 'rev'
-   is also partially lost, but during COBRA -> RAVEN conversion it's
-   reconstructed based on lower bound reaction values
-
-   NOTE: During COBRA -> RAVEN -> COBRA conversion cycle the following
-   fields are lost: geneEntrezID, modelVersion, proteins
-
-   NOTE: The information about mandatory RAVEN fields was taken from
-   checkModelStruct function, whereas the corresponding information about
-   COBRA fields was fetched from verifyModel function
-
- Usage: newModel=ravenCobraWrapper(model)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: - -This function is called by: -
    -
- - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 function newModel=ravenCobraWrapper(model)
-0002 % ravenCobraWrapper
-0003 %   Converts between RAVEN and COBRA structures
-0004 %
-0005 %   Input: model          a RAVEN/COBRA-compatible model structure
-0006 %
-0007 %   Ouput: newModel       a COBRA/RAVEN-compatible model structure
-0008 %
-0009 %   This function is a bidirectional tool to convert between RAVEN and
-0010 %   COBRA structures. It recognises COBRA structure by checking field
-0011 %   'rules' existense, which is only found in COBRA Toolbox structure. If
-0012 %   the COBRA model also has a grRules field, then this will be used
-0013 %   instead of parsing the rules field.
-0014 %
-0015 %   NOTE: During RAVEN -> COBRA -> RAVEN conversion cycle the following
-0016 %   fields are lost: annotation, compOutside, compMiriams, rxnComps,
-0017 %   geneComps, unconstrained. Boundary metabolites are lost, because COBRA
-0018 %   structure does not involve boundary metabolites, so they are removed
-0019 %   using simplifyModel before RAVEN -> COBRA conversion. The field 'rev'
-0020 %   is also partially lost, but during COBRA -> RAVEN conversion it's
-0021 %   reconstructed based on lower bound reaction values
-0022 %
-0023 %   NOTE: During COBRA -> RAVEN -> COBRA conversion cycle the following
-0024 %   fields are lost: geneEntrezID, modelVersion, proteins
-0025 %
-0026 %   NOTE: The information about mandatory RAVEN fields was taken from
-0027 %   checkModelStruct function, whereas the corresponding information about
-0028 %   COBRA fields was fetched from verifyModel function
-0029 %
-0030 % Usage: newModel=ravenCobraWrapper(model)
-0031 
-0032 if isfield(model,'rules')
-0033     isRaven=false;
-0034 else
-0035     isRaven=true;
-0036 end
-0037 
-0038 ravenPath=findRAVENroot();
-0039 
-0040 % Load COBRA field information
-0041 fid             = fopen(fullfile(ravenPath,'struct_conversion','COBRA_structure_fields.csv')); % Taken from https://github.com/opencobra/cobratoolbox/blob/develop/src/base/io/definitions/COBRA_structure_fields.csv
-0042 fieldFile       = textscan(fid,repmat('%s',1,15),'Delimiter','\t','HeaderLines',1);
-0043 dbFields        = ~cellfun(@isempty,fieldFile{5}); % Only keep fields with database annotations that should be translated to xxxMiriams
-0044 dbFields        = dbFields & ~contains(fieldFile{1},{'metInChIString','metKEGGID','metPubChemID','rxnECNumbers'});
-0045 COBRAnamespace  = fieldFile{5}(dbFields);
-0046 COBRAnamespace  = regexprep(COBRAnamespace,';.*',''); % Only keep first suggested namespace
-0047 COBRAfields     = fieldFile{1}(dbFields);
-0048 fclose(fid);
-0049 
-0050 % Load conversion between additional COBRA fields and namespaces:
-0051 fid             = fopen(fullfile(ravenPath,'struct_conversion','cobraNamespaces.csv'));
-0052 fieldFile       = textscan(fid,'%s %s','Delimiter',',','HeaderLines',0);
-0053 COBRAfields     = [COBRAfields; fieldFile{1}];
-0054 COBRAnamespace  = [COBRAnamespace; fieldFile{2}];
-0055 rxnCOBRAfields  = COBRAfields(startsWith(COBRAfields,'rxn'));
-0056 rxnNamespaces   = COBRAnamespace(startsWith(COBRAfields,'rxn'));
-0057 metCOBRAfields  = COBRAfields(startsWith(COBRAfields,'met'));
-0058 metNamespaces   = COBRAnamespace(startsWith(COBRAfields,'met'));
-0059 geneCOBRAfields = COBRAfields(startsWith(COBRAfields,'gene'));
-0060 geneNamespaces  = COBRAnamespace(startsWith(COBRAfields,'gene'));
-0061 fclose(fid);
-0062 
-0063 if isRaven
-0064     %Firstly remove boundary metabolites
-0065     model=simplifyModel(model);
-0066 end
-0067 
-0068 % Keep fields that have identical names and content
-0069 newModel.S=model.S;
-0070 newModel.lb=model.lb;
-0071 newModel.ub=model.ub;
-0072 if isfield(model,'c')
-0073     newModel.c=model.c;
-0074 else
-0075     newModel.c=zeros(numel(model.rxns),1);
-0076 end
-0077 newModel.rxns=model.rxns;
-0078 optFields = {'rxnNames','rxnNotes','rxnConfidenceScores','rxnDeltaG',...
-0079     'rxnGeneMat','rev','subSystems','comps','compNames','metCharges',...
-0080     'metDeltaG','metFormulas','metNotes','metSmiles','genes','proteins'};
-0081 for i=1:length(optFields)
-0082     if isfield(model,optFields{i})
-0083         newModel.(optFields{i})=model.(optFields{i});
-0084     end
-0085 end
-0086     
-0087 % Convert unique fields
-0088 if isRaven
-0089     fprintf('Converting RAVEN structure to COBRA..\n');
-0090     %Convert from RAVEN to COBRA structure
-0091     
-0092     %Mandatory COBRA fields
-0093     newModel.rxns=model.rxns;
-0094     if all(~cellfun(@isempty,regexp(model.mets,'\[[^\]]+\]$')))
-0095         newModel.mets=model.mets;
-0096     else
-0097         %Check if model has compartment info as "met_c" suffix in all metabolites:
-0098         BiGGformat = false(size(model.mets));
-0099         for i=1:numel(model.comps)
-0100             compPos=model.metComps==i;
-0101             BiGGformat(compPos)=~cellfun(@isempty,regexp(model.mets(compPos),['_' model.comps{i} '$']));
-0102         end
-0103         if all(BiGGformat)
-0104             newModel.mets=model.mets;
-0105             for i=1:numel(model.comps)
-0106                 newModel.mets=regexprep(newModel.mets,['_' model.comps{i} '$'],['[' model.comps{i} ']']);
-0107             end
-0108         else
-0109             newModel.mets=strcat(model.mets,'[',model.comps(model.metComps),']');
-0110         end
-0111     end
-0112 
-0113     %b, csense, osenseStr, genes, rules are also mandatory, but defined
-0114     %later to match the order of fields
-0115     
-0116     %Optional COBRA fields
-0117     if isfield(model,'id')
-0118         newModel.modelID=model.id;
-0119     end
-0120     if isfield(model,'name')
-0121         newModel.modelName=model.name;
-0122     end
-0123     if isfield(model,'eccodes')
-0124         newModel.rxnECNumbers=model.eccodes;
-0125     end
-0126     if isfield(model,'rxnMiriams')
-0127         [miriams,extractedMiriamNames]=extractMiriam(model.rxnMiriams);
-0128         for i = 1:length(rxnCOBRAfields)
-0129             j=ismember(extractedMiriamNames,rxnNamespaces{i});
-0130             if any(j)
-0131                 eval(['newModel.' rxnCOBRAfields{i} ' = miriams(:,j);'])
-0132             end
-0133         end
-0134     end
-0135     if isfield(model,'rxnReferences') % Concatenate model.rxnReferences to those extracted from model.rxnMiriams
-0136         if isfield(newModel,'rxnReferences')
-0137             newModel.rxnReferences = strcat(newModel.rxnReferences,{'; '},model.rxnReferences);
-0138             newModel.rxnReferences = regexprep(newModel.rxnReferences,'^; $','');
-0139         else
-0140             newModel.rxnReferences = model.rxnReferences;
-0141         end
-0142     end
-0143     if isfield(model,'metNames')
-0144         newModel.metNames=strcat(model.metNames,' [',model.compNames(model.metComps),']');
-0145     end
-0146     if isfield(model,'metMiriams')
-0147         [miriams,extractedMiriamNames]=extractMiriam(model.metMiriams);
-0148         %Shorten miriam names for KEGG and PubChem. These shorter names
-0149         %will be used later to concatenate KEGG COMPOUND/GLYCAN and PubChem
-0150         %Compound/Substance, into corresponding COBRA model fields
-0151         extractedMiriamNames=regexprep(extractedMiriamNames,'^kegg\..+','kegg');
-0152         extractedMiriamNames=regexprep(extractedMiriamNames,'^pubchem\..+','pubchem');
-0153         i=ismember(extractedMiriamNames,'kegg');
-0154         if any(i) % Combine KEGG compounds and glycans
-0155             for j=1:length(i)
-0156                 if i(j) && isfield(newModel,'metKEGGID')~=1
-0157                     newModel.metKEGGID=miriams(:,j);
-0158                 elseif i(j)
-0159                     newModel.metKEGGID=strcat(newModel.metKEGGID,';',miriams(:,j));
-0160                 end
-0161             end
-0162             newModel.metKEGGID=regexprep(newModel.metKEGGID,'^;|;$','');
-0163         end
-0164         i=ismember(extractedMiriamNames,'pubchem');
-0165         if any(i) % Combine Pubchem compounds and substances
-0166             for j=1:length(i)
-0167                 if i(j) && isfield(newModel,'metPubChemID')~=1
-0168                     newModel.metPubChemID=miriams(:,j);
-0169                 elseif i(j)
-0170                     newModel.metPubChemID=strcat(newModel.metPubChemID,';',miriams(:,j));
-0171                 end
-0172             end
-0173             newModel.metPubChemID=regexprep(newModel.metPubChemID,'^;|;$','');
-0174         end
-0175         %All other Miriams can be directly parsed with no modifications:
-0176         for i = 1:length(metCOBRAfields)
-0177             j=ismember(extractedMiriamNames,metNamespaces{i});
-0178             if any(j)
-0179                 eval(['newModel.' metCOBRAfields{i} ' = miriams(:,j);'])
-0180             end
-0181         end
-0182     end
-0183     if isfield(model,'inchis')
-0184         newModel.metInChIString=regexprep(strcat('InChI=', model.inchis),'^InChI=$','');
-0185     end
-0186     newModel.b=zeros(numel(model.mets),1);
-0187     newModel.csense=repmat('E',size(model.mets));
-0188     if isfield(model,'geneMiriams')
-0189         [~,extractedMiriamNames]=extractMiriam(model.geneMiriams);
-0190         for i = 1:length(geneCOBRAfields)
-0191             j=ismember(extractedMiriamNames,geneNamespaces{i});
-0192             if any(j)
-0193                 eval(['newModel.' geneCOBRAfields{i} ' = miriams(:,j);'])
-0194             end
-0195         end
-0196     end
-0197     if isfield(model,'geneShortNames')
-0198         newModel.geneNames=model.geneShortNames;
-0199     end
-0200     if isfield(model,'genes')
-0201         newModel.rules=grrulesToRules(model);
-0202     else
-0203         fprintf('WARNING: no genes detected. The model therefore may not be exportable to SBML file with writeCbModel\n');
-0204     end
-0205     % If needed, normalise subSystems to cell-of-cells format
-0206     if isfield(newModel,'subSystems') && ~isempty(newModel.subSystems)
-0207         if ~iscell(newModel.subSystems{1})
-0208             newModel.subSystems = cellfun(@(x) {x}, newModel.subSystems, 'UniformOutput', false);
-0209         end
-0210     end
-0211 else
-0212     fprintf('Converting COBRA structure to RAVEN..\n');
-0213     %Convert from COBRA to RAVEN structure
-0214 
-0215     %Mandatory RAVEN fields
-0216     newModel.mets=model.mets;
-0217     if ~isfield(model,'comps')
-0218         %Since 'comps' field is not mandatory in COBRA, it may be required
-0219         %to obtain the non-redundant list of comps from metabolite ids, if
-0220         %'comps' field is not available
-0221         newModel.comps = unique(regexprep(model.mets,'.*\[([^\]]+)\]$','$1'));
-0222         newModel.compNames = newModel.comps;
-0223     end
-0224     for i=1:numel(newModel.comps)
-0225         newModel.mets=regexprep(newModel.mets,['\[', newModel.comps{i}, '\]$'],'');
-0226         newModel.mets=regexprep(newModel.mets,['\[', newModel.compNames{i}, '\]$'],'');
-0227     end
-0228     
-0229     %In some cases (e.g. any model that uses BiGG ids as main ids), there
-0230     %may be overlapping mets due to removal of compartment info. To avoid
-0231     %this, we change compartments from e.g. [c] into _c
-0232     if numel(unique(newModel.mets))~=numel(model.mets)
-0233         newModel.mets=model.mets;
-0234         for i=1:numel(newModel.comps)
-0235             newModel.mets=regexprep(newModel.mets,['\[' newModel.comps{i} '\]$'],['_' newModel.comps{i}]);
-0236         end
-0237     end
-0238     %Since COBRA no longer contains rev field it is assumed that rxn is
-0239     %reversible if its lower bound is set below zero
-0240     if ~isfield(model,'rev')
-0241         for i=1:numel(model.rxns)
-0242             if model.lb(i)<0
-0243                 newModel.rev(i,1)=1;
-0244             else
-0245                 newModel.rev(i,1)=0;
-0246             end
-0247         end
-0248     end
-0249     newModel.b=zeros(numel(model.mets),1);
-0250    
-0251     %metComps is also mandatory, but defined later to match the order of
-0252     %fields
-0253     
-0254     %Fields 'name' and 'id' are also considered as mandatory, but
-0255     %these are added to the model during exportModel/exportToExcelFormat
-0256     %anyway, so there is no point to add this information here
-0257     
-0258     %Optional RAVEN fields
-0259     if isfield(model,'modelID')
-0260         newModel.id=model.modelID;
-0261     end
-0262     if isfield(model,'modelName')
-0263         newModel.name=model.modelName;
-0264     end
-0265     if isfield(model,'rules') && ~isfield(model,'grRules')
-0266         model.grRules        = rulesTogrrules(model);
-0267     end
-0268     if isfield(model,'grRules')
-0269         [grRules,rxnGeneMat] = standardizeGrRules(model,true);
-0270         newModel.grRules     = grRules;
-0271         newModel.rxnGeneMat  = rxnGeneMat;
-0272     end
-0273     if isfield(model,'rxnECNumbers')
-0274         newModel.eccodes=regexprep(model.rxnECNumbers,'EC|EC:','');
-0275     end
-0276     if any(isfield(model,rxnCOBRAfields))
-0277         for i=1:numel(model.rxns)
-0278             counter=1;
-0279             newModel.rxnMiriams{i,1}=[];
-0280             if isfield(model,'rxnReferences')
-0281                 if ~isempty(model.rxnReferences{i})
-0282                     pmids = model.rxnReferences{i};
-0283                     pmids = strsplit(pmids,'; ');
-0284                     nonPmids = cellfun(@isempty,regexp(pmids,'^\d+$','match','once'));
-0285                     if any(nonPmids) %Not a pubmed id, keep in rxnReferences instead
-0286                         newModel.rxnReferences{i,1} = strjoin(pmids(nonPmids),', ');
-0287                         pmids(nonPmids)=[];
-0288                     end
-0289                     for j = 1:length(pmids)
-0290                         newModel.rxnMiriams{i,1}.name{counter,1} = 'pubmed';
-0291                         newModel.rxnMiriams{i,1}.value{counter,1} = pmids{j};
-0292                         counter=counter+1;
-0293                     end
-0294                 end
-0295             end
-0296             for j = 2:length(rxnCOBRAfields) %Start from 2, as 1 is rxnReferences
-0297                 if isfield(model,rxnCOBRAfields{j})
-0298                     rxnAnnotation = eval(['model.' rxnCOBRAfields{j} '{i}']);
-0299                     if ~isempty(rxnAnnotation)
-0300                         rxnAnnotation = strtrim(strsplit(rxnAnnotation,';'));
-0301                         for a=1:length(rxnAnnotation)
-0302                             newModel.rxnMiriams{i,1}.name{counter,1} = rxnNamespaces{j};
-0303                             newModel.rxnMiriams{i,1}.value{counter,1} = rxnAnnotation{a};
-0304                             counter=counter+1;
-0305                         end
-0306                     end
-0307                 end
-0308             end
-0309         end
-0310     end
-0311     if isfield(newModel,'rxnReferences')
-0312         emptyEntry = cellfun(@isempty,newModel.rxnReferences);
-0313         newModel.rxnReferences(emptyEntry)={''};
-0314         diffNumel = numel(newModel.rxns) - numel(newModel.rxnReferences);
-0315         if diffNumel > 0
-0316             newModel.rxnReferences(end+1:end+diffNumel) = {''};
-0317         end
-0318     end
-0319     if any(isfield(model,geneCOBRAfields))
-0320         for i=1:numel(model.genes)
-0321             counter=1;
-0322             newModel.geneMiriams{i,1}=[];
-0323             for j = 1:length(geneCOBRAfields)
-0324                 if isfield(model,geneCOBRAfields{j})
-0325                     geneAnnotation = eval(['model.' geneCOBRAfields{j} '{i}']);
-0326                     if ~isempty(geneAnnotation)
-0327                         geneAnnotation = strtrim(strsplit(geneAnnotation,';'));
-0328                         for a=1:length(geneAnnotation)
-0329                             newModel.geneMiriams{i,1}.name{counter,1} = geneNamespaces{j};
-0330                             newModel.geneMiriams{i,1}.value{counter,1} = geneAnnotation{a};
-0331                             counter=counter+1;
-0332                         end
-0333                     end
-0334                 end
-0335             end
-0336         end
-0337     end
-0338     if isfield(model,'geneNames')
-0339         newModel.geneShortNames=model.geneNames;
-0340     end
-0341     newModel.metNames=model.metNames;
-0342     for i=1:numel(newModel.comps)
-0343         newModel.metNames=regexprep(newModel.metNames,['\[', newModel.comps{i}, '\]$'],'');
-0344         newModel.metNames=regexprep(newModel.metNames,['\[', newModel.compNames{i}, '\]$'],'');
-0345     end
-0346     newModel.metNames=deblank(newModel.metNames);
-0347     newModel.metComps=regexprep(model.mets,'^.+\[','');
-0348     newModel.metComps=regexprep(newModel.metComps,'\]$','');
-0349     [~, newModel.metComps]=ismember(newModel.metComps,newModel.comps);
-0350     if isfield(model,'metInChIString')
-0351         newModel.inchis=regexprep(model.metInChIString,'^InChI=','');
-0352     end
-0353     printWarning=false;
-0354     if any(isfield(model,[metCOBRAfields;'metKEGGID';'metPubChemID']))
-0355         for i=1:numel(model.mets)
-0356             counter=1;
-0357             newModel.metMiriams{i,1}=[];
-0358             if isfield(model,'metKEGGID')
-0359                 if ~isempty(model.metKEGGID{i})
-0360                     if strcmp(model.metKEGGID{i}(1),'C')
-0361                         newModel.metMiriams{i,1}.name{counter,1} = 'kegg.compound';
-0362                         newModel.metMiriams{i,1}.value{counter,1} = model.metKEGGID{i};
-0363                         counter=counter+1;
-0364                     elseif strcmp(model.metKEGGID{i}(1),'G')
-0365                         newModel.metMiriams{i,1}.name{counter,1} = 'kegg.glycan';
-0366                         newModel.metMiriams{i,1}.value{counter,1} = model.metKEGGID{i};
-0367                         counter=counter+1;
-0368                     end
-0369                 end
-0370             end
-0371             if isfield(model,'metPubChemID')
-0372                 if ~isempty(model.metPubChemID{i})
-0373                     if length(model.metPubChemID{i})>3 && strcmp(model.metPubChemID{i}(1:4),'CID:')
-0374                         newModel.metMiriams{i,1}.name{counter,1} = 'pubchem.compound';
-0375                         newModel.metMiriams{i,1}.value{counter,1} = model.metPubChemID{i};
-0376                         counter=counter+1;
-0377                     elseif length(model.metPubChemID{i})>3 && strcmp(model.metPubChemID{i}(1:4),'SID:')
-0378                         newModel.metMiriams{i,1}.name{counter,1} = 'pubchem.substance';
-0379                         newModel.metMiriams{i,1}.value{counter,1} = model.metPubChemID{i};
-0380                         counter=counter+1;
-0381                     else
-0382                         newModel.metMiriams{i,1}.name{counter,1} = 'pubchem.compound';
-0383                         newModel.metMiriams{i,1}.value{counter,1} = model.metPubChemID{i};
-0384                         counter=counter+1;
-0385                         printWarning=true;
-0386                     end
-0387                 end
-0388             end            
-0389             for j = 1:length(metCOBRAfields)
-0390                 if isfield(model,metCOBRAfields{j})
-0391                     metAnnotation = eval(['model.' metCOBRAfields{j} '{i}']);
-0392                     if ~isempty(metAnnotation)
-0393                         metAnnotation = strtrim(strsplit(metAnnotation,';'));
-0394                         for a=1:length(metAnnotation)
-0395                             newModel.metMiriams{i,1}.name{counter,1} = metNamespaces{j};
-0396                             newModel.metMiriams{i,1}.value{counter,1} = metAnnotation{a};
-0397                             counter=counter+1;
-0398                         end
-0399                     end
-0400                 end
-0401             end
-0402         end
-0403     end
-0404     % Flatten subSystems if every reaction has exactly one subsystem.
-0405     if isfield(newModel,'subSystems') && ~isempty(newModel.subSystems)
-0406         if all(cellfun(@(x) iscell(x) && isscalar(x), newModel.subSystems))
-0407             newModel.subSystems = transpose([newModel.subSystems{:}]);
-0408         end
-0409     end
-0410     if printWarning
-0411         fprintf('Could not determine whether PubChemIDs are compounds (CID)\n or substances (SID). All annotated PubChemIDs will therefore \n be assigned as compounds (CID).\n');
-0412     end
-0413 end
-0414 
-0415 % Order fields
-0416 newModel=standardizeModelFieldOrder(newModel); % Corrects for both RAVEN and COBRA models
-0417 end
-0418 
-0419 function rules=grrulesToRules(model)
-0420 %This function just takes grRules, changes all gene names to
-0421 %'x(geneNumber)' and also changes 'or' and 'and' relations to corresponding
-0422 %symbols
-0423 replacingGenes=cell([size(model.genes,1) 1]);
-0424 for i=1:numel(replacingGenes)
-0425     replacingGenes{i}=strcat('x(',num2str(i),')');
-0426 end
-0427 rules = strcat({' '},model.grRules,{' '});
-0428 for i=1:length(model.genes)
-0429     rules=regexprep(rules,[' ' model.genes{i} ' '],[' ' replacingGenes{i} ' ']);
-0430     rules=regexprep(rules,['(' model.genes{i} ' '],['(' replacingGenes{i} ' ']);
-0431     rules=regexprep(rules,[' ' model.genes{i} ')'],[' ' replacingGenes{i} ')']);
-0432 end
-0433 rules=regexprep(rules,' and ',' & ');
-0434 rules=regexprep(rules,' or ',' | ');
-0435 rules=strtrim(rules);
-0436 end
-0437 
-0438 function grRules=rulesTogrrules(model)
-0439 %This function takes rules, replaces &/| for and/or, replaces the x(i)
-0440 %format with the actual gene ID, and takes out extra whitespace and
-0441 %redundant parenthesis introduced by COBRA, to create grRules.
-0442 grRules = strrep(model.rules,'&','and');
-0443 grRules = strrep(grRules,'|','or');
-0444 for i = 1:length(model.genes)
-0445     grRules = strrep(grRules,['x(' num2str(i) ')'],model.genes{i});
-0446 end
-0447 grRules = strrep(grRules,'( ','(');
-0448 grRules = strrep(grRules,' )',')');
-0449 grRules = regexprep(grRules,'^(',''); %rules that start with a "("
-0450 grRules = regexprep(grRules,')$',''); %rules that end with a ")"
-0451 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/struct_conversion/removeIdentifierPrefix.html b/doc/struct_conversion/removeIdentifierPrefix.html deleted file mode 100644 index 3fae6a6c2..000000000 --- a/doc/struct_conversion/removeIdentifierPrefix.html +++ /dev/null @@ -1,143 +0,0 @@ - - - - Description of removeIdentifierPrefix - - - - - - - - - -
Home > struct_conversion > removeIdentifierPrefix.m
- - - -

removeIdentifierPrefix -

- -

PURPOSE ^

-
removeIdentifierPrefix
- -

SYNOPSIS ^

-
function [model, hasChanged]=removeIdentifierPrefix(model,fields,forceRemove)
- -

DESCRIPTION ^

-
 removeIdentifierPrefix
-   This function removes identifier prefixes:
-       "R_" for model.rxns, model.rxnNames and model.id,
-       "M_" for model.mets and model.metNames,
-       "C_" for model.comps;
-       "G_" for model.genes (and also represented in model.grRules).
-   By default, the prefixes are only removed if all entries in a
-   particular field has the prefix. The prefixes might have been present
-   because one or more identifiers do not start with a letter or _, which
-   conflicts with SBML specifications.
-
- Input:
-   model           model whose identifiers should be modified
-   fields          cell array with model field names from which the
-                   identifiers should be removed, possible values: 
-                   'rxns', 'mets', 'comps', 'genes', 'metNames', 
-                   'rxnNames', 'id'. (optional, by default all listed
-                   model fields will be checked).
-   forceRemove     if prefixes should be removed even if not all entries
-                   in a model field have the prefix (optional, default
-                   false)
-
- Output:
-   model           modified model
-   hasChanged      cell array with fields and prefixes that are removed
-
- Usage: model=removeIdentifierPrefix(model,fields,forceRemove)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function [model, hasChanged]=removeIdentifierPrefix(model,fields,forceRemove)
-0002 % removeIdentifierPrefix
-0003 %   This function removes identifier prefixes:
-0004 %       "R_" for model.rxns, model.rxnNames and model.id,
-0005 %       "M_" for model.mets and model.metNames,
-0006 %       "C_" for model.comps;
-0007 %       "G_" for model.genes (and also represented in model.grRules).
-0008 %   By default, the prefixes are only removed if all entries in a
-0009 %   particular field has the prefix. The prefixes might have been present
-0010 %   because one or more identifiers do not start with a letter or _, which
-0011 %   conflicts with SBML specifications.
-0012 %
-0013 % Input:
-0014 %   model           model whose identifiers should be modified
-0015 %   fields          cell array with model field names from which the
-0016 %                   identifiers should be removed, possible values:
-0017 %                   'rxns', 'mets', 'comps', 'genes', 'metNames',
-0018 %                   'rxnNames', 'id'. (optional, by default all listed
-0019 %                   model fields will be checked).
-0020 %   forceRemove     if prefixes should be removed even if not all entries
-0021 %                   in a model field have the prefix (optional, default
-0022 %                   false)
-0023 %
-0024 % Output:
-0025 %   model           modified model
-0026 %   hasChanged      cell array with fields and prefixes that are removed
-0027 %
-0028 % Usage: model=removeIdentifierPrefix(model,fields,forceRemove)
-0029 
-0030 if nargin<2 || isempty(fields)
-0031     fields = {'rxns','mets','comps','genes','metNames','rxnNames','id'};
-0032 end
-0033 if nargin<3 || isempty(forceRemove)
-0034     forceRemove = false;
-0035 end
-0036 
-0037 modelFields = {'rxns',      'R_';
-0038     'mets',      'M_';
-0039     'comps',     'C_';
-0040     'genes',     'G_';
-0041     'metNames',  'M_';
-0042     'rxnNames',  'R_';
-0043     'id',        'M_'};
-0044 
-0045 toChangeIdx = find(ismember(modelFields(:,1),fields));
-0046 hasChanged  = false(numel(modelFields(:,1)),1);
-0047 for i=1:numel(toChangeIdx)
-0048     currName    = modelFields{toChangeIdx(i),1};
-0049     currPrefix  = modelFields{toChangeIdx(i),2};
-0050     currField   = model.(currName);
-0051 
-0052     if forceRemove && any(startsWith(currField,currPrefix))
-0053         hasPrefix = true;
-0054     else
-0055         hasPrefix = all(startsWith(currField,currPrefix));
-0056     end
-0057     if hasPrefix
-0058         currField = regexprep(currField,['^' currPrefix],'');
-0059         hasChanged(toChangeIdx(i)) = true;
-0060         if strcmp(currName,'genes')
-0061             model.grRules=regexprep(model.grRules,'^G_','');
-0062             model.grRules=regexprep(model.grRules,'\(G_','(');
-0063             model.grRules=regexprep(model.grRules,' G_',' ');
-0064         end
-0065     end
-0066     model.(currName) = currField;
-0067 end
-0068 hasChanged = modelFields(hasChanged,:);
-0069 hasChanged = append('model.', hasChanged(:,1), ' (', hasChanged(:,2), ' prefix)');
-0070 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/struct_conversion/standardizeModelFieldOrder.html b/doc/struct_conversion/standardizeModelFieldOrder.html deleted file mode 100644 index 8810543a0..000000000 --- a/doc/struct_conversion/standardizeModelFieldOrder.html +++ /dev/null @@ -1,123 +0,0 @@ - - - - Description of standardizeModelFieldOrder - - - - - - - - - -
Home > struct_conversion > standardizeModelFieldOrder.m
- - - -

standardizeModelFieldOrder -

- -

PURPOSE ^

-
standardizeModelFieldOrder
- -

SYNOPSIS ^

-
function orderedModel=standardizeModelFieldOrder(model)
- -

DESCRIPTION ^

-
 standardizeModelFieldOrder
-   Orders fields of RAVEN model structure as specified at
-   https://github.com/SysBioChalmers/RAVEN/wiki/RAVEN-Model-Structure
-
-   Input: model           model structure, either RAVEN or COBRA format
-
-   Output: orderedModel   model structure with ordered fields
-
-   The model fields themselves are not changed, only the order is
-   modified. For changing model fields between RAVEN and COBRA format, use
-   ravenCobraWrapper().
-
- Usage: orderedModel=standardizeModelFieldOrder(model)
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: - - - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 function orderedModel=standardizeModelFieldOrder(model)
-0002 % standardizeModelFieldOrder
-0003 %   Orders fields of RAVEN model structure as specified at
-0004 %   https://github.com/SysBioChalmers/RAVEN/wiki/RAVEN-Model-Structure
-0005 %
-0006 %   Input: model           model structure, either RAVEN or COBRA format
-0007 %
-0008 %   Output: orderedModel   model structure with ordered fields
-0009 %
-0010 %   The model fields themselves are not changed, only the order is
-0011 %   modified. For changing model fields between RAVEN and COBRA format, use
-0012 %   ravenCobraWrapper().
-0013 %
-0014 % Usage: orderedModel=standardizeModelFieldOrder(model)
-0015 
-0016 ravenPath=findRAVENroot();
-0017 
-0018 if ~isfield(model,'rules') % Check if model is RAVEN
-0019     fid = fopen(fullfile(ravenPath,'struct_conversion','orderRavenFields.csv'));
-0020     fields = textscan(fid,'%s','Delimiter',',','HeaderLines',0);
-0021     fields = fields{1};
-0022     fclose(fid);
-0023 else % If model is COBRA
-0024     fid = fopen(fullfile(ravenPath,'struct_conversion','COBRA_structure_fields.csv')); % Taken from https://github.com/opencobra/cobratoolbox/blob/develop/src/base/io/definitions/COBRA_structure_fields.csv
-0025     fields = textscan(fid,repmat('%s',1,15),'Delimiter','\t','HeaderLines',1);
-0026     fields = fields{1};
-0027     fclose(fid);
-0028 end
-0029 
-0030 modelfields = fieldnames(model);
-0031 order = fields(ismember(fields(:,1),modelfields));
-0032 remainingOrder = sort(setdiff(modelfields,order));
-0033 overallOrder = [columnVector(order);columnVector(remainingOrder)];
-0034 orderedModel = orderfields(model,overallOrder);
-0035 end
-0036 
-0037 function vecT = columnVector(vec)
-0038 % Converts a vector to a column vector
-0039 %
-0040 % USAGE:
-0041 %
-0042 %   vecT = columnVector(vec)
-0043 %
-0044 % INPUT:
-0045 %   vec:     a vector
-0046 %
-0047 % OUTPUT:
-0048 %   vecT:    a column vector
-0049 %
-0050 % .. Authors:
-0051 %     - Original file: Markus Herrgard
-0052 %     - Minor changes: Laurent Heirendt January 2017
-0053 %     - Copied from COBRA Toolbox May 2022
-0054 
-0055 [n, m] = size(vec);
-0056 
-0057 if (m ~= 1 && n < m) || n == 1
-0058     vecT = vec';
-0059 else
-0060     vecT = vec;
-0061 end
-0062 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/testing/manual_tests/ManualINITTests.html b/doc/testing/manual_tests/ManualINITTests.html deleted file mode 100644 index 7b0776026..000000000 --- a/doc/testing/manual_tests/ManualINITTests.html +++ /dev/null @@ -1,170 +0,0 @@ - - - - Description of ManualINITTests - - - - - - - - - -
Home > testing > manual_tests > ManualINITTests.m
- - - -

ManualINITTests -

- -

PURPOSE ^

-
These tests are using the Human-GEM model.
- -

SYNOPSIS ^

-
This is a script file.
- -

DESCRIPTION ^

-
These tests are using the Human-GEM model.
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 %These tests are using the Human-GEM model.
-0002 
-0003 %%%%%%%%%%%%%%%%%%%%%%%%%%
-0004 % TC0901 - Test that all reactions in the minimal model to be
-0005 %          used by the MILP can carry flux > 0.1
-0006 %%%%%%%%%%%%%%%%%%%%%%%%%%
-0007 
-0008 %In the MILP, the flux of reactions with negative rxn scores cannot exceed 100
-0009 %At the same time, the flux of positive reactions need to be >= 0.1 to be able
-0010 %to turn them on. Likewise, we force the flux on essential reactions to be >= 0.1.
-0011 %Therefore, it is important that all reactions can get a flux > 0.1, while all
-0012 %reactions are limited to a flux <= 100. We can test this in a similar way to the
-0013 %haveFlux function in RAVEN, so that code is copied here and modified.
-0014 
-0015 %This code is partly copied from the function haveFlux
-0016 %The prepData takes a couple of hours to generate. If you have it somewhere,
-0017 %better to load it
-0018 %cd C:\Work\MatlabCode\components\human-GEM\Human-GEMftINIT\Human-GEM %replace this with the root of the Human-GEM repo.
-0019 %ihuman = importYaml('model/Human-GEM.yml');
-0020 %save('model/Human-GEM.mat', 'ihuman');
-0021 %load('model/Human-GEM.mat')
-0022 %prepData = prepHumanModelForftINIT(ihuman, false);
-0023 prepData2 = load('model/PrepData2.mat').prepData;
-0024 
-0025 upperLimit = 100;
-0026 lowerLimit = 0.1;
-0027 
-0028 model = prepData2.minModel;
-0029 model = prepData.minModel;
-0030 
-0031 
-0032 
-0033 
-0034 model.lb(model.lb==-inf)=-upperLimit;
-0035 model.ub(model.ub==inf)=upperLimit;
-0036 model.lb(model.lb==-1000)=-upperLimit;
-0037 model.ub(model.ub==1000)=upperLimit;
-0038 
-0039 %check
-0040 unique(model.lb) %ok, only 0 and -100
-0041 unique(model.ub) %ok, only 100
-0042 
-0043 %First make a loop where we optimize for all
-0044 onFwd = false(numel(model.rxns,1));
-0045 onRev = false(numel(model.rxns,1));
-0046 
-0047 iter = 1;
-0048 while true
-0049     disp([num2str(iter) ': ' num2str(sum(onFwd))])
-0050     model.c=ones(numel(model.c),1);
-0051     model.c(onFwd) = 0; %don't include the ones already verified
-0052     
-0053     sol=solveLP(model);
-0054     if isempty(sol.x)
-0055         disp('Failed');
-0056         break;
-0057     end
-0058     
-0059     currRes = sol.x > lowerLimit;
-0060     if sum(currRes & ~onFwd) == 0
-0061         break;%we didn't turn any more rxns on
-0062     end
-0063     
-0064     onFwd = onFwd | currRes;
-0065     iter = iter + 1;
-0066 end
-0067 
-0068 sum(~onFwd)%zero, perfect
-0069 
-0070 %Now the other direction (reversible):
-0071 onRev = false(numel(model.rxns,1));
-0072 
-0073 iter = 1;
-0074 while true
-0075     disp([num2str(iter) ': ' num2str(sum(onRev))])
-0076     model.c=-ones(numel(model.c),1);
-0077     model.c(~model.rev) = 0;
-0078     model.c(onRev) = 0; %don't include the ones already verified
-0079     
-0080     sol=solveLP(model);
-0081     if isempty(sol.x)
-0082         disp('Failed');
-0083         break;
-0084     end
-0085     
-0086     currRes = sol.x < -lowerLimit;
-0087     if sum(currRes & ~onRev) == 0
-0088         break;%we didn't turn any more rxns on
-0089     end
-0090     
-0091     onRev = onRev | currRes;
-0092     iter = iter + 1;
-0093 end
-0094 
-0095 sum(~onRev(model.rev == 1))%
-0096 
-0097 onRev = false(numel(model.rxns,1));
-0098 
-0099 indLeft = find(model.rev == 1 & ~onRev);
-0100 
-0101 constructEquations(model, model.rxns(indLeft))%no scaling here...
-0102 
-0103 %go trough the last one by one
-0104 for i = 1:numel(indLeft)
-0105     model.c=zeros(numel(model.c),1);
-0106     model.c(indLeft(i)) = -1;
-0107     
-0108     sol=solveLP(model);
-0109     if isempty(sol.x)
-0110         disp('Failed');
-0111         break;
-0112     end
-0113     
-0114     currRes = sol.x(indLeft(i)) < -lowerLimit;
-0115     disp([num2str(indLeft(i)) ': ' num2str(currRes)])
-0116     onRev(indLeft(i)) = currRes;
-0117     onRev = onRev | currRes;
-0118     iter = iter + 1;
-0119 end
-0120 
-0121 sum(~onRev(model.rev == 1))%0, perfect. This means that we can use the limits 0.1 and 100 in the MILP!
-0122 
-0123
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/testing/manual_tests/index.html b/doc/testing/manual_tests/index.html deleted file mode 100644 index 8e8945518..000000000 --- a/doc/testing/manual_tests/index.html +++ /dev/null @@ -1,29 +0,0 @@ - - - - Index for Directory testing\manual_tests - - - - - - - - - - -
< Master indexIndex for testing\manual_tests >
- -

Index for testing\manual_tests

- -

Matlab files in this directory:

- -
 ManualINITTestsThese tests are using the Human-GEM model.
- - - - -
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/testing/unit_tests/blastPlusTests.html b/doc/testing/unit_tests/blastPlusTests.html deleted file mode 100644 index 2b0ba05b1..000000000 --- a/doc/testing/unit_tests/blastPlusTests.html +++ /dev/null @@ -1,108 +0,0 @@ - - - - Description of blastPlusTests - - - - - - - - - -
Home > testing > unit_tests > blastPlusTests.m
- - - -

blastPlusTests -

- -

PURPOSE ^

-
run this test case with the command
- -

SYNOPSIS ^

-
function tests = blastPlusTests
- -

DESCRIPTION ^

-
run this test case with the command
-results = runtests('blastPlusTests.m')
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 %run this test case with the command
-0002 %results = runtests('blastPlusTests.m')
-0003 function tests = blastPlusTests
-0004 tests = functiontests(localfunctions);
-0005 end
-0006 
-0007 function testBlastPlus(testCase)
-0008 %This unit test comprises several functionality tests for BLAST+ in RAVEN:
-0009 % 1. MD5 checksum check for BLAST database files. This check is applied for
-0010 %    "phr", "pot", "psq" and "pto" files. The remaining files (i.e. "pdb",
-0011 %    "pin" and "ptf") are not compared as these seem to be
-0012 %    machine-specific.
-0013 % 2. Non-parsed text check for BLAST result files. Although the content of
-0014 %    the files is exactly the same, their MD5 hashes are somehow different
-0015 %    between the operating systems.
-0016 % 3. Check of resulting blastStructure against the expected one. This is
-0017 %    done to test BLAST results parsing in RAVEN.
-0018 
-0019 %%
-0020 %Get the directory for RAVEN Toolbox
-0021 [ST, I]=dbstack('-completenames');
-0022 ravenPath=fileparts(fileparts(fileparts(ST(I).file)));
-0023 
-0024 %Import structures that contain expected MD5 hashes and BLAST results
-0025 sourceDir = fileparts(which(mfilename));
-0026 load([sourceDir,'/test_data/expBlastResults.mat'],'expBlastStructure','expBlastReport');
-0027 
-0028 organismID='sce';
-0029 fastaFile=fullfile(ravenPath,'testing','unit_tests','test_data','yeast_galactosidases.fa');
-0030 modelIDs={'hsa' 'afv'};
-0031 refFastaFiles={fullfile(ravenPath,'testing','unit_tests','test_data','human_galactosidases.fa') fullfile(ravenPath,'testing','unit_tests','test_data','aflavus_galactosidases.fa')};
-0032 
-0033 %%
-0034 %Run BLAST
-0035 [actBlastStructure,actBlastReport]=getBlast(organismID,fastaFile,modelIDs,refFastaFiles,true,true);
-0036 
-0037 %%
-0038 %Test 1a: Check if MD5 checksums for BLAST database files are the same
-0039 verifyEqual(testCase,actBlastReport.dbHashes,expBlastReport.dbHashes);
-0040 
-0041 %Test 1b: Change one of the MD5 checksums and check if test fails
-0042 actBlastReport.dbHashes.phr{1,1}=actBlastReport.dbHashes.phr{1,2};
-0043 verifyNotEqual(testCase,actBlastReport.dbHashes,expBlastReport.dbHashes);
-0044 
-0045 %Test 2a: Check if BLAST result files are the same
-0046 verifyEqual(testCase,actBlastReport.blastTxtOutput,expBlastReport.blastTxtOutput);
-0047 
-0048 %Test 2b: Change actual BLAST result file and check if test fails
-0049 actBlastReport.blastTxtOutput='empty';
-0050 verifyNotEqual(testCase,actBlastReport.blastTxtOutput,expBlastReport.blastTxtOutput);
-0051 
-0052 %Test 3a: Check if BLAST structures are the same
-0053 verifyEqual(testCase,actBlastStructure,expBlastStructure);
-0054 
-0055 %Test 3b: Modify actual BLAST structure and check if test fails
-0056 actBlastStructure(1,1).toId=actBlastStructure(1,1).fromId;
-0057 verifyNotEqual(testCase,actBlastStructure,expBlastStructure);
-0058 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/testing/unit_tests/cdhitTests.html b/doc/testing/unit_tests/cdhitTests.html deleted file mode 100644 index 31c2880e9..000000000 --- a/doc/testing/unit_tests/cdhitTests.html +++ /dev/null @@ -1,129 +0,0 @@ - - - - Description of cdhitTests - - - - - - - - - -
Home > testing > unit_tests > cdhitTests.m
- - - -

cdhitTests -

- -

PURPOSE ^

-
run this test case with the command
- -

SYNOPSIS ^

-
function tests = cdhitTests
- -

DESCRIPTION ^

-
run this test case with the command
-results = runtests('cdhitTests.m')
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 %run this test case with the command
-0002 %results = runtests('cdhitTests.m')
-0003 function tests = cdhitTests
-0004 tests = functiontests(localfunctions);
-0005 end
-0006 
-0007 function testCdhit(testCase)
-0008 %This unit test comprises the functionality test for CD-HIT in RAVEN:
-0009 % 1. Check for resulting file against the expected one.
-0010 
-0011 %%
-0012 %Get the directory for RAVEN Toolbox
-0013 [ST, I]=dbstack('-completenames');
-0014 ravenPath=fileparts(fileparts(fileparts(ST(I).file)));
-0015 
-0016 %Identify the operating system
-0017 if isunix
-0018     if ismac
-0019         binEnd='.mac';
-0020     else
-0021         binEnd='';
-0022     end
-0023 elseif ispc
-0024     binEnd='.exe';
-0025 else
-0026     dispEM('Unknown OS, exiting.')
-0027     return
-0028 end
-0029 
-0030 %Import structure that contains expected MAFFT results
-0031 sourceDir = fileparts(which(mfilename));
-0032 load([sourceDir,'/test_data/expCdhitMafftOutput.mat'],'expCdhitMafftOutput');
-0033 
-0034 %Generate temporary names for working directory and outFile
-0035 tmpDIR=tempname;
-0036 outFile=tempname;
-0037 
-0038 %Run CD-HIT multi-threaded to use all logical cores assigned to MATLAB
-0039 cores = evalc('feature(''numcores'')');
-0040 cores = strsplit(cores, 'MATLAB was assigned: ');
-0041 cores = regexp(cores{2},'^\d*','match');
-0042 cores = cores{1};
-0043 
-0044 %Create a temporary folder and copy multi-FASTA file there
-0045 [~, ~]=system(['mkdir "' tmpDIR '"']);
-0046 
-0047 sourceDir = fileparts(which(mfilename));
-0048 copyfile(fullfile(sourceDir,'test_data','yeast_galactosidases.fa'),tmpDIR);
-0049 
-0050 %%
-0051 %Run protein clustering with CD-HIT
-0052 if ispc
-0053     % Define WSL paths
-0054     wslPath.fastaFile=getWSLpath([tmpDIR filesep 'yeast_galactosidases.fa']);
-0055     wslPath.outFile=getWSLpath(outFile);
-0056     wslPath.cdhit=getWSLpath(fullfile(ravenPath,'software','cd-hit','cd-hit'));
-0057     [~, ~]=system(['wsl "' wslPath.cdhit '" -T "' num2str(cores) '" -i "' wslPath.fastaFile '" -o "' wslPath.outFile '" -c 1.0 -n 5 -M 2000']);
-0058 else
-0059     [~, ~]=system(['"' fullfile(ravenPath,'software','cd-hit',['cd-hit' binEnd]) '" -T "' num2str(cores) '" -i "' fullfile(tmpDIR, 'yeast_galactosidases.fa') '" -o "' outFile '" -c 1.0 -n 5 -M 2000']);
-0060 end
-0061 
-0062 %%
-0063 %Open actual cdhit results file
-0064 actCdhitOutput=importdata(fullfile(outFile));
-0065 
-0066 %Remove the old tempfiles
-0067 delete([outFile '*']);
-0068 
-0069 %Remove temporary folder, since testing is finished
-0070 [~, ~]=system(['rm "' tmpDIR '" -r']);
-0071 
-0072 %%
-0073 %Check 1a: Check if files for CD-HIT results are the same
-0074 verifyEqual(testCase,actCdhitOutput,expCdhitMafftOutput);
-0075 
-0076 %Check 1b: Change actual CD-HIT results file and check if test fails
-0077 actCdhitOutput='abc';
-0078 verifyNotEqual(testCase,actCdhitOutput,expCdhitMafftOutput);
-0079 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/testing/unit_tests/checkTasksTests.html b/doc/testing/unit_tests/checkTasksTests.html deleted file mode 100644 index 2887066ce..000000000 --- a/doc/testing/unit_tests/checkTasksTests.html +++ /dev/null @@ -1,138 +0,0 @@ - - - - Description of checkTasksTests - - - - - - - - - -
Home > testing > unit_tests > checkTasksTests.m
- - - -

checkTasksTests -

- -

PURPOSE ^

-
run this test case with the command
- -

SYNOPSIS ^

-
function tests = checkTasksTests
- -

DESCRIPTION ^

-
run this test case with the command
-results = runtests('checkTasksTests.m')
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 %run this test case with the command
-0002 %results = runtests('checkTasksTests.m')
-0003 function tests = checkTasksTests
-0004     tests = functiontests(localfunctions);
-0005 end
-0006 
-0007 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-0008 % testModel
-0009 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-0010 
-0011 function testModel = getTaskTstModel()
-0012     testModel = struct();
-0013     testModel.id = 'testModel';
-0014     testModel.rxns = {};
-0015     testModel.S=[];
-0016     testModel.rev=[];
-0017     testModel.mets = {'as';'ac';'bc';'cc';'dc';'ec';'es';'fc'};
-0018     testModel.metNames = {'a';'a';'b';'c';'d';'e';'e';'f'};
-0019     testModel.comps = {'s';'c'};
-0020     testModel.compNames = testModel.comps;
-0021     testModel.metComps = [1;2;2;2;2;2;1;2];
-0022     testModel.genes = {'G1';'G2';'G3';'G4';'G5';'G6';'G7';'G8';'G9';'G10'};
-0023     testModel.grRules = {};
-0024     testModel.rxnGeneMat = [];
-0025 
-0026     rxnsToAdd = struct();
-0027     rxnsToAdd.rxns = {'R1';'R2';'R3';'R4';'R5';'R6';'R7';'R8';'R9';'R10'};
-0028     rxnsToAdd.equations = {'=> a[s]';...
-0029                            'a[s] <=> a[c]';...
-0030                            'a[c] <=> b[c] + c[c]';...
-0031                            'a[c] <=> 2 d[c]';...
-0032                            'b[c] + c[c] => e[c]';...
-0033                            '2 d[c] => e[c]';...
-0034                            'e[c] => e[s]';...
-0035                            'e[s] =>';...
-0036                            'a[c] <=> f[c]';...
-0037                            'f[c] <=> e[c]'};
-0038     rxnsToAdd.grRules = {'';'';'G3';'G4';'G5';'G6';'G7';'';'G9';'G10'};
-0039     testModel = addRxns(testModel,rxnsToAdd, 3);
-0040     testModel.c = [0;0;0;0;0;0;0;1;0;0];%optimize for output flux, if this is used, not sure
-0041     testModel.ub = repmat(1000,10,1);
-0042     testModel.lb = [0;-1000;-1000;-1000;0;0;0;0;-1000;-1000];
-0043     testModel.rxnNames = testModel.rxns;
-0044     testModel.b = repmat(0,8,1);
-0045 end
-0046 
-0047 function testModelTasks = getTaskTstModelTasks()
-0048     testModelTasks = struct();
-0049     testModelTasks.id = 'Gen e[s] from a[s]';
-0050     testModelTasks.description = 'Gen e[s] from a[s]';
-0051     testModelTasks.shouldFail = false;
-0052     testModelTasks.printFluxes = false;
-0053     testModelTasks.comments = '';
-0054     testModelTasks.inputs = {'a[s]'};
-0055     testModelTasks.LBin = 0;
-0056     testModelTasks.UBin = inf;
-0057     testModelTasks.outputs = {'e[s]'};
-0058     testModelTasks.LBout = 1;
-0059     testModelTasks.UBout = 1;
-0060     testModelTasks.equations = {};
-0061     testModelTasks.LBequ = [];
-0062     testModelTasks.UBequ = [];
-0063     testModelTasks.changed = {};
-0064     testModelTasks.LBrxn = {};
-0065     testModelTasks.UBrxn = {};
-0066 end
-0067 
-0068 
-0069 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-0070 %TXXXX: checkTasks
-0071 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-0072 function testcheckTasks(testCase)
-0073 
-0074     testModel = getTaskTstModel();
-0075     testModel = closeModel(testModel);
-0076     testModelTasks = getTaskTstModelTasks();
-0077     
-0078     %the task should work with the full model
-0079     [~,taskReport] = evalc("checkTasks(testModel,[],true,false,false,testModelTasks);");
-0080     verifyTrue(testCase, taskReport.ok == 1)
-0081     
-0082     %now remove R2, then it should fail
-0083     testModel2 = removeReactions(testModel, {'R2'});
-0084     [~, taskReport2] = evalc("checkTasks(testModel2,[],true,false,false,testModelTasks);");
-0085     verifyTrue(testCase, taskReport2.ok == 0)
-0086 end
-0087 
-0088
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/testing/unit_tests/diamondTests.html b/doc/testing/unit_tests/diamondTests.html deleted file mode 100644 index 5af96de46..000000000 --- a/doc/testing/unit_tests/diamondTests.html +++ /dev/null @@ -1,107 +0,0 @@ - - - - Description of diamondTests - - - - - - - - - -
Home > testing > unit_tests > diamondTests.m
- - - -

diamondTests -

- -

PURPOSE ^

-
run this test case with the command
- -

SYNOPSIS ^

-
function tests = diamondTests
- -

DESCRIPTION ^

-
run this test case with the command
-results = runtests('diamondTests.m')
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 %run this test case with the command
-0002 %results = runtests('diamondTests.m')
-0003 function tests = diamondTests
-0004 tests = functiontests(localfunctions);
-0005 end
-0006 
-0007 function testDiamond(testCase)
-0008 %This unit test comprises several functionality tests for DIAMOND blastp in
-0009 %RAVEN:
-0010 % 1. MD5 checksum check for DIAMOND database files.
-0011 % 2. Non-parsed text check for DIAMOND result files. Although the content
-0012 %    of the files is exactly the same, their MD5 hashes are somehow
-0013 %    different between the operating systems.
-0014 % 3. Check of resulting blastStructure against the expected one. This is
-0015 %    done to test DIAMOND blastp results parsing in RAVEN.
-0016 
-0017 %%
-0018 %Get the directory for RAVEN Toolbox
-0019 [ST, I]=dbstack('-completenames');
-0020 ravenPath=fileparts(fileparts(fileparts(ST(I).file)));
-0021 
-0022 %Import structures that contain expected MD5 hashes and DIAMOND blastp
-0023 %results
-0024 sourceDir = fileparts(which(mfilename));
-0025 load([sourceDir,'/test_data/expDiamondResults.mat'],'expBlastStructure','expDiamondReport');
-0026 
-0027 organismID='sce';
-0028 fastaFile=fullfile(ravenPath,'testing','unit_tests','test_data','yeast_galactosidases.fa');
-0029 modelIDs={'hsa' 'afv'};
-0030 refFastaFiles={fullfile(ravenPath,'testing','unit_tests','test_data','human_galactosidases.fa') fullfile(ravenPath,'testing','unit_tests','test_data','aflavus_galactosidases.fa')};
-0031 
-0032 %%
-0033 %Run DIAMOND blastp
-0034 [actBlastStructure,actDiamondReport]=getDiamond(organismID,fastaFile,modelIDs,refFastaFiles,true,true);
-0035 
-0036 %%
-0037 %Test 1a: Check if MD5 checksums for DIAMOND blastp database files are the same
-0038 verifyEqual(testCase,actDiamondReport.dbHashes,expDiamondReport.dbHashes);
-0039 
-0040 %Test 1b: Change one of the MD5 checksums and check if test fails
-0041 actDiamondReport.dbHashes{1,1}=actDiamondReport.dbHashes{1,2};
-0042 verifyNotEqual(testCase,actDiamondReport.dbHashes,expDiamondReport.dbHashes);
-0043 
-0044 %Test 2a: Check if DIAMOND blastp result files are the same
-0045 verifyEqual(testCase,actDiamondReport.diamondTxtOutput,expDiamondReport.diamondTxtOutput);
-0046 
-0047 %Test 2b: Change actual DIAMOND blastp result file and check if test fails
-0048 actDiamondReport.diamondTxtOutput='empty';
-0049 verifyNotEqual(testCase,actDiamondReport.diamondTxtOutput,expDiamondReport.diamondTxtOutput);
-0050 
-0051 %Test 3a: Check if DIAMOND blastp structures are the same
-0052 verifyEqual(testCase,actBlastStructure,expBlastStructure);
-0053 
-0054 %Test 3b: Modify actual DIAMOND blastp structure and check if test fails
-0055 actBlastStructure(1,1).toId=actBlastStructure(1,1).fromId;
-0056 verifyNotEqual(testCase,actBlastStructure,expBlastStructure);
-0057 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/testing/unit_tests/fillGapsLargeTests.html b/doc/testing/unit_tests/fillGapsLargeTests.html deleted file mode 100644 index 9b44640b5..000000000 --- a/doc/testing/unit_tests/fillGapsLargeTests.html +++ /dev/null @@ -1,146 +0,0 @@ - - - - Description of fillGapsLargeTests - - - - - - - - - -
Home > testing > unit_tests > fillGapsLargeTests.m
- - - -

fillGapsLargeTests -

- -

PURPOSE ^

-
run this test case with the command
- -

SYNOPSIS ^

-
function tests = fillGapsLargeTests
- -

DESCRIPTION ^

-
run this test case with the command
-results = runtests('fillGapsLargeTests.m')
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 %run this test case with the command
-0002 %results = runtests('fillGapsLargeTests.m')
-0003 function tests = fillGapsLargeTests
-0004 tests = functiontests(localfunctions);
-0005 testGurobi = exist('gurobi','file')==3;
-0006 if testGurobi
-0007     try
-0008         gurobi_read('solverTests.m');
-0009     catch ME
-0010         if ~startsWith(ME.message,{'Gurobi error 10012','Gurobi error 10003'}) % Expected error codes, others may indicate problems with license
-0011            testGurobi = false;
-0012         end
-0013     end
-0014 end
-0015 if ~testGurobi
-0016     disp('Gurobi not installed or not functional, some fillGapsLargeTests skipped.')
-0017     skipTests = contains({tests.Name},'gurobi','IgnoreCase',true);
-0018     tests(skipTests) = [];
-0019 end
-0020 if exist('scip','file')~=3
-0021     disp('SCIP MEX binary not installed or not functional, some fillGapsLargeTests skipped.')
-0022     skipTests = contains({tests.Name},'scip','IgnoreCase',true);
-0023     tests(skipTests) = [];
-0024 end
-0025 end
-0026 
-0027 function testLargeGurobi(testCase)
-0028 sourceDir = fileparts(fileparts(fileparts(which(mfilename))));
-0029 evalc('model=importModel(fullfile(sourceDir,''tutorial'',''iAL1006 v1.00.xml''))');
-0030 model.c(1484)=1;
-0031 modelDB=model; % Keep as database with reactions
-0032 try
-0033     oldSolver=getpref('RAVEN','solver');
-0034 catch
-0035 end
-0036 setRavenSolver('gurobi');
-0037 
-0038 %Remove first 10 reactions
-0039 model=removeReactions(modelDB,(1:10));
-0040 modelDB.id='DB';
-0041 try
-0042     evalc('[newConnected,cannotConnect,addedRxns,model,exitFlag]=fillGaps(model,modelDB,false,false)');
-0043 catch
-0044     try
-0045         setRavenSolver(oldSolver);
-0046     catch
-0047         rmpref('RAVEN','solver');
-0048     end
-0049     error('Solver not working')
-0050 end
-0051 sol=solveLP(model);
-0052 try
-0053     setRavenSolver(oldSolver);
-0054 catch
-0055     rmpref('RAVEN','solver');
-0056 end
-0057 %Expect at least 5% of the original growth
-0058 verifyTrue(testCase,sol.f>0);
-0059 end
-0060 
-0061 function testLargeSCIP(testCase)
-0062 sourceDir = fileparts(fileparts(fileparts(which(mfilename))));
-0063 evalc('model=importModel(fullfile(sourceDir,''tutorial'',''iAL1006 v1.00.xml''))');
-0064 model.c(1484)=1;
-0065 modelDB=model; % Keep as database with reactions
-0066 % Force growth in gapped model
-0067 sol=solveLP(model);
-0068 model.lb(1484)=sol.f*0.1;
-0069 try
-0070     oldSolver=getpref('RAVEN','solver');
-0071 catch
-0072 end
-0073 setRavenSolver('scip');
-0074 
-0075 %Remove first 10 reactions
-0076 model=removeReactions(model,(1:10));
-0077 modelDB.id='DB';
-0078 try
-0079     evalc('[newConnected,cannotConnect,addedRxns,model,exitFlag]=fillGaps(model,modelDB,false,true)');
-0080 catch
-0081     try
-0082         setRavenSolver(oldSolver);
-0083     catch
-0084         rmpref('RAVEN','solver');
-0085     end
-0086     error('Solver not working')
-0087 end
-0088 sol=solveLP(model);
-0089 try
-0090     setRavenSolver(oldSolver);
-0091 catch
-0092     rmpref('RAVEN','solver');
-0093 end
-0094 %Expect at least 5% of the original growth
-0095 verifyTrue(testCase,sol.f>0);
-0096 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/testing/unit_tests/fillGapsSmallTests.html b/doc/testing/unit_tests/fillGapsSmallTests.html deleted file mode 100644 index 3e5fa374c..000000000 --- a/doc/testing/unit_tests/fillGapsSmallTests.html +++ /dev/null @@ -1,144 +0,0 @@ - - - - Description of fillGapsSmallTests - - - - - - - - - -
Home > testing > unit_tests > fillGapsSmallTests.m
- - - -

fillGapsSmallTests -

- -

PURPOSE ^

-
run this test case with the command
- -

SYNOPSIS ^

-
function tests = fillGapsSmallTests
- -

DESCRIPTION ^

-
run this test case with the command
-results = runtests('fillGapsSmallTests.m')
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 %run this test case with the command
-0002 %results = runtests('fillGapsSmallTests.m')
-0003 function tests = fillGapsSmallTests
-0004 tests = functiontests(localfunctions);
-0005 testGurobi = exist('gurobi','file')==3;
-0006 if testGurobi
-0007     try
-0008         gurobi_read('solverTests.m');
-0009     catch ME
-0010         if ~startsWith(ME.message,'Gurobi error 10012') % Expected error code, others may indicate problems with license
-0011            testGurobi = false;
-0012         end
-0013     end
-0014 end
-0015 if ~testGurobi
-0016     disp('Gurobi not installed or not functional, some fillGapsSmallTests skipped.')
-0017     skipTests = contains({tests.Name},'gurobi','IgnoreCase',true);
-0018     tests(skipTests) = [];
-0019 end
-0020 if exist('scip','file')~=3
-0021     disp('SCIP MEX binary not installed or not functional, some fillGapsSmallTests skipped.')
-0022     skipTests = contains({tests.Name},'scip','IgnoreCase',true);
-0023     tests(skipTests) = [];
-0024 end
-0025 end
-0026 
-0027 function testSmallSCIP(testCase)
-0028 %Test using small model
-0029 sourceDir = fileparts(which(mfilename));
-0030 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
-0031 modelDB=model; % Keep as database with reactions
-0032 try
-0033     oldSolver=getpref('RAVEN','solver');
-0034 catch
-0035 end
-0036 setRavenSolver('scip');
-0037 
-0038 %Remove first 10 reactions
-0039 model=removeReactions(modelDB,(1:10));
-0040 modelDB.id='DB';
-0041 try
-0042     evalc('[newConnected,cannotConnect,addedRxns,model,exitFlag]=fillGaps(model,modelDB)');
-0043 catch
-0044     try
-0045         setRavenSolver(oldSolver);
-0046     catch
-0047         rmpref('RAVEN','solver');
-0048     end
-0049     error('Solver not working')
-0050 end
-0051 sol=solveLP(model);
-0052 try
-0053     setRavenSolver(oldSolver);
-0054 catch
-0055     rmpref('RAVEN','solver');
-0056 end
-0057 %Should give non-zero flux
-0058 verifyTrue(testCase,sol.f>0);
-0059 end
-0060 
-0061 function testSmallGurobi(testCase)
-0062 %Test using small model
-0063 sourceDir = fileparts(which(mfilename));
-0064 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
-0065 modelDB=model; % Keep as database with reactions
-0066 try
-0067     oldSolver=getpref('RAVEN','solver');
-0068 catch
-0069 end
-0070 setRavenSolver('gurobi');
-0071 
-0072 %Remove first 10 reactions
-0073 model=removeReactions(modelDB,(1:10));
-0074 
-0075 modelDB.id='DB';
-0076 try
-0077     evalc('[newConnected,cannotConnect,addedRxns,model,exitFlag]=fillGaps(model,modelDB)');
-0078 catch
-0079     try
-0080         setRavenSolver(oldSolver);
-0081     catch
-0082         rmpref('RAVEN','solver');
-0083     end
-0084     error('Solver not working')
-0085 end
-0086 sol=solveLP(model);
-0087 try
-0088     setRavenSolver(oldSolver);
-0089 catch
-0090     rmpref('RAVEN','solver');
-0091 end
-0092 %Expect at least 5% of the original growth
-0093 verifyTrue(testCase,sol.f>0);
-0094 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/testing/unit_tests/hmmerTests.html b/doc/testing/unit_tests/hmmerTests.html deleted file mode 100644 index 121a6d331..000000000 --- a/doc/testing/unit_tests/hmmerTests.html +++ /dev/null @@ -1,203 +0,0 @@ - - - - Description of hmmerTests - - - - - - - - - -
Home > testing > unit_tests > hmmerTests.m
- - - -

hmmerTests -

- -

PURPOSE ^

-
run this test case with the command
- -

SYNOPSIS ^

-
function tests = hmmerTests
- -

DESCRIPTION ^

-
run this test case with the command
-results = runtests('hmmerTests.m')
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 %run this test case with the command
-0002 %results = runtests('hmmerTests.m')
-0003 function tests = hmmerTests
-0004 tests = functiontests(localfunctions);
-0005 end
-0006 
-0007 function testHmmer(testCase)
-0008 %This unit test comprises the functionality test for HMMER in RAVEN:
-0009 % 1. Check of parsed HMMER results against the expected.
-0010 %
-0011 % NOTE: as hmm and HMMER results files are time-specific, no checks for
-0012 % these files existence are done. Also, due to the way HMMER is utilized in
-0013 % getKEGGModelForOrganism (HMMER result files can be parsed only once all
-0014 % required hmm files are generated), the code segment involving HMMER
-0015 % results parsing is pasted in this test function. Should the parsing problems
-0016 % occur in the results processing, the code modifications shall be done in
-0017 % this function and getKEGGModelForOrganism respectively.
-0018 
-0019 %%
-0020 %Get the directory for RAVEN Toolbox
-0021 [ST, I]=dbstack('-completenames');
-0022 ravenPath=fileparts(fileparts(fileparts(ST(I).file)));
-0023 
-0024 %Generate temporary names for working directory and outFile
-0025 tmpDIR=tempname;
-0026 outFile=tempname;
-0027 
-0028 %Create a temporary folder and copy multi-FASTA file there
-0029 [~, ~]=system(['mkdir "' tmpDIR '"']);
-0030 
-0031 sourceDir = fileparts(which(mfilename));
-0032 copyfile(fullfile(sourceDir,'test_data','yeast_galactosidases.fa'),tmpDIR);
-0033 copyfile(fullfile(sourceDir,'test_data','human_galactosidases.fa'),tmpDIR);
-0034 
-0035 
-0036 %Identify the operating system
-0037 if isunix
-0038     if ismac
-0039         binEnd='.mac';
-0040     else
-0041         binEnd='';
-0042     end
-0043 elseif ispc
-0044     wslPath.tmpDIR    = getWSLpath(tmpDIR);
-0045     wslPath.hmmbuild  = getWSLpath(fullfile(ravenPath,'software','hmmer','hmmbuild'));
-0046     wslPath.hmmsearch = getWSLpath(fullfile(ravenPath,'software','hmmer','hmmsearch'));
-0047     filesep='/';
-0048 else
-0049     dispEM('Unknown OS, exiting.')
-0050     return
-0051 end
-0052 
-0053 %Create empty structures needed for HMMER results
-0054 actHmmResult.genes = {};
-0055 actHmmResult.scores = [];
-0056 
-0057 %Create structures that contain expected HMMER results
-0058 expHmmResult.genes = {'sp|P41947|MEL6_YEASX','sp|P41946|MEL5_YEASX', 'sp|P41945|MEL2_YEASX', 'sp|P04824|MEL1_YEASX'};
-0059 expHmmResult.scores = [10^-250, 10^-250, 10^-250, 10^-250];
-0060 
-0061 %Run HMMER multi-threaded to use all logical cores assigned to MATLAB
-0062 cores = evalc('feature(''numcores'')');
-0063 cores = strsplit(cores, 'MATLAB was assigned: ');
-0064 cores = regexp(cores{2},'^\d*','match');
-0065 cores = cores{1};
-0066 
-0067 %%
-0068 %Train a hidden Markov model
-0069 if ismac || isunix
-0070     [~, ~]=system(['"' fullfile(ravenPath,'software','hmmer',['hmmbuild' binEnd]) '" --cpu "' num2str(cores) '" "' fullfile(tmpDIR,'human_galactosidases.hmm') '" "' fullfile(tmpDIR,'yeast_galactosidases.fa') '"']);
-0071 else
-0072     [~, ~]=system(['wsl "' wslPath.hmmbuild '" --cpu "' num2str(cores) '" "' wslPath.tmpDIR '/human_galactosidases.hmm" "' wslPath.tmpDIR '/yeast_galactosidases.fa"']);
-0073 end
-0074 
-0075 %Run a homology search against the newly-trained HMM
-0076 if ismac || isunix
-0077     [~, output]=system(['"' fullfile(ravenPath,'software','hmmer',['hmmsearch' binEnd]) '" --cpu "' num2str(cores) '" "' fullfile(tmpDIR,'human_galactosidases.hmm') '" "' fullfile(tmpDIR,'yeast_galactosidases.fa') '"']);
-0078 else
-0079     [~, output]=system(['wsl "' wslPath.hmmsearch '" --cpu "' num2str(cores) '" "' wslPath.tmpDIR '/human_galactosidases.hmm" "' wslPath.tmpDIR '/yeast_galactosidases.fa"']);
-0080 end
-0081 
-0082 %Save the output to a file
-0083 fid=fopen(outFile,'w');
-0084 fwrite(fid,output);
-0085 fclose(fid);
-0086 
-0087 %%
-0088 %Parse the results
-0089 geneCounter=0;
-0090 fid=fopen(outFile,'r');
-0091 beginMatches=false;
-0092 while 1
-0093     %Get the next line
-0094     tline = fgetl(fid);
-0095     
-0096     %Abort at end of file
-0097     if ~ischar(tline)
-0098         break;
-0099     end
-0100     
-0101     if and(beginMatches,strcmp(tline,'  ------ inclusion threshold ------'))
-0102         break;
-0103     end
-0104     
-0105     if beginMatches==false
-0106         %This is how the listing of matches begins
-0107         if any(strfind(tline,'E-value '))
-0108             %Read one more line that is only padding
-0109             tline = fgetl(fid);
-0110             beginMatches=true;
-0111         end
-0112     else
-0113         %If matches should be read
-0114         if ~strcmp(tline,'   [No hits detected that satisfy reporting thresholds]') && ~isempty(tline)
-0115             elements=regexp(tline,' ','split');
-0116             elements=elements(cellfun(@any,elements));
-0117             
-0118             %Check if the match is below the treshhold
-0119             score=str2double(elements{1});
-0120             gene=elements{9};
-0121             if score<=10^-50
-0122                 %If the score is exactly 0, change it to a very
-0123                 %small value to avoid NaN
-0124                 if score==0
-0125                     score=10^-250;
-0126                 end
-0127                 %Check if the gene is added already and, is so, get
-0128                 %the best score for it
-0129                 geneCounter=geneCounter+1;
-0130                 actHmmResult.genes{geneCounter}=gene;
-0131                 actHmmResult.scores(geneCounter)=score;
-0132             end
-0133         else
-0134             break;
-0135         end
-0136     end
-0137 end
-0138 fclose(fid);
-0139 
-0140 %Remove the old tempfiles
-0141 delete([outFile '*']);
-0142 
-0143 %Remove temporary folder, since testing is finished
-0144 [~, ~]=system(['rm "' tmpDIR '" -r']);
-0145 
-0146 %%
-0147 %Test 1a: Check if HMMER results match the expected ones
-0148 verifyEqual(testCase,actHmmResult,expHmmResult);
-0149 
-0150 %Test 1b: Modify actual HMMER results structure and check if test fails
-0151 actHmmResult.score(2)=1;
-0152 verifyNotEqual(testCase,actHmmResult,expHmmResult);
-0153 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/testing/unit_tests/importExportTests.html b/doc/testing/unit_tests/importExportTests.html deleted file mode 100644 index 00201adb1..000000000 --- a/doc/testing/unit_tests/importExportTests.html +++ /dev/null @@ -1,153 +0,0 @@ - - - - Description of importExportTests - - - - - - - - - -
Home > testing > unit_tests > importExportTests.m
- - - -

importExportTests -

- -

PURPOSE ^

-
run this test case with the command
- -

SYNOPSIS ^

-
function tests = importExportTests
- -

DESCRIPTION ^

-
run this test case with the command
-results = runtests('importExportTests.m')
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 %run this test case with the command
-0002 %results = runtests('importExportTests.m')
-0003 function tests = importExportTests
-0004 tests = functiontests(localfunctions);
-0005 end
-0006 
-0007 function testExcelImport(testCase)
-0008 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
-0009 excelFile=fullfile(sourceDir,'tutorial','empty.xlsx');
-0010 %%Prepare test results, uncomment and run when new reference is needed
-0011 % modelExcel=importExcelModel(excelFile);
-0012 % sbmlFile=fullfile(sourceDir,'tutorial','empty.xml');
-0013 % modelSBML=importModel(sbmlFile);
-0014 % save(fullfile(sourceDir,'testing','unit_tests','test_data','importExportResults.mat'),'modelExcel','modelSBML');
-0015 evalc('model=importExcelModel(excelFile)'); % Repress warnings
-0016 load(fullfile(sourceDir,'testing','unit_tests','test_data','importExportResults.mat'), 'modelExcel');
-0017 verifyEqual(testCase,model,modelExcel)
-0018 end
-0019 
-0020 function testSBMLImport(testCase)
-0021 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
-0022 sbmlFile=fullfile(sourceDir,'tutorial','empty.xml');
-0023 evalc('model=importModel(sbmlFile)'); % Repress warnings
-0024 load(fullfile(sourceDir,'testing','unit_tests','test_data','importExportResults.mat'), 'modelSBML');
-0025 verifyEqual(testCase,model,modelSBML)
-0026 end
-0027 
-0028 function testYAMLimport(testCase)
-0029 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
-0030 yamlFile=fullfile(sourceDir,'tutorial','empty.yml');
-0031 evalc('model=readYAMLmodel(yamlFile)'); % Repress warnings
-0032 load(fullfile(sourceDir,'testing','unit_tests','test_data','importExportResults.mat'), 'modelYAML');
-0033 verifyEqual(testCase,model,modelYAML)
-0034 end
-0035 
-0036 function testExcelExport(testCase)
-0037 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
-0038 load(fullfile(sourceDir,'testing','unit_tests','test_data','ecoli_textbook.mat'), 'model');
-0039 evalc('exportToExcelFormat(model,fullfile(sourceDir,''testing'',''unit_tests'',''test_data'',''_test.xlsx''))');
-0040 %File will not be exactly equal as it contains the current date and time,
-0041 %so md5 or similar would not work. Just check whether file is reasonably
-0042 %sized.
-0043 s = dir(fullfile(sourceDir,'testing','unit_tests','test_data','_test.xlsx'));         
-0044 filesize = s.bytes;
-0045 verifyTrue(testCase,filesize>17000);
-0046 delete(fullfile(sourceDir,'testing','unit_tests','test_data','_test.xlsx'));
-0047 end
-0048 
-0049 function testSBMLExport(testCase)
-0050 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
-0051 load(fullfile(sourceDir,'testing','unit_tests','test_data','ecoli_textbook.mat'), 'model');
-0052 evalc('exportModel(model,fullfile(sourceDir,''testing'',''unit_tests'',''test_data'',''_test.xml''))');
-0053 %File will not be exactly equal as it contains the current date and time,
-0054 %so md5 or similar would not work. Just check whether file is reasonably
-0055 %sized.
-0056 s = dir(fullfile(sourceDir,'testing','unit_tests','test_data','_test.xml'));         
-0057 filesize = s.bytes;
-0058 verifyTrue(testCase,filesize>18500);
-0059 delete(fullfile(sourceDir,'testing','unit_tests','test_data','_test.xml'));
-0060 end
-0061 
-0062 function testSBMLExportNestedSubSystems(testCase)
-0063 %Regression test: a model where reactions have differing numbers of
-0064 %subsystems (nested cell-of-cells, e.g. one reaction in two subsystems and
-0065 %others in one) must be exportable to SBML. Previously exportModel failed
-0066 %with "Dimensions of arrays being concatenated are not consistent" because
-0067 %the subSystems flattening could not concatenate entries of unequal length.
-0068 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
-0069 load(fullfile(sourceDir,'testing','unit_tests','test_data','ecoli_textbook.mat'), 'model');
-0070 
-0071 %Assign nested subSystems: most reactions get a single subsystem, but a few
-0072 %get multiple, which is the scenario that triggered the bug.
-0073 nRxns=numel(model.rxns);
-0074 model.subSystems=repmat({{'Subsystem A'}},nRxns,1);
-0075 model.subSystems{1}={'Subsystem A','Subsystem B'};
-0076 model.subSystems{2}={'Subsystem B','Subsystem C'};
-0077 
-0078 tmpFile=fullfile(sourceDir,'testing','unit_tests','test_data','_testNested.xml');
-0079 %This call previously errored; verify it completes and round-trips.
-0080 evalc('exportModel(model,tmpFile)');
-0081 evalc('modelImported=importModel(tmpFile)');
-0082 delete(tmpFile);
-0083 
-0084 %Subsystems should be preserved (order within a reaction is not guaranteed)
-0085 srt=@(c) sort(reshape(c,1,[]));
-0086 for i=1:3
-0087     j=find(strcmp(modelImported.rxns,model.rxns{i}));
-0088     verifyEqual(testCase,srt(modelImported.subSystems{j}),srt(model.subSystems{i}));
-0089 end
-0090 end
-0091 
-0092 function testYAMLexport(testCase)
-0093 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
-0094 load(fullfile(sourceDir,'tutorial','empty.mat'), 'emptyModel');
-0095 evalc('writeYAMLmodel(emptyModel,fullfile(sourceDir,''testing'',''unit_tests'',''test_data'',''_test.yml''))');
-0096 %File will not be exactly equal as it contains the current date and time,
-0097 %so md5 or similar would not work. Just check whether file is reasonably
-0098 %sized.
-0099 s = dir(fullfile(sourceDir,'testing','unit_tests','test_data','_test.yml'));         
-0100 filesize = s.bytes;
-0101 verifyTrue(testCase,filesize>1290);
-0102 delete(fullfile(sourceDir,'testing','unit_tests','test_data','_test.yml'));
-0103 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/testing/unit_tests/index.html b/doc/testing/unit_tests/index.html deleted file mode 100644 index d476f4516..000000000 --- a/doc/testing/unit_tests/index.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - Index for Directory testing\unit_tests - - - - - - - - - - -
< Master indexIndex for testing\unit_tests >
- -

Index for testing\unit_tests

- -

Matlab files in this directory:

- -
 blastPlusTestsrun this test case with the command
 cdhitTestsrun this test case with the command
 checkTasksTestsrun this test case with the command
 diamondTestsrun this test case with the command
 fillGapsLargeTestsrun this test case with the command
 fillGapsSmallTestsrun this test case with the command
 hmmerTestsrun this test case with the command
 importExportTestsrun this test case with the command
 mafftTestsrun this test case with the command
 mergeModelsTestsrun this test case with the command
 miriamTestsrun this test case with the command
 modelAbilitiesTestsrun this test case with the command
 modelConversionTestsrun this test case with the command
 modelCurationTestsrun this test case with the command
 modelSortingTestsrun this test case with the command
 solverTestsrun this test case with the command
 tinitTestsrun this test case with the command
- - -

Subsequent directories:

-
    -
  • tINITtestInfo
  • test_data
- -
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/testing/unit_tests/mafftTests.html b/doc/testing/unit_tests/mafftTests.html deleted file mode 100644 index 96a9f1fc2..000000000 --- a/doc/testing/unit_tests/mafftTests.html +++ /dev/null @@ -1,117 +0,0 @@ - - - - Description of mafftTests - - - - - - - - - -
Home > testing > unit_tests > mafftTests.m
- - - -

mafftTests -

- -

PURPOSE ^

-
run this test case with the command
- -

SYNOPSIS ^

-
function tests = mafftTests
- -

DESCRIPTION ^

-
run this test case with the command
-results = runtests('mafftTests.m')
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 %run this test case with the command
-0002 %results = runtests('mafftTests.m')
-0003 function tests = mafftTests
-0004 tests = functiontests(localfunctions);
-0005 end
-0006 
-0007 function testMafft(testCase)
-0008 %This unit test comprises the functionality test for MAFFT in RAVEN:
-0009 % 1. Check for resulting file against the expected one.
-0010 
-0011 %%
-0012 %Get the directory for RAVEN Toolbox
-0013 [ST, I]=dbstack('-completenames');
-0014 ravenPath=fileparts(fileparts(fileparts(ST(I).file)));
-0015 
-0016 %Import structure that contains expected MAFFT results
-0017 sourceDir = fileparts(which(mfilename));
-0018 load([sourceDir,'/test_data/expCdhitMafftOutput.mat'],'expCdhitMafftOutput');
-0019 
-0020 %Generate temporary names for working directory and outFile
-0021 tmpDIR=tempname;
-0022 outFile=tempname;
-0023 
-0024 %Run MAFFT multi-threaded to use all logical cores assigned to MATLAB
-0025 cores = evalc('feature(''numcores'')');
-0026 cores = strsplit(cores, 'MATLAB was assigned: ');
-0027 cores = regexp(cores{2},'^\d*','match');
-0028 cores = cores{1};
-0029 
-0030 %Create a temporary folder and copy multi-FASTA file there
-0031 [~, ~]=system(['mkdir "' tmpDIR '"']);
-0032 
-0033 sourceDir = fileparts(which(mfilename));
-0034 copyfile(fullfile(sourceDir,'test_data','yeast_galactosidases.fa'),tmpDIR);
-0035 
-0036 %%
-0037 %Run protein multi-sequence alignment with MAFFT
-0038 if ismac
-0039     [~, ~]=system(['"' fullfile(ravenPath,'software','mafft','mafft-mac','mafft.bat') '" --auto --anysymbol --thread "' num2str(cores) '" "' fullfile(tmpDIR, 'yeast_galactosidases.fa') '" > "' outFile '"']);
-0040 elseif isunix
-0041     [~, ~]=system(['"' fullfile(ravenPath,'software','mafft','mafft-linux64','mafft.bat') '" --auto --anysymbol --thread "' num2str(cores) '" "' fullfile(tmpDIR, 'yeast_galactosidases.fa') '" > "' outFile '"']);
-0042 elseif ispc
-0043     % Define WSL paths
-0044     wslPath.fastaFile=getWSLpath([tmpDIR filesep 'yeast_galactosidases.fa']);
-0045     wslPath.outFile=getWSLpath(outFile);
-0046     wslPath.mafft=getWSLpath(fullfile(ravenPath,'software','mafft','mafft-linux64','mafft.bat'));
-0047     [~, ~]=system(['wsl "' wslPath.mafft '" --auto --anysymbol --quiet --thread "' num2str(cores) '" --out "' wslPath.outFile '" "' wslPath.fastaFile '"']);
-0048 end
-0049 
-0050 %%
-0051 %Open actual MAFFT results file
-0052 actMafftOutput=importdata(fullfile(outFile));
-0053 
-0054 %Remove the old tempfiles
-0055 delete([outFile '*']);
-0056 
-0057 %Remove temporary folder, since testing is finished
-0058 [~, ~]=system(['rm "' tmpDIR '" -r']);
-0059 
-0060 %%
-0061 %Check 1a: Check if files for MAFFT results are the same
-0062 verifyEqual(testCase,actMafftOutput,expCdhitMafftOutput);
-0063 
-0064 %Check 1b: Change actual MAFFT results file and check if test fails
-0065 actMafftOutput='abc';
-0066 verifyNotEqual(testCase,actMafftOutput,expCdhitMafftOutput);
-0067 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/testing/unit_tests/mergeModelsTests.html b/doc/testing/unit_tests/mergeModelsTests.html deleted file mode 100644 index ef7d42dc7..000000000 --- a/doc/testing/unit_tests/mergeModelsTests.html +++ /dev/null @@ -1,159 +0,0 @@ - - - - Description of mergeModelsTests - - - - - - - - - -
Home > testing > unit_tests > mergeModelsTests.m
- - - -

mergeModelsTests -

- -

PURPOSE ^

-
run this test case with the command
- -

SYNOPSIS ^

-
function tests = mergeModelsTests
- -

DESCRIPTION ^

-
run this test case with the command
-results = runtests('mergeModelsTests.m')
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 %run this test case with the command
-0002 %results = runtests('mergeModelsTests.m')
-0003 function tests = mergeModelsTests
-0004 tests = functiontests(localfunctions);
-0005 end
-0006 
-0007 function mergeModelsBasicTest(testCase)
-0008 %Merging plain models (without rxnFrom/metFrom/geneFrom) should create these
-0009 %fields and trace each reaction/metabolite/gene back to the model it came from
-0010 sourceDir = fileparts(which(mfilename));
-0011 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
-0012 
-0013 modelA    = model;
-0014 modelA.id = 'modelA';
-0015 
-0016 %Make all reactions and metabolites in modelB unique so that they are all
-0017 %added as new entities when merging (metabolites are matched by name)
-0018 modelB          = model;
-0019 modelB.id       = 'modelB';
-0020 modelB.rxns     = strcat(modelB.rxns,'_B');
-0021 modelB.mets     = strcat(modelB.mets,'_B');
-0022 modelB.metNames = strcat(modelB.metNames,'_B');
-0023 
-0024 evalc('modelMerged=mergeModels({modelA;modelB})');
-0025 
-0026 %The From fields should exist and have the same size as their entities. Before
-0027 %the fix, metFrom was not extended and ended up shorter than mets
-0028 verifyTrue(testCase,isfield(modelMerged,'rxnFrom'));
-0029 verifyTrue(testCase,isfield(modelMerged,'metFrom'));
-0030 verifyTrue(testCase,isfield(modelMerged,'geneFrom'));
-0031 verifyEqual(testCase,numel(modelMerged.rxnFrom),numel(modelMerged.rxns));
-0032 verifyEqual(testCase,numel(modelMerged.metFrom),numel(modelMerged.mets));
-0033 verifyEqual(testCase,numel(modelMerged.geneFrom),numel(modelMerged.genes));
-0034 
-0035 %Each reaction and metabolite should be traced back to its source model
-0036 verifyEqual(testCase,modelMerged.rxnFrom,[repmat({'modelA'},numel(modelA.rxns),1);repmat({'modelB'},numel(modelB.rxns),1)]);
-0037 verifyEqual(testCase,modelMerged.metFrom,[repmat({'modelA'},numel(modelA.mets),1);repmat({'modelB'},numel(modelB.mets),1)]);
-0038 %Genes are shared between the models, so all are traced to the first model
-0039 verifyTrue(testCase,all(ismember(modelMerged.geneFrom,{'modelA','modelB'})));
-0040 end
-0041 
-0042 function mergeModelsKeepExistingFromTest(testCase)
-0043 %If the input models already have rxnFrom/metFrom/geneFrom fields, mergeModels
-0044 %should keep those values instead of overwriting them with the model ids
-0045 sourceDir = fileparts(which(mfilename));
-0046 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
-0047 
-0048 modelA          = model;
-0049 modelA.id       = 'modelA';
-0050 modelA.rxnFrom  = repmat({'origA'},numel(modelA.rxns),1);
-0051 modelA.metFrom  = repmat({'origA'},numel(modelA.mets),1);
-0052 
-0053 modelB          = model;
-0054 modelB.id       = 'modelB';
-0055 modelB.rxns     = strcat(modelB.rxns,'_B');
-0056 modelB.mets     = strcat(modelB.mets,'_B');
-0057 modelB.metNames = strcat(modelB.metNames,'_B');
-0058 modelB.rxnFrom  = repmat({'origB'},numel(modelB.rxns),1);
-0059 modelB.metFrom  = repmat({'origB'},numel(modelB.mets),1);
-0060 
-0061 evalc('modelMerged=mergeModels({modelA;modelB})');
-0062 
-0063 %The pre-existing labels should be preserved, not replaced by the model ids
-0064 verifyEqual(testCase,modelMerged.rxnFrom,[repmat({'origA'},numel(modelA.rxns),1);repmat({'origB'},numel(modelB.rxns),1)]);
-0065 verifyEqual(testCase,modelMerged.metFrom,[repmat({'origA'},numel(modelA.mets),1);repmat({'origB'},numel(modelB.mets),1)]);
-0066 end
-0067 
-0068 function mergeModelsViaCopyToCompsTest(testCase)
-0069 %copyToComps runs mergeModels with the copyToComps flag set. When the input
-0070 %model has no rxnFrom/metFrom/geneFrom fields, the output should not gain any
-0071 sourceDir = fileparts(which(mfilename));
-0072 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
-0073 
-0074 evalc('modelNew=copyToComps(model,{''p''},''ACKr'')');
-0075 
-0076 verifyFalse(testCase,isfield(modelNew,'rxnFrom'));
-0077 verifyFalse(testCase,isfield(modelNew,'metFrom'));
-0078 verifyFalse(testCase,isfield(modelNew,'geneFrom'));
-0079 %The reaction should still have been copied to the new compartment
-0080 verifyTrue(testCase,ismember('ACKr_p',modelNew.rxns));
-0081 end
-0082 
-0083 function mergeModelsViaCopyToCompsKeepFromTest(testCase)
-0084 %When the input model already has the From fields, copyToComps should keep
-0085 %them and assign empty labels ('') to the newly created reactions/metabolites
-0086 sourceDir = fileparts(which(mfilename));
-0087 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
-0088 
-0089 model.rxnFrom  = repmat({'orig'},numel(model.rxns),1);
-0090 model.metFrom  = repmat({'orig'},numel(model.mets),1);
-0091 model.geneFrom = repmat({'orig'},numel(model.genes),1);
-0092 
-0093 nRxns = numel(model.rxns);
-0094 nMets = numel(model.mets);
-0095 
-0096 evalc('modelNew=copyToComps(model,{''p''},''ACKr'')');
-0097 
-0098 %The fields should still be present and consistent in size
-0099 verifyEqual(testCase,numel(modelNew.rxnFrom),numel(modelNew.rxns));
-0100 verifyEqual(testCase,numel(modelNew.metFrom),numel(modelNew.mets));
-0101 %The original labels are kept, the new reactions/metabolites are labelled ''
-0102 verifyEqual(testCase,modelNew.rxnFrom(1:nRxns),model.rxnFrom);
-0103 verifyEqual(testCase,modelNew.metFrom(1:nMets),model.metFrom);
-0104 verifyTrue(testCase,all(strcmp(modelNew.rxnFrom(nRxns+1:end),'')));
-0105 verifyTrue(testCase,all(strcmp(modelNew.metFrom(nMets+1:end),'')));
-0106 %No new genes are introduced, so geneFrom is left untouched
-0107 verifyEqual(testCase,modelNew.geneFrom,model.geneFrom);
-0108 end
-0109
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/testing/unit_tests/miriamTests.html b/doc/testing/unit_tests/miriamTests.html deleted file mode 100644 index b84499d0f..000000000 --- a/doc/testing/unit_tests/miriamTests.html +++ /dev/null @@ -1,86 +0,0 @@ - - - - Description of miriamTests - - - - - - - - - -
Home > testing > unit_tests > miriamTests.m
- - - -

miriamTests -

- -

PURPOSE ^

-
run this test case with the command
- -

SYNOPSIS ^

-
function tests = miriamTests
- -

DESCRIPTION ^

-
run this test case with the command
-results = runtests('miriamTests.m')
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 %run this test case with the command
-0002 %results = runtests('miriamTests.m')
-0003 function tests = miriamTests
-0004 tests = functiontests(localfunctions);
-0005 end
-0006 
-0007 function editMiriam_and_extractMiriamTest(testCase)
-0008 %This function tests the extractMiriam and editMiriam functions
-0009 
-0010 %%
-0011 %Load the expected (i.e. sorted) model
-0012 sourceDir = fileparts(which(mfilename));
-0013 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
-0014 
-0015 %Try out all combinations, keep metMiriams field, compare with output
-0016 modelTest=editMiriam(model,'met',1,'bigg.metabolite','test','add');
-0017 testOut{1}=modelTest.metMiriams;
-0018 modelTest=editMiriam(model,'met',1,'bigg.metabolite','test','replace');
-0019 testOut{end+1}=modelTest.metMiriams;
-0020 modelTest=editMiriam(model,'met',1,'bigg.metabolite','test','fill');
-0021 testOut{end+1}=modelTest.metMiriams;
-0022 modelTest=editMiriam(model,'met','all','bigg.metabolite','test','add');
-0023 testOut{end+1}=modelTest.metMiriams;
-0024 modelTest=editMiriam(model,'met',true(1,numel(model.mets)),'bigg.metabolite','test','add');
-0025 testOut{end+1}=modelTest.metMiriams;
-0026 modelTest=editMiriam(model,'met','3pg_c','bigg.metabolite','test','add');
-0027 testOut{end+1}=modelTest.metMiriams;
-0028 modelTest=editMiriam(model,'met','3pg_c','bigg.metabolite','3pg','add');
-0029 testOut{end+1}=modelTest.metMiriams;
-0030 
-0031 %Load the correct results to compare with
-0032 load([sourceDir,'/test_data/miriamTestOutput.mat'])
-0033 
-0034 %Check that the actual model is the same as the expected model
-0035 verifyEqual(testCase,testOut,testOutOriginal)
-0036 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/testing/unit_tests/modelAbilitiesTests.html b/doc/testing/unit_tests/modelAbilitiesTests.html deleted file mode 100644 index 6841b69a0..000000000 --- a/doc/testing/unit_tests/modelAbilitiesTests.html +++ /dev/null @@ -1,173 +0,0 @@ - - - - Description of modelAbilitiesTests - - - - - - - - - -
Home > testing > unit_tests > modelAbilitiesTests.m
- - - -

modelAbilitiesTests -

- -

PURPOSE ^

-
run this test case with the command
- -

SYNOPSIS ^

-
function tests = modelAbilitiesTests
- -

DESCRIPTION ^

-
run this test case with the command
-results = runtests('modelAbilitiesTests.m')
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 %run this test case with the command
-0002 %results = runtests('modelAbilitiesTests.m')
-0003 function tests = modelAbilitiesTests
-0004 tests = functiontests(localfunctions);
-0005 end
-0006 
-0007 function canConsumeTest(testCase)
-0008 %Load the model in RAVEN format
-0009 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
-0010 load(fullfile(sourceDir,'testing','unit_tests','test_data','ecoli_textbook.mat'), 'model');
-0011 
-0012 testOut=canConsume(model,{'r5p_c';'ru5p_DASH_D_c';'s7p_c';'succ_c';'succ_e';'succoa_c';'xu5p_DASH_D_c'});
-0013 
-0014 testCheck=[true;true;true;true;true;false;true];
-0015 
-0016 verifyEqual(testCase,testOut,testCheck)
-0017 end
-0018 
-0019 function canProduceTest(testCase)
-0020 %Load the model in RAVEN format
-0021 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
-0022 load(fullfile(sourceDir,'testing','unit_tests','test_data','ecoli_textbook.mat'), 'model');
-0023 
-0024 testOut=canProduce(model,{'r5p_c';'ru5p_DASH_D_c';'s7p_c';'succ_c';'succ_e';'succoa_c';'xu5p_DASH_D_c'});
-0025 
-0026 testCheck=[true;true;true;true;true;false;true];
-0027 
-0028 verifyEqual(testCase,testOut,testCheck)
-0029 end
-0030 
-0031 function checkProductionTest(testCase)
-0032 %Load the model in RAVEN format
-0033 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
-0034 load(fullfile(sourceDir,'testing','unit_tests','test_data','ecoli_textbook.mat'), 'model');
-0035 
-0036 [testOut.np, testOut.npn, testOut.nfpm,testOut.mtc,~]=checkProduction(model,true,model.comps,false);
-0037 
-0038 testCheck.np=[10;13;16;17;21;30;32;37;49;50;51;52;53;64;65;71];
-0039 testCheck.npn={'Acetyl-CoA[c]';'ADP[c]';'AMP[c]';'ATP[c]';'Coenzyme A[c]';'D-Fructose[e]';'Fumarate[e]';'L-Glutamine[e]';'L-Malate[e]';'NAD[c]';'NADH[c]';'NADP[c]';'NADPH[c]';'Ubiquinone-8[c]';'Ubiquinol-8[c]';'Succinyl-CoA[c]'};
-0040 testCheck.nfpm=[true,false,false,false,true,false,false,false,false,false,false,false,false,false,false,true;false,true,true,true,false,false,false,false,false,false,false,false,false,false,false,false;false,true,true,true,false,false,false,false,false,false,false,false,false,false,false,false;false,true,true,true,false,false,false,false,false,false,false,false,false,false,false,false;true,false,false,false,true,false,false,false,false,false,false,false,false,false,false,true;false,false,false,false,false,true,false,false,false,false,false,false,false,false,false,false;false,false,false,false,false,false,true,false,false,false,false,false,false,false,false,false;false,false,false,false,false,false,false,true,false,false,false,false,false,false,false,false;false,false,false,false,false,false,false,false,true,false,false,false,false,false,false,false;false,false,false,false,false,false,false,false,false,true,true,false,false,false,false,false;false,false,false,false,false,false,false,false,false,true,true,false,false,false,false,false;false,false,false,false,false,false,false,false,false,false,false,true,true,false,false,false;false,false,false,false,false,false,false,false,false,false,false,true,true,false,false,false;false,false,false,false,false,false,false,false,false,false,false,false,false,true,true,false;false,false,false,false,false,false,false,false,false,false,false,false,false,true,true,false;true,false,false,false,true,false,false,false,false,false,false,false,false,false,false,true];
-0041 testCheck.mtc={'Acetyl-CoA[c] (connects 3 metabolites)';'ADP[c] (connects 3 metabolites)';'NAD[c] (connects 2 metabolites)';'NADP[c] (connects 2 metabolites)';'Ubiquinone-8[c] (connects 2 metabolites)';'D-Fructose[e] (connects 1 metabolites)';'Fumarate[e] (connects 1 metabolites)';'L-Glutamine[e] (connects 1 metabolites)';'L-Malate[e] (connects 1 metabolites)'};
-0042 
-0043 verifyEqual(testCase,testOut,testCheck)
-0044 end
-0045 
-0046 function consumeSomethingTest(testCase)
-0047 %Load the model in RAVEN format
-0048 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
-0049 load(fullfile(sourceDir,'testing','unit_tests','test_data','ecoli_textbook.mat'), 'model');
-0050 
-0051 [testOut.s, testOut.m]=consumeSomething(model,{'r5p_c';'ru5p_DASH_D_c';'s7p_c';'succ_c';'succ_e';'succoa_c';'xu5p_DASH_D_c'});
-0052 % Simplify output for later check, no need for high precision
-0053 % testOut.s(abs(testOut.s)<1e-10)=0;
-0054 % testOut.s=round(testOut.s,4)
-0055 testCheck.s=[0;0;1.4591;0;0;1.4591;0;0;0;0;8.39;4.0126;0;1.4591;0;2.9183;0;1.4591;0;1.4591;0;0;1.4591;0;0;0;0;0;0;0;1.4591;0;0;0;0;-1.4591;1.4591;0;0;0;0;0;0;0;0;0;0;0;-1.4591;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;2.9183;0;0;-1.4591;1.4591;0;0;0;-1.4591;0;1.4591;1.4591;0;0;0;-1.4591;1.4591;0;0;0;0;0;0;0;0;0;0;0;0];
-0056 testCheck.m=[33];
-0057 
-0058 verifyEqual(testCase,testOut,testCheck,'AbsTol',1e-4)
-0059 end
-0060 
-0061 function makeSomethingTest(testCase)
-0062 %Load the model in RAVEN format
-0063 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
-0064 load(fullfile(sourceDir,'testing','unit_tests','test_data','ecoli_textbook.mat'), 'model');
-0065 
-0066 [testOut.s, testOut.m]=makeSomething(model,{'r5p_c';'ru5p_DASH_D_c';'s7p_c';'succ_c';'succ_e';'succoa_c';'xu5p_DASH_D_c'});
-0067 % Simplify output for later check, no need for high precision
-0068 % testOut.s(abs(testOut.s)<1e-10)=0;
-0069 % testOut.s=round(testOut.s,4);
-0070 
-0071 testCheck.s=[0;0;1.8644;0;0;0;0;0;0;0;8.39;4.6611;0;0;0;3.7289;0;1.8644;0;0;0;0;0;0;0;0;0;-0.93220;0;0;0;0;0;0;0;-1.8644;0;0;0;0.93220;0;0;0;0;0;0;0;0;-1.8644;0.93220;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;3.7289;0;0;-1.8644;1.8644;0.93220;0;-0.93220;-1.8644;0;1.8644;0;0;0;0;-1.8644;0.93220;0;0;0;0;0;0;0;0;0;0;0;0.93220];
-0072 testCheck.m=[6];
-0073 
-0074 verifyEqual(testCase,testOut,testCheck,'AbsTol',1e-4)
-0075 end
-0076 
-0077 function getElementalBalanceTest(testCase)
-0078 %Load the model in RAVEN format
-0079 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
-0080 load(fullfile(sourceDir,'testing','unit_tests','test_data','ecoli_textbook.mat'), 'model');
-0081 
-0082 testOut=getElementalBalance(model,1);
-0083 
-0084 testCheck.balanceStatus=1;
-0085 testCheck.elements.abbrevs={'C';'N';'O';'S';'P';'H'};
-0086 testCheck.elements.names={'carbon';'nitrogen';'oxygen';'sulfur';'phosphorus';'hydrogen'};
-0087 testCheck.leftComp=[44,14,31,1,5,62];
-0088 testCheck.rightComp=[44,14,31,1,5,62];
-0089 
-0090 verifyEqual(testCase,testOut,testCheck)
-0091 end
-0092 
-0093 function getAllowedBoundsTest(testCase)
-0094 %Load the model in RAVEN format
-0095 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
-0096 load(fullfile(sourceDir,'testing','unit_tests','test_data','ecoli_textbook.mat'), 'model');
-0097 
-0098 
-0099 evalc("[testOut.min, testOut.max, testOut.flag]=getAllowedBounds(model,[1:10],false);");
-0100 % Simplify output for later check, no need for high precision
-0101 % testOut.min(abs(testOut.min)<1e-10)=0;
-0102 % testOut.min=single(testOut.min);
-0103 % testOut.max(abs(testOut.max)<1e-10)=0;
-0104 % testOut.max=single(testOut.max);
-0105 
-0106 testCheck.min=[-20;0;0;0;0;0;-166.610;0;0;0];
-0107 testCheck.max=[0;20;20;20;20;20;0;20;10;20];
-0108 testCheck.flag=[1,1;1,1;1,1;1,1;1,1;1,1;1,1;1,1;1,1;1,1];
-0109 
-0110 verifyEqual(testCase,testOut,testCheck,'AbsTol',1e-4)
-0111 end
-0112 
-0113 function getEssentialRxnsTest(testCase)
-0114 %Load the model in RAVEN format
-0115 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
-0116 load(fullfile(sourceDir,'testing','unit_tests','test_data','ecoli_textbook.mat'), 'model');
-0117 
-0118 [testOut.r, testOut.i]=getEssentialRxns(model);
-0119 
-0120 testCheck.r={'EX_glc';'GLCpts'};
-0121 testCheck.i=[28;50];
-0122 verifyEqual(testCase,testOut,testCheck)
-0123 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/testing/unit_tests/modelConversionTests.html b/doc/testing/unit_tests/modelConversionTests.html deleted file mode 100644 index 269e71e1b..000000000 --- a/doc/testing/unit_tests/modelConversionTests.html +++ /dev/null @@ -1,75 +0,0 @@ - - - - Description of modelConversionTests - - - - - - - - - -
Home > testing > unit_tests > modelConversionTests.m
- - - -

modelConversionTests -

- -

PURPOSE ^

-
run this test case with the command
- -

SYNOPSIS ^

-
function tests = modelConversionTests
- -

DESCRIPTION ^

-
run this test case with the command
-results = runtests('modelConversionTests.m')
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 %run this test case with the command
-0002 %results = runtests('modelConversionTests.m')
-0003 function tests = modelConversionTests
-0004 tests = functiontests(localfunctions);
-0005 end
-0006 
-0007 function ravenCobraWrapperTest(testCase)
-0008 %This function tests the ravenCobraWrapper function by going through a full
-0009 %cycle RAVEN -> COBRA -> RAVEN, and the model should be (near) identical
-0010 %(only annotation field should be lost).
-0011 
-0012 %Load the model in RAVEN format
-0013 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
-0014 load(fullfile(sourceDir,'testing','unit_tests','test_data','ecoli_textbook.mat'), 'model');
-0015 
-0016 %Prevent writing of messages to command window
-0017 evalc('modelCobra=ravenCobraWrapper(model);');
-0018 evalc('modelRaven=ravenCobraWrapper(modelCobra);');
-0019 
-0020 %We know that the annotation field is lost
-0021 modelNoAnnot=rmfield(model,'annotation');
-0022 
-0023 %Check that the actual model is the same as the expected model
-0024 verifyEqual(testCase,modelRaven,modelNoAnnot)
-0025 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/testing/unit_tests/modelCurationTests.html b/doc/testing/unit_tests/modelCurationTests.html deleted file mode 100644 index dde7fe80c..000000000 --- a/doc/testing/unit_tests/modelCurationTests.html +++ /dev/null @@ -1,543 +0,0 @@ - - - - Description of modelCurationTests - - - - - - - - - -
Home > testing > unit_tests > modelCurationTests.m
- - - -

modelCurationTests -

- -

PURPOSE ^

-
run this test case with the command
- -

SYNOPSIS ^

-
function tests = modelCurationTests
- -

DESCRIPTION ^

-
run this test case with the command
-results = runtests('modelCurationTests.m')
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 %run this test case with the command
-0002 %results = runtests('modelCurationTests.m')
-0003 function tests = modelCurationTests
-0004 tests = functiontests(localfunctions);
-0005 end
-0006 
-0007 function addExchangeRxnsTest(testCase)
-0008 sourceDir = fileparts(which(mfilename));
-0009 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
-0010 
-0011 modelNew=addExchangeRxns(model,'both','6pgl_c');
-0012 
-0013 %Perform the curation manually for comparison
-0014 modelManual=model;
-0015 modelManual.rxns(end+1)={'EXC_BOTH_6pgl_c'};
-0016 modelManual.lb(end+1)=-1000;
-0017 modelManual.ub(end+1)=1000;
-0018 modelManual.c(end+1)=0;
-0019 modelManual.rev(end+1)=1;
-0020 modelManual.rxnNames(end+1)={'6-phospho-D-glucono-1,5-lactone exchange (BOTH)'};
-0021 modelManual.grRules(end+1)={''};
-0022 modelManual.eccodes(end+1)={''};
-0023 modelManual.rxnGeneMat(end+1,:)=sparse(zeros(1,numel(modelManual.genes)));
-0024 modelManual.S(:,end+1)=sparse(zeros(numel(modelManual.mets),1));
-0025 modelManual.S(5,end)=-1;
-0026 
-0027 verifyEqual(testCase,modelNew,modelManual)
-0028 end
-0029 
-0030 function addTransportTest(testCase)
-0031 sourceDir = fileparts(which(mfilename));
-0032 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
-0033 
-0034 evalc('modelNew=addTransport(model,''c'',''e'',{''6-phospho-D-glucono-1,5-lactone''},false,false,''test_'');');
-0035 
-0036 %Perform the curation manually for comparison
-0037 modelManual=model;
-0038 modelManual.rxns(end+1)={'test_0001'};
-0039 modelManual.lb(end+1)=0;
-0040 modelManual.ub(end+1)=Inf;
-0041 modelManual.c(end+1)=0;
-0042 modelManual.rev(end+1)=0;
-0043 modelManual.rxnNames(end+1)={'6-phospho-D-glucono-1,5-lactone transport, Cytoplasm-Extraorganism'};
-0044 modelManual.grRules(end+1)={''};
-0045 modelManual.eccodes(end+1)={''};
-0046 modelManual.rxnGeneMat(end+1,:)=sparse(zeros(1,numel(modelManual.genes)));
-0047 
-0048 modelManual.S(:,end+1)=sparse(zeros(numel(modelManual.mets),1));
-0049 modelManual.S(end+1,:)=sparse(zeros(1,numel(modelManual.rxns)));
-0050 modelManual.S([5,73],end)=[-1,1];
-0051 
-0052 modelManual.mets(end+1)={'m_0001'};
-0053 modelManual.metNames(end+1)={'6-phospho-D-glucono-1,5-lactone'};
-0054 modelManual.metMiriams(end+1)=modelManual.metMiriams(5);
-0055 modelManual.b(end+1)=[0];
-0056 modelManual.metFormulas(end+1)={'C6H9O9P'};
-0057 modelManual.metComps(end+1)=[2];
-0058 
-0059 verifyEqual(testCase,modelNew,modelManual)
-0060 end
-0061 
-0062 function addGenesRavenTest(testCase)
-0063 sourceDir = fileparts(which(mfilename));
-0064 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
-0065 
-0066 genesToAdd.genes={'testgene1','testgene2'};
-0067 genesToAdd.geneShortNames={'short1','short2'};
-0068 genesToAdd.geneMiriams{1}=struct('name',{{'testDB1';'testDB2'}},'value',...
-0069     {{'testValue1';'testValue2'}});
-0070 genesToAdd.geneMiriams{2}=struct('name',{{'testDB2';'testDB1'}},'value',...
-0071     {{'testValue2';'testValue1'}});
-0072 
-0073 modelNew=addGenesRaven(model,genesToAdd);
-0074 
-0075 %Perform the curation manually for comparison
-0076 modelManual=model;
-0077 modelManual.geneMiriams(1:numel(modelManual.genes),1)={[]};
-0078 modelManual.genes(end+1:end+2)=genesToAdd.genes;
-0079 modelManual.geneShortNames(end+1:end+2)=genesToAdd.geneShortNames;
-0080 modelManual.rxnGeneMat(:,end+1:end+2)=sparse(zeros(numel(modelManual.rxns),2));
-0081 modelManual.geneMiriams(end+1:end+2)=genesToAdd.geneMiriams;
-0082 verifyEqual(testCase,modelNew,modelManual)
-0083 end
-0084 
-0085 function removeGenesTest(testCase)
-0086 sourceDir = fileparts(which(mfilename));
-0087 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
-0088 
-0089 modelNew=removeGenes(model,'b1817',true,true,false);
-0090 
-0091 %Perform the curation manually for comparison
-0092 modelManual=model;
-0093 modelManual.genes(54)=[];
-0094 modelManual.geneShortNames(54)=[];
-0095 modelManual.rxnGeneMat(:,54)=[];
-0096 modelManual.rxnGeneMat(45,:)=[];
-0097 modelManual.grRules(50)={'(b2415 and b1621 and b2417 and b2416) or (b2415 and b2417 and b2416 and b1101)'};
-0098 modelManual.grRules(45)=[];
-0099 modelManual.rxns(45)=[];
-0100 modelManual.rxnNames(45)=[];
-0101 modelManual.lb(45)=[];
-0102 modelManual.ub(45)=[];
-0103 modelManual.c(45)=[];
-0104 modelManual.rev(45)=[];
-0105 modelManual.S(:,45)=[];
-0106 modelManual.eccodes(45)=[];
-0107 verifyEqual(testCase,modelNew,modelManual)
-0108 end
-0109 
-0110 function addMetsTest(testCase)
-0111 sourceDir = fileparts(which(mfilename));
-0112 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
-0113 
-0114 metsToAdd.metNames={'metaboliteName','3-Phospho-D-glycerate'};
-0115 metsToAdd.compartments={'c','e'};
-0116 metsToAdd.metCharges=[2,0];
-0117 metsToAdd.metNotes={'this is just a test','another one'};
-0118 metsToAdd.metMiriams{1}=struct('name',{{'testDB1';'testDB2'}},'value',...
-0119     {{'testValue1';'testValue2'}});
-0120 metsToAdd.metMiriams{2}=struct('name',{{'testDB1'}},'value',...
-0121     {{'testValue1'}});
-0122 
-0123 evalc('modelNew=addMets(model,metsToAdd,true);');
-0124 
-0125 %Perform the curation manually for comparison
-0126 modelManual=model;
-0127 modelManual.metNotes(1:numel(modelManual.mets),1)={''};
-0128 modelManual.metCharges(1:numel(modelManual.mets),1)=NaN(numel(modelManual.mets),1);
-0129 modelManual.mets(end+1:end+2)={'m_0001','m_0002'};
-0130 modelManual.metNames(end+1:end+2)=metsToAdd.metNames;
-0131 modelManual.metNotes(end+1:end+2)=metsToAdd.metNotes;
-0132 modelManual.metMiriams(end+1:end+2)=metsToAdd.metMiriams;
-0133 modelManual.metCharges(end+1:end+2)=[2,NaN];
-0134 modelManual.b(end+1:end+2)=[0,0];
-0135 modelManual.metFormulas(end+1:end+2)={'','C3H4O7P'};
-0136 modelManual.metComps(end+1:end+2)=[1,2];
-0137 modelManual.S(end+1:end+2,:)=sparse(zeros(2,numel(modelManual.rxns)));
-0138 
-0139 verifyEqual(testCase,modelManual,modelNew)
-0140 end
-0141 
-0142 function addMets_oneCompTest(testCase)
-0143 sourceDir = fileparts(which(mfilename));
-0144 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
-0145 
-0146 metsToAdd.metNames={'metaboliteName','3-Phospho-D-glycerate'};
-0147 metsToAdd.compartments={'e'};
-0148 metsToAdd.metCharges=[2,0];
-0149 metsToAdd.metNotes={'this is just a test','another one'};
-0150 metsToAdd.metMiriams{1}=struct('name',{{'testDB1';'testDB2'}},'value',...
-0151     {{'testValue1';'testValue2'}});
-0152 metsToAdd.metMiriams{2}=struct('name',{{'testDB1'}},'value',...
-0153     {{'testValue1'}});
-0154 
-0155 evalc('modelNew=addMets(model,metsToAdd,true);');
-0156 
-0157 %Perform the curation manually for comparison
-0158 modelManual=model;
-0159 modelManual.metNotes(1:numel(modelManual.mets),1)={''};
-0160 modelManual.metCharges(1:numel(modelManual.mets),1)=NaN(numel(modelManual.mets),1);
-0161 modelManual.mets(end+1:end+2)={'m_0001','m_0002'};
-0162 modelManual.metNames(end+1:end+2)=metsToAdd.metNames;
-0163 modelManual.metNotes(end+1:end+2)=metsToAdd.metNotes;
-0164 modelManual.metMiriams(end+1:end+2)=metsToAdd.metMiriams;
-0165 modelManual.metCharges(end+1:end+2)=[2,NaN];
-0166 modelManual.b(end+1:end+2)=[0,0];
-0167 modelManual.metFormulas(end+1:end+2)={'','C3H4O7P'};
-0168 modelManual.metComps(end+1:end+2)=2;
-0169 modelManual.S(end+1:end+2,:)=sparse(zeros(2,numel(modelManual.rxns)));
-0170 
-0171 verifyEqual(testCase,modelManual,modelNew)
-0172 end
-0173 
-0174 function removeMetsTest(testCase)
-0175 sourceDir = fileparts(which(mfilename));
-0176 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
-0177 
-0178 modelNew=removeMets(model,'Acetate',true,true,true,true);
-0179 
-0180 %Perform the curation manually for comparison
-0181 modelManual=model;
-0182 modelManual.mets(6:7)=[];
-0183 modelManual.metNames(6:7)=[];
-0184 modelManual.metMiriams(6:7)=[];
-0185 modelManual.b(6:7)=[];
-0186 modelManual.metFormulas(6:7)=[];
-0187 modelManual.metComps(6:7)=[];
-0188 modelManual.S(6:7,:)=[];
-0189 
-0190 modelManual.rxnGeneMat(20,:)=[];
-0191 modelManual.grRules(20)=[];
-0192 modelManual.rxns(20)=[];
-0193 modelManual.rxnNames(20)=[];
-0194 modelManual.lb(20)=[];
-0195 modelManual.ub(20)=[];
-0196 modelManual.c(20)=[];
-0197 modelManual.rev(20)=[];
-0198 modelManual.S(:,20)=[];
-0199 modelManual.eccodes(20)=[];
-0200 verifyEqual(testCase,modelNew,modelManual)
-0201 end
-0202 
-0203 function addRxnsTest(testCase)
-0204 sourceDir = fileparts(which(mfilename));
-0205 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
-0206 rxnsToAdd.rxns='test1';
-0207 rxnsToAdd.equations='2-Oxoglutarate => TEST';
-0208 rxnsToAdd.rxnNames={'testRxn1'}; % test cell array
-0209 rxnsToAdd.rxnMiriams{1}=struct('name',{{'testDB1';'testDB2'}},'value',...
-0210     {{'testValue1';'testValue2'}});
-0211 rxnsToAdd.grRules="b0008"; % test string
-0212 evalc('modelNew=addRxns(model,rxnsToAdd,2,''c'',true);');
-0213 
-0214 rxnsToAdd.rxns='test2';
-0215 rxnsToAdd=rmfield(rxnsToAdd,'equations');
-0216 rxnsToAdd.mets={{'6pgl_c','atp_c'}};
-0217 rxnsToAdd.stoichCoeffs=[[-1,2]];
-0218 rxnsToAdd.lb=-1000;
-0219 rxnsToAdd.grRules='test';
-0220 evalc('modelNew=addRxns(modelNew,rxnsToAdd,1,''c'',true,true);');
-0221 
-0222 %Perform the curation manually for comparison
-0223 modelManual=model;
-0224 
-0225 modelManual.rxnMiriams=cell(numel(modelManual.rxns),1);
-0226 modelManual.rxns(end+1:end+2)={'test1';'test2'};
-0227 modelManual.mets(end+1)={'m_0001'};
-0228 modelManual.S(end+1,:)=zeros(1,numel(modelManual.rxns)-2);
-0229 modelManual.S(:,end+1:end+2)=zeros(numel(modelManual.mets),2);
-0230 modelManual.S(end,96)=1;
-0231 modelManual.S([14,73],end-1)=[-1,1];
-0232 modelManual.S([5,17],end)=[-1,2];
-0233 modelManual.lb(end+1:end+2)=[0;-1000];
-0234 modelManual.ub(end+1:end+2)=[Inf;Inf];
-0235 modelManual.rev(end+1:end+2)=[0;1];
-0236 modelManual.c(end+1:end+2)=[0;0];
-0237 modelManual.b(end+1)=[0];
-0238 modelManual.rxnNames(end+1:end+2)={'testRxn1';'testRxn1'};
-0239 modelManual.grRules(end+1:end+2)={'b0008';'test'};
-0240 
-0241 modelManual.rxnGeneMat(end+1:end+2,:)=zeros(2,numel(modelManual.genes));
-0242 modelManual.rxnGeneMat(:,end+1)=zeros(numel(modelManual.rxns),1);
-0243 modelManual.rxnGeneMat(97,end)=1;
-0244 modelManual.rxnGeneMat(end-1,1)=1;
-0245 modelManual.rxnGeneMat(end,138)=1;
-0246 
-0247 modelManual.eccodes(end+1:end+2)={'';''};
-0248 modelManual.genes(end+1)={'test'};
-0249 modelManual.geneShortNames(end+1)={''};
-0250 modelManual.metNames(end+1)={'TEST'};
-0251 modelManual.metComps(end+1)=[1];
-0252 modelManual.metFormulas(end+1)={''};
-0253 modelManual.metMiriams(end+1)={[]};
-0254 modelManual.rxnMiriams(end+1:end+2)={struct('name',{{'testDB1';'testDB2'}},'value',...
-0255     {{'testValue1';'testValue2'}})};
-0256 
-0257 verifyEqual(testCase,modelManual,modelNew)
-0258 end
-0259 
-0260 function removeReactionsTest(testCase)
-0261 sourceDir = fileparts(which(mfilename));
-0262 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
-0263 
-0264 modelNew=removeMets(model,'Acetate',true,true,true,true);
-0265 
-0266 %Perform the curation manually for comparison
-0267 modelManual=model;
-0268 modelManual.mets(6:7)=[];
-0269 modelManual.metNames(6:7)=[];
-0270 modelManual.metMiriams(6:7)=[];
-0271 modelManual.b(6:7)=[];
-0272 modelManual.metFormulas(6:7)=[];
-0273 modelManual.metComps(6:7)=[];
-0274 modelManual.S(6:7,:)=[];
-0275 
-0276 modelManual.rxnGeneMat(20,:)=[];
-0277 modelManual.grRules(20)=[];
-0278 modelManual.rxns(20)=[];
-0279 modelManual.rxnNames(20)=[];
-0280 modelManual.lb(20)=[];
-0281 modelManual.ub(20)=[];
-0282 modelManual.c(20)=[];
-0283 modelManual.rev(20)=[];
-0284 modelManual.S(:,20)=[];
-0285 modelManual.eccodes(20)=[];
-0286 verifyEqual(testCase,modelNew,modelManual)
-0287 end
-0288 
-0289 function getMetsInCompTest(testCase)
-0290 %Load the model in RAVEN format
-0291 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
-0292 load(fullfile(sourceDir,'testing','unit_tests','test_data','ecoli_textbook.mat'), 'model');
-0293 
-0294 evalc('[testOut.I, testOut.metNames]=getMetsInComp(model,''e'');');
-0295 
-0296 testCheck.I=[false;false;false;false;false;false;true;false;true;false;false;false;false;false;true;false;false;false;false;true;false;false;false;false;true;false;false;false;true;true;false;true;false;false;true;false;true;false;true;false;false;true;false;true;false;false;true;false;true;false;false;false;false;false;true;false;true;false;false;false;true;false;true;false;false;false;false;false;false;true;false;false];
-0297 testCheck.metNames={'Acetate';'Acetaldehyde';'2-Oxoglutarate';'CO2';'Ethanol';'Formate';'D-Fructose';'Fumarate';'D-Glucose';'L-Glutamine';'L-Glutamate';'H2O';'H+';'D-Lactate';'L-Malate';'Ammonium';'O2';'Phosphate';'Pyruvate';'Succinate'};
-0298 verifyEqual(testCase,testOut,testCheck)
-0299 end
-0300 
-0301 function getRxnsInCompTest(testCase)
-0302 %Load the model in RAVEN format
-0303 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
-0304 load(fullfile(sourceDir,'testing','unit_tests','test_data','ecoli_textbook.mat'), 'model');
-0305 
-0306 evalc('[testOut.I, testOut.rxnNames]=getRxnsInComp(model,''e'');');
-0307 
-0308 testCheck.I=[20;21;22;23;24;25;26;27;28;29;30;31;32;33;34;35;36;37;38;39];
-0309 testCheck.rxnNames={'Acetate exchange';'Acetaldehyde exchange';'2-Oxoglutarate exchange';'CO2 exchange';'Ethanol exchange';'Formate exchange';'D-Fructose exchange';'Fumarate exchange';'D-Glucose exchange';'L-Glutamine exchange';'L-Glutamate exchange';'H+ exchange';'H2O exchange';'D-lactate exchange';'L-Malate exchange';'Ammonia exchange';'O2 exchange';'Phosphate exchange';'Pyruvate exchange';'Succinate exchange'};
-0310 verifyEqual(testCase,testOut,testCheck)
-0311 end
-0312 
-0313 function getAllRxnsFromGenesTest(testCase)
-0314 %Load the model in RAVEN format
-0315 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
-0316 load(fullfile(sourceDir,'testing','unit_tests','test_data','ecoli_textbook.mat'), 'model');
-0317 evalc('testOut=getAllRxnsFromGenes(model,''ACONTa'');');
-0318 
-0319 testCheck={'ACONTa';'ACONTb'};
-0320 verifyEqual(testCase,testOut,testCheck)
-0321 end
-0322 
-0323 function changeRxnsTest(testCase)
-0324 %Load the model in RAVEN format
-0325 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
-0326 load(fullfile(sourceDir,'testing','unit_tests','test_data','ecoli_textbook.mat'), 'model');
-0327 
-0328 evalc('modelNew=changeRxns(model,''ACKr'',''2-Oxoglutarate <=> TEST'',2,''c'',true);');
-0329 
-0330 equations.mets={{'2-Oxoglutarate','TEST'}};
-0331 equations.stoichCoeffs={[-1,1]};
-0332 
-0333 evalc('modelNewStruct=changeRxns(model,''ACKr'',equations,2,''c'',true);');
-0334 
-0335 %Perform the curation manually for comparison
-0336 modelManual=model;
-0337 
-0338 modelManual.mets(end+1)={'m_0001'};
-0339 modelManual.S(end+1,:)=zeros(1,numel(modelManual.rxns));
-0340 modelManual.S(:,3)=0;
-0341 modelManual.S([14,73],3)=[-1,1];
-0342 
-0343 modelManual.metNames(end+1)={'TEST'};
-0344 modelManual.metComps(end+1)=[1];
-0345 modelManual.metFormulas(end+1)={''};
-0346 modelManual.metMiriams(end+1)={[]};
-0347 modelManual.b(end+1)=[0];
-0348 modelManual.rev(3)=[1];
-0349 
-0350 verifyEqual(testCase,modelNew,modelManual)
-0351 verifyEqual(testCase,modelNewStruct,modelManual)
-0352 end
-0353 
-0354 function removeBadRxnsTest(testCase)
-0355 %Load the model in RAVEN format
-0356 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
-0357 load(fullfile(sourceDir,'testing','unit_tests','test_data','ecoli_textbook.mat'), 'model');
-0358 
-0359 [~,exchRxns]=getExchangeRxns(model);
-0360 modelNew=model;
-0361 
-0362 modelNew.lb(exchRxns)=[0];
-0363 modelNew.ub(exchRxns)=[0];
-0364 modelNew.lb(modelNew.lb>0)=0;
-0365 modelNew.S(17,:)=1;
-0366 [~, testOut]=removeBadRxns(modelNew);
-0367 evalc('[~, testOut]=removeBadRxns(modelNew,3,modelNew.metComps==2);');
-0368 
-0369 import matlab.unittest.constraints.AnyCellOf;
-0370 import matlab.unittest.constraints.ContainsSubstring;
-0371 verifyThat(testCase,AnyCellOf({'SUCDi','FRD7'}),ContainsSubstring(testOut{:}),'test')
-0372 %Either SUCDi or FRD7 should be given as output
-0373 end
-0374 
-0375 function changeGrRulesTest(testCase)
-0376 sourceDir = fileparts(which(mfilename));
-0377 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
-0378 
-0379 modelNew=changeGrRules(model,{'ACKr','ACONTa'},{'b2296 and b1849';'b1849'},true);
-0380 modelNew=changeGrRules(modelNew,'ACONTa','b1849',false);
-0381 
-0382 %Perform the curation manually for comparison
-0383 modelManual=model;
-0384 modelManual.grRules(3:4)={'b2296 and b1849';'b1849 or b1849'};
-0385 modelManual.rxnGeneMat(3:4,:)=0;
-0386 modelManual.rxnGeneMat(3,[57,76])=1;
-0387 modelManual.rxnGeneMat(4,57)=1;
-0388 
-0389 verifyEqual(testCase,modelNew,modelManual)
-0390 end
-0391 
-0392 function copyToCompsTest(testCase)
-0393 sourceDir = fileparts(which(mfilename));
-0394 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
-0395 
-0396 modelNew=copyToComps(model,{'p','e'},'ACKr');
-0397 
-0398 %Perform the curation manually for comparison
-0399 modelManual=model;
-0400 
-0401 modelManual.rxns(end+1:end+2)={'ACKr_p';'ACKr_e'};
-0402 modelManual.mets(end+1:end+7)={'ac_c_p';'actp_c_p';'adp_c_p';'atp_c_p';'actp_c_e';'adp_c_e';'atp_c_e'};
-0403 modelManual.S(end+1:end+7,:)=zeros(7,numel(modelManual.rxns)-2);
-0404 modelManual.S(:,end+1:end+2)=zeros(numel(modelManual.mets),2);
-0405 
-0406 modelManual.S([73,74,75,76],end-1)=[1,-1,-1,1];
-0407 modelManual.S([7,77,78,79],end)=[1,-1,-1,1];
-0408 
-0409 modelManual.lb(end+1:end+2)=[-1000;-1000];
-0410 modelManual.ub(end+1:end+2)=[1000;1000];
-0411 modelManual.rev(end+1:end+2)=[1;1];
-0412 modelManual.c(end+1:end+2)=[0;0];
-0413 modelManual.rxnNames(end+1:end+2)={'acetate kinase';'acetate kinase'};
-0414 modelManual.grRules(end+1:end+2)={'b1849 or b2296 or b3115';'b1849 or b2296 or b3115'};
-0415 modelManual.eccodes(end+1:end+2)={'2.7.2.1';'2.7.2.1'};
-0416 
-0417 modelManual.rxnGeneMat(end+1:end+2,:)=zeros(2,numel(modelManual.genes));
-0418 modelManual.rxnGeneMat(end-1:end,[57,76,97])=1;
-0419 
-0420 modelManual.metNames(end+1:end+7)={'Acetate';'Acetyl phosphate';'ADP';'ATP';'Acetyl phosphate';'ADP';'ATP'};
-0421 modelManual.metComps(end+1:end+7)=[3;3;3;3;2;2;2];
-0422 modelManual.metFormulas(end+1:end+7)={'C2H3O2';'C2H3O5P';'C10H12N5O10P2';'C10H12N5O13P3';'C2H3O5P';'C10H12N5O10P2';'C10H12N5O13P3'};
-0423 modelManual.metMiriams(end+1:end+7)=modelManual.metMiriams([6,12,13,17,12,13,17]);
-0424 modelManual.b(end+1:end+7)=[0];
-0425 
-0426 modelManual.comps(end+1)={'p'};
-0427 modelManual.compNames(end+1)={'p'};
-0428 
-0429 verifyEqual(testCase,modelNew,modelManual)
-0430 end
-0431 
-0432 function setExchangeBoundsTest(testCase)
-0433 sourceDir = fileparts(which(mfilename));
-0434 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
-0435 
-0436 modelNew=setExchangeBounds(model,{'ac_e';'akg_e'},-500,500);
-0437 
-0438 %Perform the curation manually for comparison
-0439 modelManual=model;
-0440 
-0441 exchRxns=[21;23;24;25;26;27;28;29;30;31;32;33;34;35;36;37;38;39];
-0442 modelManual.lb(exchRxns)=0;
-0443 modelManual.lb([20,22])=-500;
-0444 modelManual.ub([20,22])=500;
-0445 
-0446 verifyEqual(testCase,modelNew,modelManual)
-0447 end
-0448 
-0449 function addRxnsGenesMetsTest(testCase)
-0450 sourceDir = fileparts(which(mfilename));
-0451 load(fullfile(sourceDir,'test_data','ecoli_textbook.mat'), 'model');
-0452 
-0453 sbmlFile=fullfile(sourceDir,'..','..','tutorial','empty.xml');
-0454 evalc('modelEmpty=importModel(sbmlFile,[],true)'); % Repress warnings
-0455 
-0456 evalc('modelNew=addRxnsGenesMets(model,modelEmpty,''r1'',true);');
-0457 
-0458 %Perform the curation manually for comparison
-0459 modelManual=model;
-0460 
-0461 modelManual.rxns(end+1)={'r1'};
-0462 modelManual.mets(end+1:end+3)={'m1';'m2';'m3'};
-0463 modelManual.S(end+1:end+3,:)=zeros(3,numel(modelManual.rxns)-1);
-0464 modelManual.S(:,end+1)=zeros(numel(modelManual.mets),1);
-0465 modelManual.S([42,73,74,75],end)=[-1,-1,1,1];
-0466 
-0467 modelManual.lb(end+1)=[0];
-0468 modelManual.ub(end+1)=[1000];
-0469 modelManual.rev(end+1)=[0];
-0470 modelManual.c(end+1)=[0];
-0471 modelManual.rxnNames(end+1)={'Breakdown of sucrose (invertase)'};
-0472 modelManual.grRules(end+1)={'g1'};
-0473 modelManual.eccodes(end+1)={''};
-0474 modelManual.rxnNotes(1:numel(modelManual.rxns),1)={''};
-0475 modelManual.rxnNotes(end)={'Added via addRxnsGenesMets()'};
-0476 modelManual.rxnConfidenceScores(1:numel(modelManual.rxns),1)=NaN;
-0477 modelManual.rxnConfidenceScores(end)=[0];
-0478 
-0479 modelManual.genes(end+1)={'g1'};
-0480 modelManual.geneShortNames(end+1)={''};
-0481 
-0482 modelManual.rxnGeneMat(end+1,:)=zeros(1,numel(modelManual.genes)-1);
-0483 modelManual.rxnGeneMat(:,end+1)=zeros(numel(modelManual.rxns),1);
-0484 modelManual.rxnGeneMat(end,end)=1;
-0485 
-0486 modelManual.metNames(end+1:end+3)={'sucrose';'glucose';'fructose'};
-0487 modelManual.metComps(end+1:end+3)=[2;2;2];
-0488 modelManual.metFormulas(end+1:end+3)={'C12H22O11';'C6H12O6';'C6H12O6'};
-0489 modelManual.metMiriams(end+1:end+3)={[];[];[]};
-0490 modelManual.b(end+1:end+3)=[0];
-0491 
-0492 verifyEqual(testCase,modelNew,modelManual)
-0493 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/testing/unit_tests/modelSortingTests.html b/doc/testing/unit_tests/modelSortingTests.html deleted file mode 100644 index f75a2fb7f..000000000 --- a/doc/testing/unit_tests/modelSortingTests.html +++ /dev/null @@ -1,118 +0,0 @@ - - - - Description of modelSortingTests - - - - - - - - - -
Home > testing > unit_tests > modelSortingTests.m
- - - -

modelSortingTests -

- -

PURPOSE ^

-
run this test case with the command
- -

SYNOPSIS ^

-
function tests = modelSortingTests
- -

DESCRIPTION ^

-
run this test case with the command
-results = runtests('modelSortingTests.m')
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 %run this test case with the command
-0002 %results = runtests('modelSortingTests.m')
-0003 function tests = modelSortingTests
-0004 tests = functiontests(localfunctions);
-0005 end
-0006 
-0007 function sortIdentifirs_and_permuteModelTest(testCase)
-0008 
-0009 %Load the expected (i.e. sorted) model
-0010 sourceDir = fileparts(which(mfilename));
-0011 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
-0012 expModel = model;
-0013 
-0014 %Create the actual model that will be permuted and sorted
-0015 actModel = expModel;
-0016 
-0017 %Randomly permutate model, do not use RAVEN functions
-0018 rndIdx = randperm(numel(actModel.rxns));
-0019 fieldsToChange = {'rxns','lb','ub','rev','c','rxnNames','grRules','eccodes'};
-0020 for i=1:numel(fieldsToChange)
-0021     actModel.(fieldsToChange{i}) = actModel.(fieldsToChange{i})(rndIdx);
-0022 end
-0023 actModel.S          = actModel.S(:,rndIdx);
-0024 actModel.rxnGeneMat = actModel.rxnGeneMat(rndIdx,:);
-0025 
-0026 rndIdx = randperm(numel(actModel.mets));
-0027 fieldsToChange = {'mets','metNames','metComps','metFormulas','metMiriams'};
-0028 for i=1:numel(fieldsToChange)
-0029     actModel.(fieldsToChange{i}) = actModel.(fieldsToChange{i})(rndIdx);
-0030 end
-0031 actModel.S     = actModel.S(rndIdx,:);
-0032 
-0033 rndIdx = randperm(numel(actModel.genes));
-0034 fieldsToChange = {'genes','geneShortNames'};
-0035 for i=1:numel(fieldsToChange)
-0036     actModel.(fieldsToChange{i}) = actModel.(fieldsToChange{i})(rndIdx);
-0037 end
-0038 actModel.rxnGeneMat = actModel.rxnGeneMat(:,rndIdx);
-0039 
-0040 rndIdx = randperm(numel(actModel.comps));
-0041 fieldsToChange = {'comps','compNames'};
-0042 for i=1:numel(fieldsToChange)
-0043     actModel.(fieldsToChange{i}) = actModel.(fieldsToChange{i})(rndIdx);
-0044 end
-0045 [~,J]=sort(rndIdx);
-0046 [toreplace, bywhat] = ismember(actModel.metComps,1:length(J));
-0047 actModel.metComps(toreplace) = J(bywhat(toreplace));
-0048 
-0049 %Sort randomly permutated model
-0050 actModel = sortIdentifiers(actModel);
-0051 
-0052 %Check that the actual model is the same as the expected model
-0053 verifyEqual(testCase,actModel,expModel)
-0054 end
-0055 
-0056 function expandModel_and_contractModelTest(testCase)
-0057 %Load the expected model
-0058 sourceDir = fileparts(which(mfilename));
-0059 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
-0060 
-0061 % Note that this does not work any model, as grRules might not be properly
-0062 % sorted (but should still be valid)
-0063 evalc('modelNew = expandModel(model);'); % Suppress warnings about complex grRules
-0064 modelNew = contractModel(modelNew);
-0065 
-0066 verifyEqual(testCase,model,modelNew)
-0067 end
-0068
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/testing/unit_tests/solverTests.html b/doc/testing/unit_tests/solverTests.html deleted file mode 100644 index ef3aee14f..000000000 --- a/doc/testing/unit_tests/solverTests.html +++ /dev/null @@ -1,192 +0,0 @@ - - - - Description of solverTests - - - - - - - - - -
Home > testing > unit_tests > solverTests.m
- - - -

solverTests -

- -

PURPOSE ^

-
run this test case with the command
- -

SYNOPSIS ^

-
function tests = solverTests
- -

DESCRIPTION ^

-
run this test case with the command
-results = runtests('solverTests.m')
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 %run this test case with the command
-0002 %results = runtests('solverTests.m')
-0003 function tests = solverTests
-0004 tests = functiontests(localfunctions);
-0005 end
-0006 
-0007 function testGlpk(testCase)
-0008 sourceDir = fileparts(which(mfilename));
-0009 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
-0010 try
-0011     oldSolver=getpref('RAVEN','solver');
-0012 catch
-0013 end
-0014 setRavenSolver('glpk');
-0015 
-0016 try
-0017     evalc('sol=solveLP(model,0);');
-0018 catch
-0019     try
-0020         setRavenSolver(oldSolver);
-0021     catch
-0022         rmpref('RAVEN','solver');
-0023     end
-0024     error('Solver not working')
-0025 end
-0026 try
-0027     setRavenSolver(oldSolver);
-0028 catch
-0029     rmpref('RAVEN','solver');
-0030 end
-0031 
-0032 load([sourceDir,'/test_data/solverTestOutput.mat'], 'solOut');
-0033 %Check that the actual model is the same as the expected model
-0034 verifyEqual(testCase,sol,solOut,'AbsTol',0.1) %Quite generous tolerance, as shadow price calculations fluctuate quite a bit between solvers
-0035 end
-0036 
-0037 function testGurobi(testCase)
-0038 sourceDir = fileparts(which(mfilename));
-0039 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
-0040 try
-0041     oldSolver=getpref('RAVEN','solver');
-0042 catch
-0043 end
-0044 
-0045 setRavenSolver('gurobi');
-0046 
-0047 if exist('gurobi','file')~=3
-0048     error('Gurobi not installed or cannot be found in MATLAB path.')
-0049 else
-0050     try
-0051         % Try all three types of flux minimization
-0052         evalc('sol=solveLP(model,3);');
-0053         evalc('sol=solveLP(model,1);');
-0054         evalc('sol=solveLP(model,0);');
-0055     catch ME
-0056         try
-0057             setRavenSolver(oldSolver);
-0058         catch
-0059             rmpref('RAVEN','solver');
-0060         end
-0061         error(ME.message)
-0062     end
-0063 end
-0064 try
-0065     setRavenSolver(oldSolver);
-0066 catch
-0067     rmpref('RAVEN','solver');
-0068 end
-0069 
-0070 load([sourceDir,'/test_data/solverTestOutput.mat'], 'solOut');
-0071 %Check that the actual model is the same as the expected model
-0072 verifyEqual(testCase,sol,solOut,'AbsTol',0.1)
-0073 end
-0074 
-0075 function testSCIP(testCase)
-0076 if exist('scip','file')~=3
-0077     error('SCIP MEX binary not installed or not functional.')
-0078 end
-0079 sourceDir = fileparts(which(mfilename));
-0080 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
-0081 try
-0082     oldSolver=getpref('RAVEN','solver');
-0083 catch
-0084 end
-0085 setRavenSolver('scip');
-0086 try
-0087     evalc('sol=solveLP(model,0);');
-0088 catch
-0089     try
-0090         setRavenSolver(oldSolver);
-0091     catch
-0092         rmpref('RAVEN','solver');
-0093     end
-0094     error('Solver not working')
-0095 end
-0096 try
-0097     setRavenSolver(oldSolver);
-0098 catch
-0099     rmpref('RAVEN','solver');
-0100 end
-0101 
-0102 load([sourceDir,'/test_data/solverTestOutput.mat'], 'solOutSCIP');
-0103 %Check that the actual model is the same as the expected model
-0104 verifyEqual(testCase,sol,solOutSCIP,'AbsTol',0.1)
-0105 end
-0106 
-0107 function testCobra(testCase)
-0108 if exist('initCobraToolbox.m','file')~=2
-0109     error('COBRA Toolbox not installed or cannot be found in MATLAB path.')
-0110 end
-0111 sourceDir = fileparts(which(mfilename));
-0112 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
-0113 try
-0114     oldSolver=getpref('RAVEN','solver');
-0115 catch
-0116 end
-0117 global CBT_LP_SOLVER
-0118 global CBT_MILP_SOLVER
-0119 CBT_LP_SOLVER = 'glpk';
-0120 CBT_MILP_SOLVER = 'glpk';
-0121 setRavenSolver('cobra');
-0122 
-0123 try
-0124     evalc('sol=solveLP(model,0);');
-0125 catch
-0126     try
-0127         setRavenSolver(oldSolver);
-0128     catch
-0129         rmpref('RAVEN','solver');
-0130     end
-0131     error('Solver not working')
-0132 end
-0133 try
-0134     setRavenSolver(oldSolver);
-0135 catch
-0136     rmpref('RAVEN','solver');
-0137 end
-0138 
-0139 load([sourceDir,'/test_data/solverTestOutput.mat'], 'solOut');
-0140 %Check that the actual model is the same as the expected model
-0141 verifyEqual(testCase,sol,solOut,'AbsTol',0.1)
-0142 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/testing/unit_tests/tinitTests.html b/doc/testing/unit_tests/tinitTests.html deleted file mode 100644 index f699d0e0d..000000000 --- a/doc/testing/unit_tests/tinitTests.html +++ /dev/null @@ -1,665 +0,0 @@ - - - - Description of tinitTests - - - - - - - - - -
Home > testing > unit_tests > tinitTests.m
- - - -

tinitTests -

- -

PURPOSE ^

-
run this test case with the command
- -

SYNOPSIS ^

-
function tests = tinitTests
- -

DESCRIPTION ^

-
run this test case with the command
-results = runtests('tinitTests.m')
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - -

SUBFUNCTIONS ^

- - -

SOURCE CODE ^

-
0001 %run this test case with the command
-0002 %results = runtests('tinitTests.m')
-0003 function tests = tinitTests
-0004 tests = functiontests(localfunctions);
-0005 solverExist = [exist('gurobi','file'), exist('scip.mexw64','file')] ==3;
-0006 if solverExist(1)
-0007     try
-0008         gurobi_read('solverTests.m'); % Random function call
-0009     catch ME
-0010         if ~startsWith(ME.message,'Gurobi error 10012') % Expected error code, others may indicate problems with license
-0011             solverExist(1) = false;
-0012         end
-0013     end
-0014 end
-0015 if all(~solverExist)
-0016     disp('No suitable solver (gurobi or scip) was found, ftINIT tests skipped.')
-0017     skipTests = contains({tests.Name},'ftinit','IgnoreCase',true);
-0018     tests(skipTests) = [];
-0019 end
-0020 end
-0021 
-0022 function testparsexpTask1List(testCase)
-0023 sourceDir = fileparts(which(mfilename));
-0024 taskStruct = parseTaskList(strcat(sourceDir, '/test_data/test_tasks.txt'));
-0025 taskStructExcel = parseTaskList(strcat(sourceDir, '/test_data/test_tasks.xls'));
-0026 %check that all fields in the first line are what we expect
-0027 
-0028 expTask1.id='ER';
-0029 expTask1.description='Aerobic rephosphorylation of ATP from glucose';
-0030 expTask1.shouldFail=true;
-0031 expTask1.printFluxes=true;
-0032 expTask1.comments='Messed up reaction';
-0033 expTask1.inputs={'O2[s]';'glucose[s]'};
-0034 expTask1.LBin=[23.6;23.6];
-0035 expTask1.UBin=[23.8;23.8];
-0036 expTask1.outputs={'H2O[s]';'CO2[s]'};
-0037 expTask1.LBout=[26.1;26.1];
-0038 expTask1.UBout=[26.2;26.2];
-0039 expTask1.equations={'ATP[c] + H2O[c] => ADP[c] + Pi[c] + H+[c]'};
-0040 expTask1.LBequ=30.2;
-0041 expTask1.UBequ=30.6;
-0042 expTask1.changed={'ATP[a] + H2O[a] => ADP[a] + Pi[a] + H+[a]'};
-0043 expTask1.LBrxn=56.2;
-0044 %check that the check works as expected
-0045 verifyNotEqual(testCase,taskStruct(1),expTask1)
-0046 expTask1.UBrxn=60;%now add the last
-0047 
-0048 
-0049 verifyEqual(testCase,taskStruct(1),expTask1)
-0050 verifyEqual(testCase,taskStructExcel(1),expTask1)
-0051 
-0052 %check that we have 2 tasks in total
-0053 verifyEqual(testCase,length(taskStruct),2)
-0054 verifyEqual(testCase,length(taskStructExcel),2)
-0055 
-0056 expTask2.id='BS';
-0057 expTask2.description='ATP de novo synthesis';
-0058 expTask2.shouldFail=false;
-0059 expTask2.printFluxes=false;
-0060 expTask2.comments='';
-0061 expTask2.inputs={'O2[s]';'glucose[s]';'NH3[s]';'Pi[s]'};
-0062 expTask2.LBin=[0;0;0;0];
-0063 expTask2.UBin=[1000;1000;1000;1000];
-0064 expTask2.outputs={'H2O[s]';'CO2[s]';'ATP[c]'};
-0065 expTask2.LBout=[0;0;1];
-0066 expTask2.UBout=[1.1;1.1;1.3];
-0067 expTask2.equations={'ATP[c] + H2O[c] <=> ADP[c] + Pi[c] + H+[c]'};
-0068 expTask2.LBequ=-1000;
-0069 expTask2.UBequ=1000;
-0070 expTask2.changed={};
-0071 expTask2.LBrxn=[];
-0072 expTask2.UBrxn=[];
-0073 
-0074 verifyEqual(testCase,taskStruct(2),expTask2)
-0075 verifyEqual(testCase,taskStructExcel(2),expTask2)
-0076 
-0077 %and, check that the two formats produce the same
-0078 verifyEqual(testCase,taskStruct,taskStructExcel)
-0079 end
-0080 
-0081 
-0082 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-0083 % testModel
-0084 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-0085 
-0086 function testModel = getTstModel()
-0087 testModel = struct();
-0088 testModel.id = 'testModel';
-0089 testModel.rxns = {};
-0090 testModel.S=[];
-0091 testModel.rev=[];
-0092 testModel.mets = {'as';'ac';'bc';'cc';'dc';'ec';'es';'fc'};
-0093 testModel.metNames = {'a';'a';'b';'c';'d';'e';'e';'f'};
-0094 testModel.comps = {'s';'c'};
-0095 testModel.compNames = testModel.comps;
-0096 testModel.metComps = [1;2;2;2;2;2;1;2];
-0097 testModel.genes = {'G1';'G2';'G3';'G4';'G5';'G6';'G7';'G8';'G9';'G10'};
-0098 testModel.grRules = {};
-0099 testModel.rxnGeneMat = [];
-0100 
-0101 rxnsToAdd = struct();
-0102 rxnsToAdd.rxns = {'R1';'R2';'R3';'R4';'R5';'R6';'R7';'R8';'R9';'R10'};
-0103 rxnsToAdd.equations = {'=> a[s]';...
-0104     'a[s] <=> a[c]';...
-0105     'a[c] <=> b[c] + c[c]';...
-0106     'a[c] <=> 2 d[c]';...
-0107     'b[c] + c[c] => e[c]';...
-0108     '2 d[c] => e[c]';...
-0109     'e[c] => e[s]';...
-0110     'e[s] =>';...
-0111     'a[c] <=> f[c]';...
-0112     'f[c] <=> e[c]'};
-0113 rxnsToAdd.grRules = {'';'';'G3';'G4';'G5';'G6';'G7';'';'G9';'G10'};
-0114 testModel = addRxns(testModel,rxnsToAdd, 3);
-0115 testModel.c = [0;0;0;0;0;0;0;1;0;0];%optimize for output flux, if this is used, not sure
-0116 testModel.ub = repmat(1000,10,1);
-0117 testModel.lb = [0;-1000;-1000;-1000;0;0;0;0;-1000;-1000];
-0118 testModel.rxnNames = testModel.rxns;
-0119 testModel.b = repmat(0,8,1);
-0120 end
-0121 
-0122 function testModelRxnScores = getTstModelRxnScores()
-0123 testModelRxnScores = [-2;-2;-1;7;0.5;0.5;-1;-2;-3;3.5];
-0124 end
-0125 
-0126 function testModelTasks = getTstModelTasks()
-0127 testModelTasks = struct();
-0128 testModelTasks.id = 'Gen e[s] from a[s]';
-0129 testModelTasks.description = 'Gen e[s] from a[s]';
-0130 testModelTasks.shouldFail = false;
-0131 testModelTasks.printFluxes = false;
-0132 testModelTasks.comments = '';
-0133 testModelTasks.inputs = {'a[s]'};
-0134 testModelTasks.LBin = 0;
-0135 testModelTasks.UBin = inf;
-0136 testModelTasks.outputs = {'e[s]'};
-0137 testModelTasks.LBout = 1;
-0138 testModelTasks.UBout = 1;
-0139 testModelTasks.equations = {};
-0140 testModelTasks.LBequ = [];
-0141 testModelTasks.UBequ = [];
-0142 testModelTasks.changed = {};
-0143 testModelTasks.LBrxn = {};
-0144 testModelTasks.UBrxn = {};
-0145 end
-0146 
-0147 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-0148 % testModel2 - not used directly for now, but indirectly
-0149 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-0150 
-0151 function testModel2 = getTstModel2()
-0152 testModel2 = struct();
-0153 testModel2.id = 'testModel2';
-0154 testModel2.rxns = {};
-0155 testModel2.S=[];
-0156 testModel2.rev=[];
-0157 testModel2.mets = {'a';'b'};
-0158 testModel2.metNames = {'a';'b'};
-0159 testModel2.comps = {'s'};
-0160 testModel2.compNames = testModel2.comps;
-0161 testModel2.metComps = [1;1];
-0162 testModel2.genes = {'G1';'G2';'G3';'G4'};
-0163 testModel2.grRules = {};
-0164 testModel2.rxnGeneMat = [];
-0165 
-0166 rxnsToAdd = struct();
-0167 rxnsToAdd.rxns = {'R1';'R2';'R3';'R4'};
-0168 rxnsToAdd.equations = {'a[s] <=>';...
-0169     'a[s] => b[s]';...
-0170     'a[s] <=> b[s]';...
-0171     'b[s] =>'};
-0172 rxnsToAdd.grRules = testModel2.genes;
-0173 testModel2 = addRxns(testModel2,rxnsToAdd,3,'',true,true);
-0174 testModel2.c = [0;0;0;1];%optimize for output flux, if this is used, not sure
-0175 testModel2.ub = repmat(1000,4,1);
-0176 testModel2.lb = [-1000;0;-1000;0];
-0177 testModel2.rxnNames = testModel2.rxns;
-0178 testModel2.b = zeros(2,1);
-0179 end
-0180 
-0181 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-0182 % testModel4
-0183 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-0184 
-0185 function testModel4 = getTstModel4()
-0186 testModel2 = getTstModel2();
-0187 testModel4 = testModel2;
-0188 
-0189 rxnsToAdd = struct();
-0190 rxnsToAdd.rxns = {'R5';'R6';'R7';'R8';'R9';'R10';'R11'};
-0191 rxnsToAdd.equations = {'5 a[s] <=> 5 d[s]';...
-0192     'e[s] <=> d[s]';
-0193     'f[s] + g[s] <=> e[s]';
-0194     'b[s] <=> f[s]';
-0195     'h[s] <=> g[s]';
-0196     'h[s] =>';
-0197     'e[s] => g[s]'};
-0198 rxnsToAdd.grRules = {'G5';'G6';'G7';'G8';'G9';'G10';'G11'};
-0199 [~,testModel4] = evalc("addRxns(testModel4,rxnsToAdd, 3, [], true, true);");
-0200 end
-0201 
-0202 function testModel4RxnScores = getTstModel4RxnScores()
-0203 testModel4RxnScores = [-1;-1;2;-1;0.5;-2;1;1.3;-0.5;-0.4;8];
-0204 end
-0205 
-0206 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-0207 % testModel5
-0208 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-0209 
-0210 function testModel5 = getTstModel5()
-0211 testModel = getTstModel();
-0212 
-0213 rxnsToAdd = struct();
-0214 rxnsToAdd.rxns = {'R11';'R12';'R13';'R14'};
-0215 rxnsToAdd.equations = {'a[c] <=> g[c]';...
-0216     'a[c] <=> g[c]';...
-0217     'g[c] <=> e[c]';...
-0218     'g[c] <=> e[c]'};
-0219 rxnsToAdd.grRules = {'G11';'G12';'G13';'G14'};
-0220 [~,testModel5] = evalc("addRxns(testModel,rxnsToAdd, 3, [], true, true);");
-0221 end
-0222 
-0223 function testModel5RxnScores = getTstModel5RxnScores()
-0224 testModel5RxnScores = [getTstModelRxnScores();-1;-1.5;-1;-1.5];
-0225 end
-0226 
-0227 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-0228 %T0001: testModel without tasks
-0229 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-0230 function testftINIT_T0001(testCase)
-0231 solverExist = [exist('gurobi','file'), exist('scip.mexw64','file')] == 3;
-0232 currSolver = getpref('RAVEN','solver');
-0233 if solverExist(1)
-0234     setRavenSolver('gurobi');
-0235 elseif solverExist(2)
-0236     setRavenSolver('scip');
-0237 else
-0238     error('No compatible solvers found');
-0239 end
-0240 %    detectedMets = {};
-0241 testParams = struct();
-0242 
-0243 %    params.TimeLimit = 10;
-0244 
-0245 testModel = getTstModel();
-0246 [~, prepDataTest1] = evalc('prepINITModel(testModel, {}, {}, false, {}, ''s'');');
-0247 %check some things in the prepData
-0248 %1. We expect 3 rxns in origRxnsToZero:
-0249 verifyTrue(testCase, all(strcmp(prepDataTest1.refModel.rxns(prepDataTest1.toIgnoreExch) , {'R1';'R8'})))
-0250 %note that R7 should not be there, since it has a GPR.
-0251 
-0252 arrayData1.genes = testModel.genes;
-0253 arrayData1.tissues = {'a'};
-0254 arrayData1.levels = getExprForRxnScore(getTstModelRxnScores());
-0255 arrayData1.threshold = 1;
-0256 
-0257 [~,tst1ResModel1] = evalc('ftINIT(prepDataTest1,arrayData1.tissues{1},[],[],arrayData1,[],getINITSteps(),true,true,testParams,false);');
-0258 
-0259 %We expect R1 and R8 to be added since they have no GPRs and are exch rxns. The transport rxn R2 without GPR will however be removed,
-0260 %since we in the standard setting run the third step with [1;0;0;0;1;0;0], meaning that such reactions will be removed
-0261 %R7 however will not be added since it has a GPR
-0262 verifyTrue(testCase, all(strcmp(tst1ResModel1.rxns,{'R1';'R4';'R6';'R8';'R9';'R10'})))
-0263 
-0264 %also test spontaneous
-0265 [~, prepDataTest1] = evalc('prepINITModel(testModel, {}, {''R7'';''R10''}, false, {}, ''s'');');
-0266 verifyTrue(testCase, all(strcmp(prepDataTest1.refModel.rxns(prepDataTest1.toIgnoreExch | prepDataTest1.toIgnoreSpont), {'R1';'R7';'R8';'R10'})))
-0267 arrayData1.genes = testModel.genes;
-0268 arrayData1.tissues = {'a'};
-0269 arrayData1.levels = getExprForRxnScore(getTstModelRxnScores());
-0270 arrayData1.threshold = 1;
-0271 [~,tst1ResModel1] = evalc('ftINIT(prepDataTest1,arrayData1.tissues{1},[],[],arrayData1,[],getINITSteps(),true,true,testParams,false);');
-0272 %the model should now change to include the "correct" path (including 'R2') and
-0273 %skip R9/R10:
-0274 verifyTrue(testCase, all(strcmp(tst1ResModel1.rxns,{'R1';'R2';'R4';'R6';'R7';'R8'})), 1)
-0275 setRavenSolver(currSolver);
-0276 end
-0277 
-0278 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-0279 %T0002: Create a task that wants to generate e[s] from a[s] for testModel
-0280 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-0281 function testftINIT_T0002(testCase)
-0282 solverExist = [exist('gurobi','file'), exist('scip.mexw64','file')] ==3;
-0283 currSolver = getpref('RAVEN','solver');
-0284 if solverExist(1)
-0285     setRavenSolver('gurobi');
-0286 elseif solverExist(2)
-0287     setRavenSolver('scip');
-0288 else
-0289     error('No compatible solvers found');
-0290 end
-0291 testModel = getTstModel();
-0292 testModelTasks = getTstModelTasks();
-0293 testRxnScores = getTstModelRxnScores();
-0294 testParams = struct();
-0295 [~, prepDataTest1] = evalc('prepINITModel(testModel, testModelTasks, {}, false, {}, ''s'');');
-0296 %We now expect to R2 and R7 to be essential. Note that R1 and R8 are not essential,
-0297 %the exchange rxns are not used when checking tasks.
-0298 %This is a bit complicated to check, because the essential rxns are expressed
-0299 %as rxn ids of the linearly merged model. We expect those to be called R1 and R7:
-0300 verifyTrue(testCase, all(strcmp(prepDataTest1.essentialRxns,{'R1';'R7'})))
-0301 
-0302 arrayData1.genes = testModel.genes;
-0303 arrayData1.tissues = {'a'};
-0304 arrayData1.levels = getExprForRxnScore(testRxnScores);
-0305 arrayData1.threshold = 1;
-0306 [~,tst1ResModel1] = evalc('ftINIT(prepDataTest1,arrayData1.tissues{1},[],[],arrayData1,[],getINITSteps(),true,true,testParams,false);');
-0307 %Since both R2 and R7 are now essential, we expect all rxns to be on except R3 and
-0308 %R5 (which have a negative total score and are not needed for the task)
-0309 verifyTrue(testCase, all(strcmp(tst1ResModel1.rxns,{'R1';'R2';'R4';'R6';'R7';'R8';'R9';'R10'})))
-0310 setRavenSolver(currSolver);
-0311 end
-0312 
-0313 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-0314 %T0003: The second step - gapfilling
-0315 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-0316 function testftINIT_T0003(testCase)
-0317 %First generate a model with gaps. We can use testModel. First we add
-0318 %boundary mets. Then we remove the exchange reactions
-0319 %(which is required for filling gaps) and create a gap by removing the R7 reaction.
-0320 testModel = getTstModel();
-0321 testModelTasks = getTstModelTasks();
-0322 testRxnScores = getTstModelRxnScores();
-0323 
-0324 mTempRef = closeModel(testModel);
-0325 mTempRef = removeReactions(mTempRef, {'R1';'R8'});
-0326 mTemp = removeReactions(mTempRef, {'R7'});
-0327 mTemp.id = 'tmp';
-0328 tmpRxnScores = testRxnScores([2;3;4;5;6;7;9;10]);
-0329 %now check that R7 is added back
-0330 [~,outModel,addedRxnMat] = evalc('ftINITFillGapsForAllTasks(mTemp,mTempRef,[],false,min(tmpRxnScores,-0.1),testModelTasks);');
-0331 verifyTrue(testCase, all(strcmp(mTempRef.rxns(addedRxnMat),'R7')))%ok
-0332 end
-0333 
-0334 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-0335 %T0004: MergeLinear and groupRxnScores
-0336 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-0337 function testftINIT_T0004(testCase)
-0338 %first testModel
-0339 testModel = getTstModel();
-0340 testRxnScores = getTstModelRxnScores();
-0341 [reducedModel,origRxnIds,groupIds,reversedRxns]=mergeLinear(testModel, {});
-0342 %We expect mergeLinear to merge {R1,R2}, {R3,R5}, {R4,R6}, {R7,R8}, {R9,R10}
-0343 verifyTrue(testCase, all(groupIds == [1;1;2;3;2;3;4;4;5;5]))
-0344 %we expect R1, R3, R4, R7 to be irreversible, R9 to be reversible
-0345 verifyTrue(testCase, all(reducedModel.rev == [0;0;0;0;1]))
-0346 verifyTrue(testCase, all(reducedModel.lb == [0;0;0;0;-1000]))
-0347 
-0348 newRxnScores=groupRxnScores(reducedModel, testRxnScores, origRxnIds, groupIds, ismember(origRxnIds, {'R1';'R2';'R8'}));
-0349 verifyTrue(testCase, all(newRxnScores == [0;-0.5;7.5;-1;0.5]))
-0350 
-0351 %then testModel4
-0352 testModel4 = getTstModel4();
-0353 [reducedModel,origRxnIds,groupIds,reversedRxns]=mergeLinear(testModel4, {});
-0354 %we expect {R5,R6},{R7,R8}, and{R9,R10} to be merged
-0355 verifyTrue(testCase, all(groupIds == [0;0;0;0;1;1;2;2;3;3;0]))
-0356 %check reversibility
-0357 verifyTrue(testCase, all(reducedModel.rev == [1;0;1;0;1;1;0;0]))
-0358 %check that some reactions have flipped direction when turned to irrev
-0359 verifyTrue(testCase, strcmp(constructEquations(reducedModel, 'R9'),'g[s] => '))
-0360 verifyTrue(testCase, all(find(reversedRxns) == [6;9]))
-0361 end
-0362 
-0363 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-0364 %T0006: reverseRxns
-0365 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-0366 
-0367 function testftINIT_T0006(testCase)
-0368 %R1 = '=> a[s]';...
-0369 %R3 = 'a[c] <=> b[c] + c[c]';...
-0370 testModel = getTstModel();
-0371 
-0372 tmpModel = reverseRxns(testModel, {'R1';'R3'});
-0373 res = constructEquations(tmpModel, {'R1';'R3'});
-0374 expRes = {'a[s] => ';'b[c] + c[c] <=> a[c]'};
-0375 verifyTrue(testCase, all(strcmp(res,expRes)))
-0376 end
-0377 
-0378 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-0379 %T0007: rescaleModelForINIT
-0380 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-0381 function testftINIT_T0007(testCase)
-0382 miniModel = struct();
-0383 miniModel.S = [1,1000;-1,-40];
-0384 miniModel.rxns = {'1';'2'};
-0385 miniModel.mets = {'1';'2'};
-0386 res = rescaleModelForINIT(miniModel,10);
-0387 verifyTrue(testCase, abs(res.S(1,2) - res.S(2,2)*-10) < 10^-6)
-0388 verifyTrue(testCase, abs((abs(res.S(1,2)) + abs(res.S(2,2)))/2) - 1 < 10^-6)
-0389 end
-0390 
-0391 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-0392 %T0008: testModel with metabolomics
-0393 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-0394 function testftINIT_T0008(testCase)
-0395 solverExist = [exist('gurobi','file'), exist('scip.mexw64','file')] ==3;
-0396 currSolver = getpref('RAVEN','solver');
-0397 if solverExist(1)
-0398     setRavenSolver('gurobi');
-0399 elseif solverExist(2)
-0400     setRavenSolver('scip');
-0401 else
-0402     error('No compatible solvers found');
-0403 end
-0404 
-0405 testParams = struct();
-0406 
-0407 testModel = getTstModel();
-0408 [~, prepDataTest1] = evalc('prepINITModel(testModel, {}, {}, false, {}, ''s'');');
-0409 
-0410 arrayData1.genes = testModel.genes;
-0411 arrayData1.tissues = {'a'};
-0412 arrayData1.levels = getExprForRxnScore(getTstModelRxnScores());
-0413 arrayData1.threshold = 1;
-0414 
-0415 [~,tst1ResModel1] = evalc('ftINIT(prepDataTest1,arrayData1.tissues{1},[],[],arrayData1,[],getINITSteps(),true,true,testParams,false);');
-0416 
-0417 %First the same as in T0001 (we keep them here to make the test case understandable):
-0418 %We expect R1 and R8 to be added since they have no GPRs and are exch rxns. The transport rxn R2 without GPR will however be removed,
-0419 %since we in the standard setting run the third step with [1;0;0;0;1;0;0], meaning that such reactions will be removed
-0420 %R7 however will not be added since it has a GPR
-0421 verifyTrue(testCase, all(strcmp(tst1ResModel1.rxns,{'R1';'R4';'R6';'R8';'R9';'R10'})))
-0422 
-0423 %make R7 and R10 spontaneous (also same as in T0001)
-0424 [~, prepDataTest1] = evalc('prepINITModel(testModel, {}, {''R7'';''R10''}, false, {}, ''s'');');
-0425 verifyTrue(testCase, all(strcmp(prepDataTest1.refModel.rxns(prepDataTest1.toIgnoreExch | prepDataTest1.toIgnoreSpont), {'R1';'R7';'R8';'R10'})))
-0426 [~,tst1ResModel1] = evalc('ftINIT(prepDataTest1,arrayData1.tissues{1},[],[],arrayData1,[],getINITSteps(),true,true,testParams,false);');
-0427 %the model should now change to include the "correct" path (including 'R2') and
-0428 %skip R9/R10:
-0429 verifyTrue(testCase, all(strcmp(tst1ResModel1.rxns,{'R1';'R2';'R4';'R6';'R7';'R8'})))
-0430 %now, test to add the metabolite f - this should turn back the favor to R9/R10:
-0431 [~,tst1ResModel1] = evalc('ftINIT(prepDataTest1,arrayData1.tissues{1},[],[],arrayData1,{''f''},getINITSteps(),true,true,testParams,false);');
-0432 %R9 should now be included, the presence of R2 is random
-0433 if length(tst1ResModel1.rxns) == 7
-0434     verifyTrue(testCase, all(strcmp(tst1ResModel1.rxns,{'R1';'R4';'R6';'R7';'R8';'R9';'R10'})))
-0435 else
-0436     verifyTrue(testCase, all(strcmp(tst1ResModel1.rxns,{'R1';'R2';'R4';'R6';'R7';'R8';'R9';'R10'})))
-0437 end
-0438 %now, test to add the metabolite a, e, f - this should give the same result:
-0439 [~,tst1ResModel1] = evalc('ftINIT(prepDataTest1,arrayData1.tissues{1},[],[],arrayData1,{''f'';''a'';''e''},getINITSteps(),true,true,testParams,false);');
-0440 %Should be the same as above (R2 is random)
-0441 if length(tst1ResModel1.rxns) == 7
-0442     verifyTrue(testCase, all(strcmp(tst1ResModel1.rxns,{'R1';'R4';'R6';'R7';'R8';'R9';'R10'})))
-0443 else
-0444     verifyTrue(testCase, all(strcmp(tst1ResModel1.rxns,{'R1';'R2';'R4';'R6';'R7';'R8';'R9';'R10'})))
-0445 end
-0446 
-0447 %now, test to add the metabolite b - this should turn on R2 and R3/R5 and turn off R9:
-0448 [~,tst1ResModel1] = evalc('ftINIT(prepDataTest1,arrayData1.tissues{1},[],[],arrayData1,{''b''},getINITSteps(),true,true,testParams,false);');
-0449 verifyTrue(testCase, all(strcmp(tst1ResModel1.rxns,{'R1';'R2';'R3';'R4';'R5';'R6';'R7';'R8'})))
-0450 
-0451 %now on model 5 to test reactions that are not linearly merged (testModel has only merged rxns)
-0452 testModel5 = getTstModel5();
-0453 arrayData1.genes = testModel5.genes;
-0454 arrayData1.tissues = {'a'};
-0455 arrayData1.levels = getExprForRxnScore(getTstModel5RxnScores());
-0456 arrayData1.threshold = 1;
-0457 
-0458 [~, prepDataTest5] = evalc('prepINITModel(testModel5, {}, {''R7'';''R10''}, false, {}, ''s'');');
-0459 [~,tst1ResModel1] = evalc('ftINIT(prepDataTest5,arrayData1.tissues{1},[],[],arrayData1,{},getINITSteps(),true,true,testParams,false);');
-0460 %We expect the 'true' path, i.e. through R2, not R9/R10 or R11-R14
-0461 verifyTrue(testCase, all(strcmp(tst1ResModel1.rxns,{'R1';'R2';'R4';'R6';'R7';'R8'})), 1)
-0462 
-0463 %now add metabolite g
-0464 %modify the scores a bit
-0465 [~, prepDataTest5] = evalc('prepINITModel(testModel5, {}, {''R10''}, false, {}, ''s'');');
-0466 arrayData1.levels(7) = getExprForRxnScore(-1.1); %modify to avoid randomness
-0467 [~,tst1ResModel1] = evalc('ftINIT(prepDataTest5,arrayData1.tissues{1},[],[],arrayData1,{''g''},getINITSteps(),true,true,testParams,false);');
-0468 %We expect R2 to be replaced with R11 and R13
-0469 verifyTrue(testCase, all(strcmp(tst1ResModel1.rxns,{'R1';'R4';'R6';'R8';'R11';'R13'})), 1)
-0470 setRavenSolver(currSolver);
-0471 end
-0472 
-0473 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-0474 %T0009: getExprFromRxnScore
-0475 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-0476 function testftINIT_T0009(testCase)
-0477 testModel = getTstModel();
-0478 [~, prepDataTest1] = evalc('prepINITModel(testModel, {}, {}, false, {}, ''s'');');
-0479 
-0480 arrayData1.genes = testModel.genes;
-0481 arrayData1.tissues = {'a'};
-0482 arrayData1.levels = getExprForRxnScore(getTstModelRxnScores());
-0483 arrayData1.threshold = 1;
-0484 
-0485 rxnScores = scoreComplexModel(prepDataTest1.refModel,[],arrayData1,arrayData1.tissues{1},[]);
-0486 expRes = getTstModelRxnScores();
-0487 verifyTrue(testCase, all(abs(rxnScores - expRes) < 10^-10)) %ok
-0488 end
-0489 
-0490 function testModelL = getTstModelL()
-0491 testModelL = struct();
-0492 testModelL.id = 'testModel';
-0493 testModelL.rxns = {};
-0494 testModelL.S=[];
-0495 testModelL.rev=[];
-0496 testModelL.metNames = {'e1';'e2';'e3';'e4';'e5';'e6';'e7';'e8';'e9';'e1';'e2';'e3';'e4';'e5';'e6';'e7';'e8';'e9';'x1';'x2';'x3';'x4';'x5';'x6';'x7';'x8';'x9';'x10';'x11'};
-0497 testModelL.comps = {'s';'c'};
-0498 testModelL.compNames = testModelL.comps;
-0499 testModelL.metComps = [1;1;1;1;1;1;1;1;1;2;2;2;2;2;2;2;2;2;2;2;2;2;2;2;2;2;2;2;2];
-0500 testModelL.mets = strcat(testModelL.metNames, testModelL.comps(testModelL.metComps));
-0501 
-0502 testModelL.grRules = {};
-0503 testModelL.rxnGeneMat = [];
-0504 
-0505 testModelL.genes = {'Ge1';'Ge2';'Ge4';'Ge5';'Ge7';'Ge9'; 'Gr1';'Gr2';'Gr3';'Gr5';'Gr6';'Gr7';'Gr8';'Gr9';'Gr10';'Gr11';'Gr12';'Gr14';'Gr15'};
-0506 
-0507 testModelL.ub = [];
-0508 testModelL.lb = [];
-0509 
-0510 rxnsToAdd = struct();
-0511 rxnsToAdd.rxns = {  'S1';'S2';'S3';'S4';'S5';'S6';'S7';'S8';'S9';'E1';'E2';'E2b';'E3';'E4';'E5';'E6';'E7';'E8';'E9';'R1';'R2';'R3';'R4';'R5';'R6';'R7';'R8';'R9';'R10';'R11';'R12';'R13';'R14';'R15'};
-0512 rxnsToAdd.grRules = {'';  '';  '';  '';  '';  '';  '';  '';  ''; 'Ge1';'Ge2';'';'';'Ge4';'Ge5';'';'Ge7';'';'Ge9'; 'Gr1';'Gr2';'Gr3';'';'Gr5';'Gr6';'Gr7';'Gr8';'Gr9';'Gr10';'Gr11';'Gr12';'';'Gr14';'Gr15'};
-0513 rxnsToAdd.equations = {'e1[s] <=>';...
-0514     'e2[s] <=>';...
-0515     'e3[s] <=>';...
-0516     'e4[s] <=>';...
-0517     'e5[s] <=>';...
-0518     'e6[s] <=>';...
-0519     'e7[s] <=>';...
-0520     'e8[s] <=>';...
-0521     'e9[s] <=>';...
-0522     'e1[s] <=> e1[c]';...
-0523     'e2[s] <=> e2[c]';...
-0524     'e2[s] <=> e2[c]';... %b variant
-0525     'e3[s] <=> e3[c]';...
-0526     'e4[s] <=> e4[c]';...
-0527     'e5[s] <=> e5[c]';...
-0528     'e6[s] <=> e6[c]';...
-0529     'e7[s] <=> e7[c]';...
-0530     'e8[s] <=> e8[c]';...
-0531     'e9[s] <=> e9[c]';...
-0532     'e1[c] + e2[c] <=> x1[c]';... %R1
-0533     'e1[c] + e3[c] => x2[c] + x3[c]';... %R2
-0534     'e4[c] + x3[c] => x4[c] + x5[c]';... %R3
-0535     'e5[c] + e6[c] + x4[c] => 2 x2[c] + x6[c]';... %R4
-0536     'x1[c] + x2[c] <=> x7[c] + 2 x8[c]';... %R5
-0537     'x2[c] + x8[c] => x3[c] + x9[c]';... %R6
-0538     'x4[c] <=> x9[c]';... %R7
-0539     'x5[c] <=> x9[c]';... %R8
-0540     'x6[c] <=> x10[c]';... %R9
-0541     'x6[c] <=> x11[c]';... %R10
-0542     'x10[c] + 2 x11[c] => e7[c]';... %R11
-0543     'x9[c] + x10[c] <=> e8[c]';... %R12
-0544     'x7[c] + x8[c] + x9[c] => e9[c]';... %R13
-0545     'x6[c] => x9[c]';... %R14
-0546     'x3[c] => x9[c]'... %R15
-0547     };
-0548 testModelL = addRxns(testModelL,rxnsToAdd, 3);
-0549 testModelL.c = [0;0;0;0;0;0;0;1;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0];%optimize for output flux, if this is used, not sure
-0550 testModelL.rxnNames = testModelL.rxns;
-0551 testModelL.b = repmat(0,length(testModelL.mets),1);
-0552 end
-0553 
-0554 function testModelLGeneScores = getTstModelLGeneScores()
-0555 %testModelL.genes = {'Ge1';'Ge2';'Ge4';'Ge5';'Ge7';'Ge9'; 'Gr1';'Gr2';'Gr3';'Gr5';'Gr6';'Gr7';'Gr8';'Gr9';'Gr10';'Gr11';'Gr12';'Gr14';'Gr15'};
-0556 testModelLGeneScores = [3; -1;   8;    6;    -5;    5;     4;    5;    2;    3;    6;    1;    3;    1;    -3;    1;     3;      1;    2];
-0557 end
-0558 
-0559 
-0560 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-0561 %T0050: Test ftINIT on a slightly larger and more complex model
-0562 %       Specifically tests if the three-step variant and the "full"
-0563 %       variant gives similar results
-0564 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-0565 function testftINIT_T0050(testCase)
-0566 solverExist = [exist('gurobi','file'), exist('scip.mexw64','file')] ==3;
-0567 currSolver = getpref('RAVEN','solver');
-0568 if solverExist(1)
-0569     setRavenSolver('gurobi');
-0570 elseif solverExist(2)
-0571     setRavenSolver('scip');
-0572 else
-0573     error('No compatible solvers found');
-0574 end
-0575 
-0576 testModelL = getTstModelL();
-0577 testModelLGeneScores = getTstModelLGeneScores();
-0578 testParams = struct();
-0579 
-0580 arrayDataL = struct();
-0581 arrayDataL.genes = testModelL.genes;
-0582 arrayDataL.tissues = {'t1'};
-0583 arrayDataL.levels = getExprForRxnScore(testModelLGeneScores,1);
-0584 arrayDataL.threshold = 1;
-0585 
-0586 %Run prep data
-0587 [~, prepDataL] = evalc('prepINITModel(testModelL, [], {}, false, {}, ''s'');');
-0588 
-0589 [~,mres] = evalc('ftINIT(prepDataL,arrayDataL.tissues{1},[],[],arrayDataL,[],getINITSteps(),true,true,testParams,false);');
-0590 [~,mres2] = evalc('ftINIT(prepDataL,arrayDataL.tissues{1},[],[],arrayDataL,[],getINITSteps([], ''full''),true,true,testParams,false);');
-0591 
-0592 expResult = {  'S1';'S2';'S3';'S4';'S5';'S6';'S7';'S8';'S9';'E1';'E2';'E3';'E4';'E5';'E6';'E8';'E9';'R1';'R2';'R3';'R4';'R5';'R6';'R7';'R8';'R9';'R12';'R13';'R14';'R15'};
-0593 
-0594 verifyTrue(testCase, all(contains(mres.rxns,expResult)))
-0595 verifyTrue(testCase, all(contains(mres2.rxns,expResult)))
-0596 
-0597 %run the old tINIT version (in Human-GEM)
-0598 %this is just to show that they become different, not really part of the test case
-0599 %paramsL2 = struct();
-0600 %paramsL2.TimeLimit = 1000;
-0601 %testModelL2 = closeModel(testModelL);
-0602 %init_modelOrig = getINITModel2(testModelL2,arrayDataL.tissues{1},[],[],arrayDataL,[],true,[],true,true,[],paramsL2);
-0603 
-0604 %in this call, I have modified the code - the possibility to turn off met secretion + don't allow flux in both directions is not possible.
-0605 %The following line, around line 337, is changed
-0606 %from:
-0607 %[~, deletedRxnsInINIT, metProduction] = runINIT(simplifyModel(cModel),rxnScores,metabolomicsData,essentialRxnsForTasks,0,true,false,params);
-0608 %to:
-0609 %[~, deletedRxnsInINIT, metProduction] = runINIT(simplifyModel(cModel),rxnScores,metabolomicsData,essentialRxnsForTasks,0,false,true,params);
-0610 %init_modelOrigNoSecrOneDirOnly = getINITModel2(testModelL2,arrayDataL.tissues{1},[],[],arrayDataL,[],true,[],true,true,[],paramsL2);
-0611 
-0612 %The models init_modelOrigNoSecrOneDirOnly and mres2 are very similar, (only one exch rxn differ, which is expected)
-0613 %init_modelOrig is quite different, with a lot of gaps, and worse. So, the conclusion is that the new version does a pretty good job.
-0614 setRavenSolver(currSolver);
-0615 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/tutorial/index.html b/doc/tutorial/index.html deleted file mode 100644 index b1ccd2ccc..000000000 --- a/doc/tutorial/index.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - Index for Directory tutorial - - - - - - - - - - -
< Master indexIndex for tutorial >
- -

Index for tutorial

- -

Matlab files in this directory:

- -
 tutorial1tutorial1
 tutorial2tutorial2
 tutorial2_solutionstutorial2_solutions
 tutorial3tutorial3
 tutorial3_solutionstutorial3_solutions
 tutorial4tutorial4
 tutorial4_solutionstutorial4_solutions
 tutorial5tutorial5
 tutorial6tutorial6
- -

Other Matlab-specific files in this directory:

-
    -
  • empty.mat
  • iMK1208+suppInfo.mat
  • pathway.mat
  • pcPathway.mat
- - -
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/tutorial/tutorial1.html b/doc/tutorial/tutorial1.html deleted file mode 100644 index c7483e543..000000000 --- a/doc/tutorial/tutorial1.html +++ /dev/null @@ -1,194 +0,0 @@ - - - - Description of tutorial1 - - - - - - - - - -
Home > tutorial > tutorial1.m
- - - -

tutorial1 -

- -

PURPOSE ^

-
tutorial1
- -

SYNOPSIS ^

-
This is a script file.
- -

DESCRIPTION ^

-
 tutorial1
-   This is a short introduction that shows how to load a genome-scale
-   metabolic model (GEM), set reaction constraints, objective function and
-   perform an optimization through flux balance analysis (FBA). The
-   resulting fluxes are visualized and exported to a PDF file.
-   For a more detailed description of the individual functions, see
-   [raven_directory]/doc/index.html.
-   A GEM for the filamentous fungus Penicillium chrysogenum is used in
-   this tutorial. The model can be found in a Microsoft Excel file under
-   the name "iAL1006 v1.00.xlsx" and in SBML file "iAL1006 v1.00.xml".
-   See Tutorial 1 in "RAVEN tutorials.docx" for more details.
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 % tutorial1
-0002 %   This is a short introduction that shows how to load a genome-scale
-0003 %   metabolic model (GEM), set reaction constraints, objective function and
-0004 %   perform an optimization through flux balance analysis (FBA). The
-0005 %   resulting fluxes are visualized and exported to a PDF file.
-0006 %   For a more detailed description of the individual functions, see
-0007 %   [raven_directory]/doc/index.html.
-0008 %   A GEM for the filamentous fungus Penicillium chrysogenum is used in
-0009 %   this tutorial. The model can be found in a Microsoft Excel file under
-0010 %   the name "iAL1006 v1.00.xlsx" and in SBML file "iAL1006 v1.00.xml".
-0011 %   See Tutorial 1 in "RAVEN tutorials.docx" for more details.
-0012 
-0013 %Import the model from Excel. This function performs a number of checks
-0014 %regarding the model structure (such as for incorrectly written equations
-0015 %or illegal characters). In this structure there is only one warning; that
-0016 %the formula for the metabolite LPE could not be parsed. The "false" flag
-0017 %imports a model with exchange reactions in their "closed" form. This makes
-0018 %the model unsuited for modelling, but it is useful for some quality
-0019 %control steps.
-0020 model=importExcelModel('iAL1006 v1.00.xlsx',false);
-0021 
-0022 %The Excel interface is supposed to work in all the systems (Windows, Unix,
-0023 %macOS), but upon any problems, the model can be imported from SBML format
-0024 %instead. However, in such case the user would not be able to run Tutorials
-0025 %2-4, which involve the editing of Excel files. Run the command below
-0026 %(remove "%" sign) instead, if having such problem:
-0027 %model=importModel('iAL1006 v1.00.xml',false);
-0028 
-0029 %The following function prints some properties of the model. The two "true"
-0030 %flags say that it should also list potential problems such as dead-end
-0031 %reactions or unconnected metabolites.
-0032 printModelStats(model,true,true);
-0033 
-0034 %As can be seen the model contains 1632 reactions, 1395 metabolites and
-0035 %1006 genes
-0036 
-0037 %Most modelling approaches using GEMs are based on the mass balancing
-0038 %around the internal metabolites in the system. However, in order for the
-0039 %system to uptake or excrete metabolites, some metabolites have been
-0040 %defined as "unconstrained". In order to simulate something, those
-0041 %metabolites have to be removed from the model. The function simplifyModel
-0042 %is a general-purpose function for making models smaller. This includes the
-0043 %options such as grouping linear reactions and deleting reactions which
-0044 %cannot carry flux. Here it is chosen to delete the exchange metabolites,
-0045 %all reactions that are constrained to zero (mainly uptake of non-standard
-0046 %carbon sources), and all reactions that cannot carry flux (mainly
-0047 %reactions that were dependent on any of those non-standard carbons
-0048 %sources).
-0049 model=simplifyModel(model,true,false,true,true);
-0050 
-0051 %As can be seen the model now contains only 1305 reactions, 1037
-0052 %metabolites and 1006 genes
-0053 
-0054 %As a first way of validating the model, calculate the theoretical yield of
-0055 %carbon dioxide from glucose. The supplied model already allows for uptake
-0056 %of phosphate, sulfate, NH3, O2 and the co-factor precursors thiamin and
-0057 %pimelate. The setParam function is used for setting constraints,
-0058 %reversibility and objective function coefficients.
-0059 %Set the uptake of glucose to be no more than 1 mmol/gDW/h and no uptake of
-0060 %ethanol.
-0061 model=setParam(model,'ub',{'glcIN' 'etohIN'},[1 0]);
-0062 
-0063 %Set the objective for the simulation to maximize CO2 production
-0064 model=setParam(model,'obj',{'co2OUT'},1);
-0065 
-0066 %The problem can now be solved using linear programming. The solveLP
-0067 %function takes a model and solves the linear programming problem defined
-0068 %by the constraints and the objective value coefficients.
-0069 sol=solveLP(model);
-0070 
-0071 %If everything worked fine one should see a structure that contains the
-0072 %fields .f which is the objective value, .stat which is 1 if the
-0073 %optimization terminated successfully and .x which contains the fluxes
-0074 %through each of the reactions in this particular solution of the problem.
-0075 %sol.x contains 1305 values which makes it rather difficult to interpret. A
-0076 %first approach is to look at only the reactions that transports
-0077 %metabolites in to or out from the system. The printFluxes function prints
-0078 %(parts of) the flux distribution to the console.
-0079 printFluxes(model, sol.x, true, 10^-7); %true means only print exchange fluxes
-0080 
-0081 %One can see that the system took up one unit of glucose and 6 units of O2
-0082 %while producing 6 units of CO2 and 6 units of H2O. To get more detailed
-0083 %insight how this happens, one can use the same function to plot all fluxes
-0084 %(above 10^-7).
-0085 printFluxes(model, sol.x, false, 10^-7);
-0086 
-0087 %The results show many reactions that have -1000 or 1000 flux. This is
-0088 %because there are loops in the solution. In order to clean up the solution
-0089 %one can minimize the sum of all the fluxes. This is done by setting the
-0090 %third flag to solveLP to true (take a look at solveLP, there are other
-0091 %options as well).
-0092 sol=solveLP(model,1);
-0093 printFluxes(model, sol.x, false, 10^-7);
-0094 
-0095 %Now there are much fewer reactions that are active. Some of them will
-0096 %probably appear to be a little "weird" but that is because the ATP and
-0097 %NAD(P)H produced has to go somewhere in order to be mass balanced.
-0098 
-0099 %If one wants to study the growth instead, change the objective to be the
-0100 %production of biomass instead of CO2
-0101 model=setParam(model,'obj',{'bmOUT'},1);
-0102 sol=solveLP(model,1);
-0103 printFluxes(model, sol.x, true, 10^-7);
-0104 
-0105 %The results show that the growth rate is 0.084/h and that the system now
-0106 %also requires sulfate, phosphate, NH3, thiamin and pimelate. Compare this
-0107 %to the growth on ethanol instead of glucose. Use three times the molar
-0108 %flux of ethanol since it contains 2 carbons rather than 6. 'eq' means
-0109 %'equal to' and sets the lower and upper bound to the same value.
-0110 modelETH=setParam(model,'eq',{'glcIN' 'etohIN'},[0 3]);
-0111 solETH=solveLP(modelETH,1);
-0112 printFluxes(modelETH, solETH.x, true, 10^-7);
-0113 
-0114 %Investigate how metabolism changes between the two carbon sources.
-0115 %followChanged takes two flux distributions and lets the user select which
-0116 %reactions should be printed. Here the reactions are shown that differ with
-0117 %more than 50%, has a flux higher than 0.5 mmol/gDW/h and an absolute
-0118 %difference higher than 0.5 mmol/gDW/h.
-0119 followChanged(modelETH,sol.x,solETH.x, 50, 0.5, 0.5);
-0120 
-0121 %There are 65 such reactions. By studying them one can start to get an idea
-0122 %about where the key changes occur. Visualization can help a lot in this
-0123 %regard. One can investigate how ATP metabolism changes by running the
-0124 %following command:
-0125 followChanged(modelETH,sol.x,solETH.x, 30, 0.4, 0.4,{'ATP'});
-0126 
-0127 %See that on glucose ATP is generated in glycolysis but on ethanol it seems
-0128 %to have to do with acetate and so on. This allows the user to look further
-0129 %and further down until one understands the underlying flux redistributions
-0130 %that give rise to different phenotypes.
-0131 
-0132 %The fluxes can also be visualized on a metabolic map. Green corresponds to
-0133 %reactions which are more used for growth on glucose, and red are reactions
-0134 %which are more used for growth on ethanol. Open the "GLCvsETH.pdf" file to
-0135 %be able to zoom in on individual reactions.
-0136 load 'pcPathway.mat' pathway;
-0137 drawMap('Glucose vs ethanol',pathway,model,sol.x,solETH.x,modelETH,'GLCvsETH.pdf',10^-5);
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/tutorial/tutorial2.html b/doc/tutorial/tutorial2.html deleted file mode 100644 index f480bd48a..000000000 --- a/doc/tutorial/tutorial2.html +++ /dev/null @@ -1,73 +0,0 @@ - - - - Description of tutorial2 - - - - - - - - - -
Home > tutorial > tutorial2.m
- - - -

tutorial2 -

- -

PURPOSE ^

-
tutorial2
- -

SYNOPSIS ^

-
This is a script file.
- -

DESCRIPTION ^

-
 tutorial2
-   This exercise deals with the a small glycolysis model in RAVEN
-   compatible Excel format and shows the most basic aspects of the
-   stoichiometric modelling. It is shown how to build a simple model from
-   scratch, set parameters and perform simple simulations.
-   See Tutorial 2 in "RAVEN tutorials.docx" for more details.
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 % tutorial2
-0002 %   This exercise deals with the a small glycolysis model in RAVEN
-0003 %   compatible Excel format and shows the most basic aspects of the
-0004 %   stoichiometric modelling. It is shown how to build a simple model from
-0005 %   scratch, set parameters and perform simple simulations.
-0006 %   See Tutorial 2 in "RAVEN tutorials.docx" for more details.
-0007 
-0008 %Import the Excel model into a RAVEN model structure
-0009 smallModel=importExcelModel('empty.xlsx');
-0010 
-0011 %This solves the linear programming problem.
-0012 %NOTE: if sol.f is equal to zero then the problem is not solvable. Ensure
-0013 %that uptake and excretion of all necessary stuff are added to the model
-0014 %and run the solveLP again.
-0015 sol=solveLP(smallModel);
-0016 
-0017 %Print the resulting exchange fluxes
-0018 printFluxes(smallModel,sol.x,true);
-0019 
-0020 %Print all fluxes
-0021 printFluxes(smallModel,sol.x,false,10^-5,[],'%rxnID (%rxnName):\n\t%eqn\n\t%flux\n');
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/tutorial/tutorial2_solutions.html b/doc/tutorial/tutorial2_solutions.html deleted file mode 100644 index 1c7a6102f..000000000 --- a/doc/tutorial/tutorial2_solutions.html +++ /dev/null @@ -1,67 +0,0 @@ - - - - Description of tutorial2_solutions - - - - - - - - - -
Home > tutorial > tutorial2_solutions.m
- - - -

tutorial2_solutions -

- -

PURPOSE ^

-
tutorial2_solutions
- -

SYNOPSIS ^

-
This is a script file.
- -

DESCRIPTION ^

-
 tutorial2_solutions
-   This script contains the solutions for Tutorial 2, see Tutorial 2 in
-   "RAVEN tutorials.docx" for more details.
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 % tutorial2_solutions
-0002 %   This script contains the solutions for Tutorial 2, see Tutorial 2 in
-0003 %   "RAVEN tutorials.docx" for more details.
-0004 
-0005 %Import the Excel model into a RAVEN model structure
-0006 smallModel=importExcelModel('small.xlsx');
-0007 
-0008 %This solves the linear programming problem.
-0009 %NOTE: if sol.f is equal to zero then the problem is not solvable. Ensure
-0010 %that uptake and excretion of all necessary stuff are added to the model
-0011 %and run the solveLP again.
-0012 sol=solveLP(smallModel);
-0013 
-0014 %Print the resulting exchange fluxes
-0015 printFluxes(smallModel,sol.x,true);
-0016 
-0017 %Print all fluxes
-0018 printFluxes(smallModel,sol.x,false,10^-5,[],'%rxnID (%rxnName):\n\t%eqn\n\t%flux\n');
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/tutorial/tutorial3.html b/doc/tutorial/tutorial3.html deleted file mode 100644 index f4cd9cc9c..000000000 --- a/doc/tutorial/tutorial3.html +++ /dev/null @@ -1,134 +0,0 @@ - - - - Description of tutorial3 - - - - - - - - - -
Home > tutorial > tutorial3.m
- - - -

tutorial3 -

- -

PURPOSE ^

-
tutorial3
- -

SYNOPSIS ^

-
This is a script file.
- -

DESCRIPTION ^

-
 tutorial3
-   This exercise shows how to run FBA and minimization of metabolic
-   adjustment (MOMA) simulations and how one can use GEMs as a scaffold
-   for interpreting microarray data. A simplified model of yeast
-   metabolism is used in this approach as an example.
-   See Tutorial 3 in "RAVEN tutorials.docx" for more details.
-
-   It is assumed that the user has already completed Tutorial 2
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 % tutorial3
-0002 %   This exercise shows how to run FBA and minimization of metabolic
-0003 %   adjustment (MOMA) simulations and how one can use GEMs as a scaffold
-0004 %   for interpreting microarray data. A simplified model of yeast
-0005 %   metabolism is used in this approach as an example.
-0006 %   See Tutorial 3 in "RAVEN tutorials.docx" for more details.
-0007 %
-0008 %   It is assumed that the user has already completed Tutorial 2
-0009 
-0010 %Import the Excel model
-0011 model=importExcelModel('smallYeast.xlsx',true);
-0012 
-0013 %Set the upper bound of glucose uptake to 1 and O2 uptake to unlimited
-0014 model=setParam(model,'ub',{'glcIN' 'o2IN'},[1 1000]);
-0015 
-0016 %Set the objective to be ethanol production
-0017 model=setParam(model,'obj',{'ethOUT'},1);
-0018 
-0019 %Solve the model
-0020 sol=solveLP(model);
-0021 
-0022 %Print the resulting exchange fluxes
-0023 printFluxes(model,sol.x,true);
-0024 
-0025 %Compare two flux distributions by loading the map
-0026 load 'pathway.mat' pathway;
-0027 drawMap('Aerobic vs Anaerobic',pathway,model,solA.x,solB.x,[],'mapFBA.pdf',10^-5);
-0028 
-0029 %Run a single gene deletion
-0030 [genes, fluxes, originalGenes, details]=findGeneDeletions(model,'sgd','fba');
-0031 
-0032 %Get the indexes of these reactions
-0033 I=getIndexes(model,{'biomassOUT'},'rxns');
-0034 J=getIndexes(model,{'glyOUT'},'rxns');
-0035 
-0036 okSolutions=find(fluxes(I,:)>10^-2); %Only look at solutions which are still growing
-0037 [maxGlycerol, J]=max(fluxes(J,okSolutions));
-0038 disp(maxGlycerol);
-0039 disp(originalGenes(genes(okSolutions(J),:)));
-0040 
-0041 %Draw map for the ZWF1 deletion strain
-0042 model2=setParam(model,'eq',{'ZWF'},0);
-0043 sol2=solveLP(model2);
-0044 drawMap('ZWF1 deletion vs WT',pathway,model,sol.x,sol2.x,[],'mapZWF.pdf',10^-5);
-0045 followChanged(model,sol2.x,sol.x, 10, 10^-2, 0,{'NADPH' 'NADH' 'NAD' 'NADP'});
-0046 
-0047 %Import the model
-0048 SBMLFromExcel('smallYeast.xlsx','smallYeast.xml')
-0049 model=importModel('smallYeast.xml',true);
-0050 sol=solveLP(model);
-0051 
-0052 %Define another model where all exchange reactions are open
-0053 model2=model;
-0054 I=getIndexes(model,getExchangeRxns(model),'rxns');
-0055 model2.lb(I)=0;
-0056 model2.ub(I)=1000;
-0057 
-0058 %Delete ZWF gene
-0059 model2=setParam(model2,'eq',{'ZWF'},0);
-0060 
-0061 %Run MOMA
-0062 [fluxA, fluxB, flag]=qMOMA(model,model2);
-0063 drawMap('Aerobic vs Anaerobic MOMA',pathway,model,fluxA,fluxB,[],'mapMOMA.pdf',10^-5);
-0064 
-0065 %Read microarray results and calculate reporter metabolites (metabolites
-0066 %around which there are significant transcriptional changes)
-0067 [orfs, pvalues]=textread('expression.txt','%s%f');
-0068 repMets=reporterMetabolites(model,orfs,pvalues);
-0069 [I, J]=sort(repMets.metPValues);
-0070 
-0071 fprintf('TOP 10 REPORTER METABOLITES:\n');
-0072 for i=1:min(numel(J),10)
-0073     fprintf([repMets.mets{J(i)} '\t' num2str(I(i)) '\n']);
-0074 end
-0075 
-0076 %Get all reactions involving those metabolites and display them on a map
-0077 mets=ismember(model.mets,repMets.mets(J(1:10)));
-0078 [~, I]=find(model.S(mets,:));
-0079 pathway=trimPathway(pathway, model.rxns(I), true);
-0080 drawMap('Reactions involving the top 10 Reporter Metabolites',pathway,model,ones(numel(model.rxns),1),zeros(numel(model.rxns),1),[],'mapRM.pdf',10^-5);
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/tutorial/tutorial3_solutions.html b/doc/tutorial/tutorial3_solutions.html deleted file mode 100644 index 2aa5cfdfa..000000000 --- a/doc/tutorial/tutorial3_solutions.html +++ /dev/null @@ -1,166 +0,0 @@ - - - - Description of tutorial3_solutions - - - - - - - - - -
Home > tutorial > tutorial3_solutions.m
- - - -

tutorial3_solutions -

- -

PURPOSE ^

-
tutorial3_solutions
- -

SYNOPSIS ^

-
This is a script file.
- -

DESCRIPTION ^

-
 tutorial3_solutions
-   This script contains the solutions for Tutorial 3, see Tutorial 3 in
-   "RAVEN tutorials.docx" for more details. All the parameters are set in
-   this script, rather than modifying the Excel model file.
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 % tutorial3_solutions
-0002 %   This script contains the solutions for Tutorial 3, see Tutorial 3 in
-0003 %   "RAVEN tutorials.docx" for more details. All the parameters are set in
-0004 %   this script, rather than modifying the Excel model file.
-0005 
-0006 %Import the Excel model
-0007 model=importExcelModel('smallYeast.xlsx',true);
-0008 
-0009 %Step 1
-0010 %Set the upper bound of glucose uptake to 1 and O2 uptake to zero
-0011 model=setParam(model,'ub',{'glcIN' 'o2IN'},[1 0]);
-0012 
-0013 %Set the objective to be ATP hydrolysis
-0014 model=setParam(model,'obj',{'ATPX'},1);
-0015 
-0016 %Solve the model
-0017 sol=solveLP(model);
-0018 
-0019 %Print the resulting fluxes. The ATP production rate should be 2.0. It was
-0020 %4.0 in Tutorial 2, but there sucrose was used instead of glucose.
-0021 printFluxes(model,sol.x,false);
-0022 
-0023 %Step 2
-0024 %Check the yield of different products and print the results
-0025 %Change to fully aerobic
-0026 model=setParam(model,'ub',{'glcIN' 'o2IN'},[1 1000]);
-0027 model=setParam(model,'obj',{'ethOUT'},1);
-0028 sol=solveLP(model);
-0029 fprintf(['Yield of ethanol is ' num2str(sol.f) ' mol/mol\n']);
-0030 model=setParam(model,'obj',{'acOUT'},1);
-0031 sol=solveLP(model);
-0032 fprintf(['Yield of acetate is ' num2str(sol.f) ' mol/mol\n']);
-0033 model=setParam(model,'obj',{'glyOUT'},1);
-0034 sol=solveLP(model);
-0035 fprintf(['Yield of glycerol is ' num2str(sol.f) ' mol/mol\n']);
-0036 model=setParam(model,'obj',{'biomassOUT'},1);
-0037 sol=solveLP(model);
-0038 fprintf(['Yield of biomass is ' num2str(sol.f) '/h\n']);
-0039 
-0040 %Step 3
-0041 %Solve for both aerobic and anaerobic growth
-0042 solA=solveLP(model);
-0043 model=setParam(model,'ub',{'o2IN'},0.5);
-0044 solB=solveLP(model);
-0045 
-0046 %Plot the differences
-0047 %Load the map
-0048 load 'pathway.mat' pathway;
-0049 drawMap('Aerobic vs Anaerobic',pathway,model,solA.x,solB.x,[],'mapFBA.pdf',10^-5);
-0050 
-0051 %Step 4
-0052 %Change to anaerobic growth and maximize for biomass
-0053 model=setParam(model,'eq',{'o2IN'},0);
-0054 model=setParam(model,'obj',{'biomassOUT'},1);
-0055 sol=solveLP(model);
-0056 printFluxes(model,sol.x,true);
-0057 %One can see that the model predicts a glycerol production of 0.23
-0058 %mmol/gDW/h
-0059 
-0060 %Run a single gene deletion
-0061 [genes, fluxes, originalGenes, details]=findGeneDeletions(model,'sgd','fba');
-0062 
-0063 %Get the indexes of these reactions
-0064 I=getIndexes(model,{'biomassOUT'},'rxns');
-0065 J=getIndexes(model,{'glyOUT'},'rxns');
-0066 
-0067 okSolutions=find(fluxes(I,:)>10^-2); %Only look at solutions which are still growing
-0068 [maxGlycerol, J]=max(fluxes(J,okSolutions));
-0069 fprintf(['Glycerol production is ' num2str(maxGlycerol) ' after deletion of ' originalGenes{genes(okSolutions(J),:)} '\n']);
-0070 
-0071 %The best gene deletion corresponds to turning off the ZWF1 reaction
-0072 %(YNL241C)
-0073 model2=setParam(model,'eq',{'ZWF'},0);
-0074 sol2=solveLP(model2);
-0075 drawMap('ZWF1 deletion vs WT',pathway,model,sol2.x,sol.x,[],'mapZWF.pdf',10^-5);
-0076 followChanged(model,sol2.x,sol.x, 10, 10^-2, 0,{'NADPH' 'NADH' 'NAD' 'NADP'});
-0077 
-0078 %Step 5
-0079 %Set the exchange rates to the recorded batch values
-0080 model=setParam(model,'lb',{'acOUT' 'biomassOUT' 'co2OUT' 'ethOUT' 'glyOUT' 'glcIN' 'o2IN' 'ethIN'},[0 0.67706 22.4122 19.0946 1.4717 15 1.6 0]*0.9999);
-0081 model=setParam(model,'ub',{'acOUT' 'biomassOUT' 'co2OUT' 'ethOUT' 'glyOUT' 'glcIN' 'o2IN' 'ethIN'},[0 0.67706 22.4122 19.0946 1.4717 15 1.6 0]*1.0001);
-0082 
-0083 %Define another model where all exchange reactions are open.
-0084 model2=model;
-0085 I=getIndexes(model,getExchangeRxns(model),'rxns');
-0086 model2.lb(I)=0;
-0087 model2.ub(I)=1000;
-0088 
-0089 %Delete ZWF gene
-0090 model2=setParam(model2,'eq',{'ZWF'},0);
-0091 
-0092 %Run MOMA
-0093 [fluxA, fluxB, flag]=qMOMA(model,model2);
-0094 drawMap('ZWF deletion vs wild type',pathway,model,fluxB,fluxA,[],'mapMOMA.pdf',10^-5);
-0095 
-0096 %As one can see, the glycerol production is higher in the deletion strain.
-0097 %Note that this is without any objectives, just by trying to maintain the
-0098 %cells original flux distribution.
-0099 
-0100 %Step 6
-0101 %Read microarray results and calculate reporter metabolites (metabolites
-0102 %around which there are significant transcriptional changes)
-0103 [orfs, pvalues]=textread('expression.txt','%s%f');
-0104 repMets=reporterMetabolites(model,orfs,pvalues);
-0105 [I, J]=sort(repMets.metPValues);
-0106 
-0107 fprintf('TOP 10 REPORTER METABOLITES:\n');
-0108 for i=1:min(numel(J),10)
-0109     fprintf([repMets.mets{J(i)} '\t' num2str(I(i)) '\n']);
-0110 end
-0111 
-0112 %Get all reactions involving those metabolites and display them on a map
-0113 mets=ismember(model.mets,repMets.mets(J(1:10)));
-0114 [~, I]=find(model.S(mets,:));
-0115 pathway=trimPathway(pathway, model.rxns(I), true);
-0116 drawMap('Reactions involving the top 10 Reporter Metabolites',pathway,model,ones(numel(model.rxns),1),zeros(numel(model.rxns),1),[],'mapRM.pdf',10^-5);
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/tutorial/tutorial4.html b/doc/tutorial/tutorial4.html deleted file mode 100644 index 6f3e8a77f..000000000 --- a/doc/tutorial/tutorial4.html +++ /dev/null @@ -1,84 +0,0 @@ - - - - Description of tutorial4 - - - - - - - - - -
Home > tutorial > tutorial4.m
- - - -

tutorial4 -

- -

PURPOSE ^

-
tutorial4
- -

SYNOPSIS ^

-
This is a script file.
- -

DESCRIPTION ^

-
 tutorial4
-   This script contains the list of functions necessary for running
-   Tutorial 4, see Tutorial 4 in "RAVEN tutorials.docx" for more details.
-   Several key stages may be missing, try to fill these gaps before
-   checking the solutions in tutorial4_solutions. It is assumed that the
-   user is somewhat familiar with linear programming.
-
-   It is assumed that the user has already completed Tutorials 2-3
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 % tutorial4
-0002 %   This script contains the list of functions necessary for running
-0003 %   Tutorial 4, see Tutorial 4 in "RAVEN tutorials.docx" for more details.
-0004 %   Several key stages may be missing, try to fill these gaps before
-0005 %   checking the solutions in tutorial4_solutions. It is assumed that the
-0006 %   user is somewhat familiar with linear programming.
-0007 %
-0008 %   It is assumed that the user has already completed Tutorials 2-3
-0009 
-0010 %Import the Excel model
-0011 model=importExcelModel('smallYeastBad.xlsx');
-0012 model.b=[model.b inf(numel(model.b),1)];
-0013 sol=solveLP(model,1);
-0014 printFluxes(model,sol.x,false,10^-5,[],'%rxnID (%rxnName):\n\t%eqn\n\t%flux\n');
-0015 I=canConsume(model);
-0016 disp(model.mets(I));
-0017 gapReport(model,{refModel});
-0018 
-0019 model=importExcelModel('smallYeastBad2.xlsx');
-0020 [reducedModel, deletedReactions, deletedMetabolites]=simplifyModel(model,false,false,false,true);
-0021 disp(deletedReactions);
-0022 disp(deletedMetabolites);
-0023 [notProducedMets, ~, neededForProductionMat, minToConnect]=checkProduction(model,true,model.comps,false);
-0024 disp(minToConnect);
-0025 
-0026 refModel=importExcelModel('smallYeast.xlsx');
-0027 [newConnected, cannotConnect, addedRxns, newModel]=fillGaps(model,{refModel},false);
-0028 disp(addedRxns);
-0029 disp(newConnected);
-0030 disp(cannotConnect);
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/tutorial/tutorial4_solutions.html b/doc/tutorial/tutorial4_solutions.html deleted file mode 100644 index 74c15ea0b..000000000 --- a/doc/tutorial/tutorial4_solutions.html +++ /dev/null @@ -1,207 +0,0 @@ - - - - Description of tutorial4_solutions - - - - - - - - - -
Home > tutorial > tutorial4_solutions.m
- - - -

tutorial4_solutions -

- -

PURPOSE ^

-
tutorial4_solutions
- -

SYNOPSIS ^

-
This is a script file.
- -

DESCRIPTION ^

-
 tutorial4_solutions
-   This script contains the solutions for Tutorial 4, see Tutorial 4 in
-   "RAVEN tutorials.docx" for more details.
-
-   NOTE: Many of these changes are easier to do in the Excel sheet. They
-   are done here in code just to avoid having several model files.
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 % tutorial4_solutions
-0002 %   This script contains the solutions for Tutorial 4, see Tutorial 4 in
-0003 %   "RAVEN tutorials.docx" for more details.
-0004 %
-0005 %   NOTE: Many of these changes are easier to do in the Excel sheet. They
-0006 %   are done here in code just to avoid having several model files.
-0007 
-0008 %Import the Excel model
-0009 model=importExcelModel('smallYeastBad.xlsx');
-0010 
-0011 %Close all uptake and maximize for production
-0012 model=setParam(model,'eq',{'glcIN', 'o2IN'},[0 0]);
-0013 model=setParam(model,'obj',{'acOUT' 'biomassOUT' 'co2OUT' 'ethOUT' 'glyOUT'},[1 1 1 1 1]);
-0014 sol=solveLP(model);
-0015 printFluxes(model,sol.x,true); %Nothing produced, good
-0016 
-0017 %Add some fake reactions
-0018 rxns.rxns={'FREE_ATP';'FREE_NADH';'FREE_NADPH'};
-0019 rxns.equations={'ATP <=> ADP + phosphate';'NAD(+) <=> NADH';'NADP(+) <=> NADPH'};
-0020 model=addRxns(model,rxns,2,'c');
-0021 sol=solveLP(model,1);
-0022 
-0023 %Lots of ethanol produced. Also plot the equations to make the error easier
-0024 %to find
-0025 printFluxes(model,sol.x,false,[],[],'%rxnID (%rxnName):%flux\n\t%eqn\n');
-0026 
-0027 %See that ADH1 should only produce one unit of ethanol. Change the reaction
-0028 %equation
-0029 model=changeRxns(model,'ADH1','acetaldehyde[c] + NADH[c] => ethanol[c] + NAD(+)[c]',3);
-0030 sol=solveLP(model,1);
-0031 printFluxes(model,sol.x,true); %Nothing produced, good
-0032 
-0033 %Add excretion of all metabolites
-0034 model.b=[model.b inf(numel(model.b),1)];
-0035 sol=solveLP(model,1);
-0036 printFluxes(model,sol.x,false,10^-5,[],'%rxnID (%rxnName):\n\t%eqn\n\t%flux\n');
-0037 
-0038 %By looking at the reactions which were unbalanced and that were in the
-0039 %flux list one can see that FBP should be changed to result in only one unit
-0040 %of F6P
-0041 model=changeRxns(model,'FBP','beta-D-fructofuranose 1,6-bisphosphate[c] => beta-D-fructofuranose 6-phosphate[c] + phosphate[c]',3);
-0042 sol=solveLP(model,1);
-0043 printFluxes(model,sol.x,false,10^-5,[],'%rxnID (%rxnName):\n\t%eqn\n\t%flux\n');
-0044 
-0045 %The same thing again and one should change PFK to only give one unit of
-0046 %F16P
-0047 model=changeRxns(model,'PFK','ATP[c] + beta-D-fructofuranose 6-phosphate[c] => ADP[c] + beta-D-fructofuranose 1,6-bisphosphate[c]',3);
-0048 sol=solveLP(model,1);
-0049 printFluxes(model,sol.x,false,10^-5,[],'%rxnID (%rxnName):\n\t%eqn\n\t%flux\n'); %Now it works
-0050 
-0051 %Set all uptakes and production to 0
-0052 model=setParam(model,'eq',getExchangeRxns(model),0);
-0053 
-0054 %Since it is checked which metabolites could be consumed without
-0055 %production, one can no longer have free production of all metabolites
-0056 model.b=model.b(:,1);
-0057 I=canConsume(model);
-0058 disp(model.mets(I)); %These 12 metabolites can be consumed without any production
-0059 
-0060 %Allow all uptake
-0061 model.b=[ones(numel(model.b),1)*-1000 model.b];
-0062 
-0063 %Pick CO2 and force uptake of it
-0064 model=setParam(model,'eq',{'co2OUT'},-1); %Negative output means input
-0065 sol=solveLP(model);
-0066 printFluxes(model,sol.x,false,10^-5,[],'%rxnID (%rxnName):\n\t%eqn\n\t%flux\n'); %Now it works
-0067 
-0068 %See that PDC converts pyruvate (3 carbons) to acetaldehyde (2 carbons)
-0069 %without any other products. If one googles, one may realize that CO2 is
-0070 %missing. This would be simpler to change in the Excel file (or using
-0071 %changeRxns), but one can change it here as an exercise. One therefore
-0072 %needs to find the index of the reactions and the index of cytosolic CO2 in
-0073 %order to change the reaction
-0074 Irxn=ismember(model.rxns,'PDC');
-0075 Imet=ismember(model.mets,'CO2_c');
-0076 model.S(Imet,Irxn)=1; %The coefficient is 1.0
-0077 
-0078 %Display the new equation just to be sure
-0079 constructEquations(model,Irxn)
-0080 
-0081 %The solution is now not feasible, meaning that it is no longer possible to
-0082 %force uptake of CO2 without any output
-0083 sol=solveLP(model);
-0084 
-0085 %***Second part of tutorial
-0086 model=importExcelModel('smallYeastBad2.xlsx',true,false,true); %This has to be loaded with the setting to ignore error or it would find the error
-0087 [reducedModel, deletedReactions, deletedMetabolites]=simplifyModel(model,false,false,false,true);
-0088 disp(deletedReactions);
-0089 disp(deletedMetabolites);
-0090 
-0091 %It turned out that G15L_c was spelled G15Lc in one reaction. The best
-0092 %solution would be just to change it in the reaction list and remove the
-0093 %duplicate metabolite, but one can do it here as an exercise. The indexes
-0094 %of the two metabolites are needed.
-0095 Igood=ismember(model.mets,'G15L_c');
-0096 Ibad=ismember(model.mets,'G15Lc');
-0097 
-0098 %Get all reactions and the coefficients in which the wrong one participates
-0099 %move them to be for the right one instead
-0100 model.S(Igood,:)=model.S(Igood,:)+model.S(Ibad,:);
-0101 
-0102 %Delete the bad one
-0103 model=removeMets(model,'G15Lc');
-0104 [reducedModel, deletedReactions, deletedMetabolites]=simplifyModel(model,false,false,false,true);
-0105 disp(deletedReactions);
-0106 disp(deletedMetabolites);
-0107 
-0108 %The only difference was that there were 20 deleted metabolites instead of
-0109 %21. Nothing too spectacular. Check production can tell the user what one
-0110 %needs to connect.
-0111 [notProducedMets, ~, neededForProductionMat, minToConnect]=checkProduction(model,true,model.comps,false);
-0112 
-0113 %In order to have production of all 54 metabolites one needs to enable
-0114 %production of these 12. This small model does not include net synthesis of
-0115 %co-factors, so one should concentrate on the other ones. Glycerone
-0116 %phosphate allows for connection 18 others, so it seems like a good target.
-0117 disp(minToConnect);
-0118 
-0119 %If one googles around a little bit, and knows the metabolism, one would
-0120 %find that DHAP (dihydroxyacetone) and GLYP (glycerone phosphate) are
-0121 %actually synonymes. Only use DHAP
-0122 Igood=ismember(model.mets,'DHAP_c');
-0123 Ibad=ismember(model.mets,'GLYP_c');
-0124 
-0125 %Get all reactions and the coefficients in which the wrong one participates
-0126 %move them to be for the right one instead
-0127 model.S(Igood,:)=model.S(Igood,:)+model.S(Ibad,:);
-0128 
-0129 %Delete the bad one
-0130 model=removeMets(model,'GLYP_c');
-0131 [reducedModel, deletedReactions, deletedMetabolites]=simplifyModel(model,false,false,false,true);
-0132 disp(deletedReactions);
-0133 disp(deletedMetabolites);
-0134 [notProducedMets, ~, neededForProductionMat, minToConnect]=checkProduction(model,true,model.comps,false);
-0135 disp(minToConnect);
-0136 
-0137 %Still quite a lot of gaps and no immediate way to fix it. One could try
-0138 %including reactions from a reference network and see if that helps. Use
-0139 %the small yeast model from Tutorial 3
-0140 refModel=importExcelModel('smallYeast.xlsx');
-0141 [newConnected, cannotConnect, addedRxns, newModel]=fillGaps(model,{refModel},false);
-0142 disp(addedRxns);
-0143 disp(newConnected);
-0144 
-0145 %By including the ALD6 reaction from the reference model it was possible to
-0146 %connect 21 reactions
-0147 [reducedModel, deletedReactions, deletedMetabolites]=simplifyModel(newModel,false,false,false,true);
-0148 disp(deletedMetabolites);
-0149 disp(deletedReactions);
-0150 
-0151 %All the model seems to be connected
-0152 
-0153 %All this stuff may be done in a more automated manner as well
-0154 model=importExcelModel('smallYeastBad2.xlsx',true,false,true);
-0155 gapReport(model,{refModel});
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/tutorial/tutorial5.html b/doc/tutorial/tutorial5.html deleted file mode 100644 index cd50311e9..000000000 --- a/doc/tutorial/tutorial5.html +++ /dev/null @@ -1,252 +0,0 @@ - - - - Description of tutorial5 - - - - - - - - - -
Home > tutorial > tutorial5.m
- - - -

tutorial5 -

- -

PURPOSE ^

-
tutorial5
- -

SYNOPSIS ^

-
This is a script file.
- -

DESCRIPTION ^

-
 tutorial5
-   This exercise is about creating a model from KEGG, based on protein
-   sequences in a FASTA file, and doing some functionality checks on the
-   model. The example case is for the yeast Saccharomyces cerevisiae. This
-   tutorial is more of a showcase than the previous four, and its main
-   purpose is to serve as a scaffold to reconstruct a GEM for any
-   organism.
-   This refers to Tutorial 5 from "RAVEN tutorials.docx"
- 
- Start by downloading trained Hidden Markov Models for eukaryotes. This can
- be done automatically or manually from the RAVEN Wiki in its GitHub
- repository. In this tutorial, the archive "euk90_kegg105" is picked for
- the automatic download. See the documentation in the RAVEN Wiki for more
- information regarding preparation of such archive.
- 
- This creates a model for S. cerevisiae. The parameters are set to exclude
- general or unclear reactions and reactions with undefined stoichiometry.
- Type "help getKEGGModelForOrganism" to see what the different parameters
- are for. This process takes up to 20-35 minutes in macOS, Unix systems and
- 40-55 minutes in Windows, depending on your hardware and the size of
- target organism proteome
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 % tutorial5
-0002 %   This exercise is about creating a model from KEGG, based on protein
-0003 %   sequences in a FASTA file, and doing some functionality checks on the
-0004 %   model. The example case is for the yeast Saccharomyces cerevisiae. This
-0005 %   tutorial is more of a showcase than the previous four, and its main
-0006 %   purpose is to serve as a scaffold to reconstruct a GEM for any
-0007 %   organism.
-0008 %   This refers to Tutorial 5 from "RAVEN tutorials.docx"
-0009 %
-0010 % Start by downloading trained Hidden Markov Models for eukaryotes. This can
-0011 % be done automatically or manually from the RAVEN Wiki in its GitHub
-0012 % repository. In this tutorial, the archive "euk90_kegg105" is picked for
-0013 % the automatic download. See the documentation in the RAVEN Wiki for more
-0014 % information regarding preparation of such archive.
-0015 %
-0016 % This creates a model for S. cerevisiae. The parameters are set to exclude
-0017 % general or unclear reactions and reactions with undefined stoichiometry.
-0018 % Type "help getKEGGModelForOrganism" to see what the different parameters
-0019 % are for. This process takes up to 20-35 minutes in macOS, Unix systems and
-0020 % 40-55 minutes in Windows, depending on your hardware and the size of
-0021 % target organism proteome
-0022 model=getKEGGModelForOrganism('sce','sce.fa','euk90_kegg105','output',false,false,false,false,10^-30,0.8,0.3,-1);
-0023 
-0024 % The resulting model should contain around 1589 reactions, 1600
-0025 % metabolites and 836 genes. Small variations are possible since it is an
-0026 % heuristic algorithm and different KEGG versions will give slightly
-0027 % different results.
-0028 disp(model);
-0029 
-0030 % A first control is that the model should not be able to produce any
-0031 % metabolites without uptake of some metabolites. This commonly happens when
-0032 % metabolites have a different meaning in different reactions. The best way
-0033 % to find such reactions is to run makeSomething and analyze the resulting
-0034 % solution for bad reactions. An automated approach is to use removeBadRxns,
-0035 % which tries to do the same thing in an automated manner. Type
-0036 % "help removeBadRxns" for details.
-0037 [newModel, removedRxns]=removeBadRxns(model);
-0038 
-0039 % One can see an error about that H+ can be made even if no reactions were
-0040 % unbalanced. Protons are particularly problematic since it is rather
-0041 % arbitary at which pH the formulas are written for. For the purpose of this
-0042 % analysis, the protons can be ignored and fixed later.
-0043 [newModel, removedRxns]=removeBadRxns(model,1,{'H+'},true);
-0044 
-0045 % Only one reaction was removed because it enabled the model to produce
-0046 % something from nothing. Since it is only one reaction, it might be
-0047 % worthwhile to look into this in more detail.
-0048 disp(removedRxns);
-0049 
-0050 % According to the information in KEGG about this reaction it is a general
-0051 % polymer reaction. One might want to look at the flux distributions
-0052 % in more detail to try to find out if there is any better alternative to
-0053 % delete. Use makeSomething to do this.
-0054 [fluxes, metabolite]=makeSomething(model,{'H+'},true);
-0055 model.metNames(metabolite)
-0056 
-0057 % The model could produce H2O using the following reactions
-0058 printFluxes(model, fluxes, false, [], [],'%rxnID (%rxnName):\n\t%eqn: %flux\n')
-0059 
-0060 % That resulted in quite a lot of fluxes to look through. Maybe it is easier
-0061 % if the elementally balanced reactions are excluded.
-0062 balanceStructure=getElementalBalance(model);
-0063 
-0064 % The hydrogen balancing is a bit tricky, so this time it seems more
-0065 % relevant to only look at the ones unbalanced for oxygen (since water was
-0066 % produced)
-0067 goodOnes=balanceStructure.leftComp(:,6)==balanceStructure.rightComp(:,6);
-0068 printFluxes(removeReactions(model,goodOnes), fluxes(~goodOnes), false, [], [],'%rxnID (%rxnName):\n\t%eqn: %flux\n');
-0069 
-0070 % There is still a good number of reactions. Leave only the reactions which
-0071 % involve amylose or starch, from one of the problematic reactions that was
-0072 % identified earlier.
-0073 printFluxes(model, fluxes, false, [], [],'%rxnID (%rxnName):\n\t%eqn: %flux\n',{'Amylose';'Starch'});
-0074 
-0075 % There are two elementally unbalanced reactions, including, the reaction
-0076 % which was identified by removeBadRxns. When looking to these reactions
-0077 % closer, one can notice the contradiction between the reactions. The first
-0078 % one shows that amylose and starch are interconvertible, while the second
-0079 % reaction shows that amylose contains one less glucose unit than starch.
-0080 % This type of general reactions are problematic and should be fixed
-0081 % manually. It is hereby chosen to trust removeBadRxns and delete R02110.
-0082 model=removeReactions(model,'R02110');
-0083 
-0084 % The model can no longer make something from nothing. Can it consume
-0085 % something without any output?
-0086 [solution, metabolite]=consumeSomething(model,{'H+'},true);
-0087 model.metNames(metabolite)
-0088 
-0089 % Nope, so that was good. Add some uptakes and see what it can produce.
-0090 [~, J]=ismember({'D-Glucose';'H2O';'Orthophosphate';'Oxygen';'NH3';'Sulfate'},model.metNames);
-0091 [model, addedRxns]=addExchangeRxns(model,'in',J);
-0092 
-0093 % Check which metabolites can be produced given these uptakes. The
-0094 % canProduce function allows for output of all metabolites. This will not
-0095 % happen in the real cell, but it is very useful for functionality testing
-0096 % of the model. Once it is functional, the excretion reactions based on
-0097 % evidence can be added as well.
-0098 I=canProduce(model);
-0099 
-0100 fprintf('%d%%\n', round(sum(I)/numel(model.mets)*100));
-0101 % It seems that around 31% of the metabolites could be synthesized. It is
-0102 % not directly clear whether this is a high or low number, many metabolites
-0103 % should not be possible to synthesize from those simple precursors.
-0104 
-0105 % Try to fill gaps using the full KEGG model to see if that gives a
-0106 % significantly higher number
-0107 keggModel=getModelFromKEGG([],false,false,false,false);
-0108 
-0109 % The KEGG model is associated to more than 6,400,000 genes. They will not
-0110 % be used for the gapfilling, so they are removed to make this a little
-0111 % faster
-0112 keggModel=rmfield(keggModel,'genes');
-0113 keggModel=rmfield(keggModel,'rxnGeneMat');
-0114 
-0115 % It is already known from the previous commands that there are some
-0116 % unbalanced reactions in KEGG. Only use the balanced ones for the gap
-0117 % filling
-0118 balanceStructure=getElementalBalance(keggModel);
-0119 keggModel=removeReactions(keggModel,balanceStructure.balanceStatus~=1,true,true);
-0120 
-0121 % The function fillGaps with these settings will try to include reactions in
-0122 % order to have flux through all reactions in the model. There are other
-0123 % settings as well. The first flag says that production of all metabolites
-0124 % should be allowed.
-0125 params.relGap=0.6; %Lower number for a more exhaustive search
-0126 params.printReport=true;
-0127 [newConnected, cannotConnect, addedRxns, newModel, exitFlag]=fillGaps(model,keggModel,true,false,false,[],params);
-0128 
-0129 % The results show that fillGaps could connect around 29 reactions
-0130 % (newConnected) by including around 41 reactions from the KEGG model
-0131 % (addedRxns). Those should of course be checked manually to confirm that
-0132 % they exist in yeast, but in this tutorial it is assumed that all these
-0133 % reactions indeed occur in yeast.
-0134 
-0135 % Continue to improve the connectivity of the model by identifying
-0136 % metabolites that should be connected. A convenient way to get an overview
-0137 % of how connected the model is, and at the same time getting a lot of
-0138 % useful data, is to use gapReport. Note that it can take several to many
-0139 % hours to run, depending on the number of gaps in the model.
-0140 [noFluxRxns, noFluxRxnsRelaxed, subGraphs, notProducedMets, minToConnect,...
-0141     neededForProductionMat]=gapReport(newModel);
-0142 
-0143 % The results show that 532 from 1634 reactions cannot carry flux. Remember
-0144 % that an output is allowed for all metabolites, that is why it calculates
-0145 % 532 in both cases. 543 from 1617 metabolites cannot be synthesized from
-0146 % the precursors which are supplied. There are 6 subnetworks in the model,
-0147 % of which 1605 from 1617 metabolites belong to the first one.
-0148 
-0149 % It will also print something similar to:
-0150 
-0151 % To enable net production of all metabolites, a total of 322 metabolites
-0152 % must be connected
-0153 % Top 10 metabolites to connect:
-0154 %     1. Acyl-CoA[s] (connects 162 metabolites)
-0155 %     2. Thiamin diphosphate[s] (connects 17 metabolites)
-0156 %     3. G00003[s] (connects 14 metabolites)
-0157 %     4. Androstenediol[s] (connects 13 metabolites)
-0158 %     5. [Dihydrolipoyllysine-residue succinyltransferase] S-glutaryldihydrolipoyllysine[s] (connects 13 metabolites)
-0159 %     6. Selenomethionyl-tRNA(Met)[s] (connects 12 metabolites)
-0160 %     7. Retinyl ester[s] (connects 11 metabolites)
-0161 %     8. 1-Alkyl-2-acylglycerol[s] (connects 10 metabolites)
-0162 %     9. G00146[s] (connects 10 metabolites)
-0163 %     10. Progesterone[s] (connects 9 metabolites)
-0164 
-0165 % This is a very useful way of directing the gap-filling tasks to where they
-0166 % are of the greatest use. In this case it says that in order to have net
-0167 % production of all metabolites in the model from the simple inputs which
-0168 % have been defined (543 metabolites can currently not have net production)
-0169 % one needs to connect 322 unconnected metabolites in. However, by
-0170 % connecting only the top 10 in the list 271/543 (50%) of them will now be
-0171 % connected. When looking at the list one can see that the top ranking one
-0172 % is Acyl-CoA, which represents many different fatty acid chains. The second
-0173 % metabolite, thiamine disphosphate, is an enzyme co-factor. It turns out
-0174 % that yeast cannot grow on only the substrates that had been defined, but
-0175 % that it requires some other precursors for co-factor synthesis as well.
-0176 
-0177 % Add uptake reactions for the minimal media constituents needed for yeast
-0178 % to grow.
-0179 [~, J]=ismember({'4-Aminobenzoate';'Riboflavin';'Thiamine';'Biotin';'Folate';'Nicotinate';'Zymosterol';'Choline'},newModel.metNames);
-0180 [newModel, addedRxns]=addExchangeRxns(newModel,'in',J);
-0181 
-0182 % Rerun gapReport and use the output for targeting the gap-filling efforts.
-0183 % Note that only some info is printed; most of it is available in the output
-0184 % structures. Work like this in an iterative manner until the model is of
-0185 % sufficient quality.
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/tutorial/tutorial6.html b/doc/tutorial/tutorial6.html deleted file mode 100644 index e4ebff117..000000000 --- a/doc/tutorial/tutorial6.html +++ /dev/null @@ -1,208 +0,0 @@ - - - - Description of tutorial6 - - - - - - - - - -
Home > tutorial > tutorial6.m
- - - -

tutorial6 -

- -

PURPOSE ^

-
tutorial6
- -

SYNOPSIS ^

-
This is a script file.
- -

DESCRIPTION ^

-
 tutorial6
-   This exercise demonstrates how to reconstruct a combined draft GEM by
-   from KEGG and MetaCyc pathway databases. A combined model with the
-   comprehensive coverage of metabolic pathways is generated from
-   different de novo reconstruction approaches. The input is a FASTA
-   format file with whole-proteome sequences. The combined model is
-   subsequently used for refinement of existing high-quality model and
-   generation of a new version of GEM, by utilizing the manual curation
-   results. This tutorial is a showcase of the new features released in
-   RAVEN 2.0 through demonstrating the utilization of the newly developed
-   functions on GEM reconstruction and curation for Streptomyces
-   coelicolor strain A3(2). Users may apply this script as the template in
-   their own work for other organisms.
-   This refers to Tutorial 6 from "RAVEN tutorials.docx"
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 % tutorial6
-0002 %   This exercise demonstrates how to reconstruct a combined draft GEM by
-0003 %   from KEGG and MetaCyc pathway databases. A combined model with the
-0004 %   comprehensive coverage of metabolic pathways is generated from
-0005 %   different de novo reconstruction approaches. The input is a FASTA
-0006 %   format file with whole-proteome sequences. The combined model is
-0007 %   subsequently used for refinement of existing high-quality model and
-0008 %   generation of a new version of GEM, by utilizing the manual curation
-0009 %   results. This tutorial is a showcase of the new features released in
-0010 %   RAVEN 2.0 through demonstrating the utilization of the newly developed
-0011 %   functions on GEM reconstruction and curation for Streptomyces
-0012 %   coelicolor strain A3(2). Users may apply this script as the template in
-0013 %   their own work for other organisms.
-0014 %   This refers to Tutorial 6 from "RAVEN tutorials.docx"
-0015 
-0016 %Before reconstruction, a FASTA file with protein sequences of the target
-0017 %organism needs to be prepared. In this tutorial, all protein sequences of
-0018 %S. coelicolor A3(2) were downloaded from the NCBI genome database and
-0019 %provided in current folder (Sco_all_protein.faa). The description lines
-0020 %(starting with ">" character) of this FASTA file were modified by keeping
-0021 %only the locus tag (e.g. SCO6005), which is commonly used as the gene
-0022 %names in GEMs.
-0023 
-0024 %Generate a draft GEM from MetaCyc database. The first parameter is
-0025 %organismID and needs to be specified by user. The other parameters are set
-0026 %to exclude unbalanced and undetermined reactions, but keep transport
-0027 %reactions. The two parameters for homology search are set to the default
-0028 %values that have been optimized to capture the protein hits with both
-0029 %comprehensive coverage and the least false positives.
-0030 ScoMetaCycDraftModel=getMetaCycModelForOrganism('ScoMetaCyc','Sco_all_protein.faa',1);
-0031 
-0032 %Generate the two draft models from KEGG database. The first one is
-0033 %reconstructed from the genome information annotated by KEGG. Since KEGG
-0034 %provides genome annotations for over 5000 organisms, their GEMs can thus
-0035 %be generated without providing protein sequences while only using the
-0036 %organismID. The organisms with KEGG annotation and their associated ids
-0037 %(e.g. 'sco' for Streptomyces coelicolor) can be found from here:
-0038 %https://www.kegg.jp/kegg/catalog/org_list.html.
-0039 %Generate a draft model using KEGG annotation and exclude incomplete
-0040 %reactions and reactions with undefined stoichiometry
-0041 ScoKEGGAnnotation=getKEGGModelForOrganism('sco','','','',1,0,0);
-0042 
-0043 %Generate the second KEGG-based draft model based on sequence homology to
-0044 %KEGG Ortholog sequence clusters while excluding incomplete reactions and
-0045 %the ones with undefined stoichiometry. Type "help getKEGGModelForOrganism"
-0046 %to see the detailed instructions for the choice of different parameters.
-0047 %The default values for homology search are used because they have been
-0048 %optimized for the best performance.
-0049 ScoKEGGHomology=getKEGGModelForOrganism('ScoKEGGHMMs','Sco_all_protein.faa','prok90_kegg105','',1,0,0);
-0050 
-0051 %De novo reconstruction from MetaCyc should take about 10 minutes, while
-0052 %both reconstructions from KEGG may take up to 50-60 minutes in overall
-0053 %depending on the computer hardware and the system used. Given that KEGG
-0054 %and MetaCyc databases are formulated in different ways; KEGG relies on
-0055 %sequence-based annotation, while MetaCyc collects only experimentally
-0056 %verified pathways. Therefore, integration of MetaCyc- and KEGG-based draft
-0057 %models could have a better coverage of the metbolism for the target
-0058 %organism.
-0059 
-0060 %At first, the two KEGG-based models can be directly merged
-0061 ScoKEGGDraftModel=mergeModels({ScoKEGGAnnotation ScoKEGGHomology});
-0062 
-0063 disp(numel(ScoKEGGHomology.rxns)+numel(ScoKEGGAnnotation.rxns));
-0064 disp(numel(ScoKEGGDraftModel.rxns));
-0065 %By checking the reaction number, it can be seen that reaction number in
-0066 %the merged model equals adding up the reaction numbers in homology and
-0067 %annotation KEGG draft models. And there are duplicated reactions in this
-0068 %merged model.
-0069 
-0070 %Merge the duplicated reactions into one and combine multiple iso-enzymes
-0071 %into a single grRules. The expandModel and contractModel functions are
-0072 %utilised, see their instructions for details.
-0073 ScoKEGGDraftModel=expandModel(ScoKEGGDraftModel);
-0074 ScoKEGGDraftModel=contractModel(ScoKEGGDraftModel);
-0075 
-0076 %In the end, KEGG- and MetaCyc-based draft models can be further combined
-0077 %into an integrated GEM. This step is achieved by the function
-0078 %combineMetaCycKEGGModels, which firstly converts metabolite and reaction
-0079 %identifiers in the KEGG model into corresponding MetaCyc ids, and then
-0080 %detects duplications and keeps only unique reactions and metabolites that
-0081 %are mostly in MetaCyc identifiers.
-0082 ScoCombinedDraftModel=combineMetaCycKEGGModels(ScoMetaCycDraftModel, ScoKEGGDraftModel);
-0083 
-0084 %With this combined model, the existing iMK1208 model is refined by
-0085 %incorporating the new pathways/reactions that are found in the combined
-0086 %model but absent from the previous iMK1208 model. At the time of
-0087 %publication, a total of 398 reactions in the combined draft model were
-0088 %determined as new pathways based on manual curation results, which have
-0089 %been organized into TableS3. Load these manually selected reactions and
-0090 %their subSystems as the pre-processed array structure selectedNewRxns.
-0091 load('iMK1208+suppInfo.mat','selectedNewRxns');
-0092 disp(selectedNewRxns);
-0093 
-0094 %Generate a sub-model that includes only these new reactions. This is
-0095 %implemented by subtracting the other reactions from the combined model
-0096 %using function removeReactions
-0097 rxnsToRemove=setdiff(ScoCombinedDraftModel.rxns,selectedNewRxns.rxns);
-0098 newRxnSubModel=removeReactions(ScoCombinedDraftModel,rxnsToRemove,1,1);
-0099 
-0100 %Now this newRxnSubModel contains only these new reactions. It needs to be
-0101 %modified before merging with the iMK1208. Since these reactions are
-0102 %metabolic ones and can all be assigned to the cytoplasm compartment
-0103 newRxnSubModel.comps{1}='c';
-0104 newRxnSubModel.compNames{1}='Cytoplasm';
-0105 
-0106 %Amend to the genes and rxnGeneMat fields
-0107 newRxnSubModel.genes={};
-0108 for k=1:numel(newRxnSubModel.rxns)
-0109    newRxnSubModel.genes=[newRxnSubModel.genes;transpose(strsplit(newRxnSubModel.grRules{k},' or '))];
-0110 end
-0111 newRxnSubModel.genes=unique(newRxnSubModel.genes);
-0112 [~, newRxnSubModel.rxnGeneMat, ~]=standardizeGrRules(newRxnSubModel);
-0113 
-0114 %Since the newRxnSubModel is ready for incorportation, the iMK1208 model
-0115 %can be loaded for integration
-0116 load('iMK1208+suppInfo.mat','iMK1208');
-0117 
-0118 %It should be noted that the incompatible nomenclatures (especially the
-0119 %metabolite identifiers) used in different GEMs and databases led to a
-0120 %serious problem in model comparison, curation and integration. In order to
-0121 %properly integrate the iMK1208 with this sub-model, both models should be
-0122 %unified into the same name space, since the metabolites in the sub-model
-0123 %use MetaCyc identifiers that are different from the ones used in iMK1208
-0124 %model. TableS2 contains the results for database mining and intensive
-0125 %manual curation while associating these metabolite identifiers. Load
-0126 %these manually selected reactions and their subSystems as the
-0127 %pre-processed array structure metaCycMetsIniMK.
-0128 load('iMK1208+suppInfo.mat','metaCycMetsIniMK');
-0129 
-0130 %Replace the metabolites in the sub-model with the identifiers and names
-0131 %used in iMK1208 according to the mapping information in TableS2
-0132 %(metaCycMetsIniMK).
-0133 [a, b]=ismember(newRxnSubModel.mets,metaCycMetsIniMK);
-0134 I=find(a);
-0135 newRxnSubModel.mets=strcat(newRxnSubModel.mets,'_c');
-0136 newRxnSubModel.metNames(I)=iMK1208.metNames(b(I));
-0137 newRxnSubModel.mets(I)=iMK1208.mets(b(I));
-0138 
-0139 %The necessary issues for merging iMK1208 with the new reactions determined
-0140 %from de novo generated draft GEMs have been resolved. Those can be
-0141 %directly merged into the Sco4 model, which refers to the 4th major update
-0142 %of the GEM for Streptomyces coelicolor.
-0143 Sco4=mergeModels({iMK1208 newRxnSubModel});
-0144 
-0145 %Check out if the newly generated Sco4 could grow
-0146 sol=solveLP(Sco4);
-0147 disp(sol.f);
-0148 %The results indicate that this new model is functional
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/up.png b/doc/up.png deleted file mode 100644 index b348b9a1b19bd5030efd3df293d84a18b41ef6a4..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 162 zcmeAS@N?(olHy`uVBq!ia0vp^{2x4R4De - - - Description of emptyOrLogicalScalar - - - - - - - - - -
Home > utils > emptyOrLogicalScalar.m
- - - -

emptyOrLogicalScalar -

- -

PURPOSE ^

-
- -

SYNOPSIS ^

-
function emptyOrLogical(x)
- -

DESCRIPTION ^

-
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function emptyOrLogical(x)
-0002     if isempty(x)
-0003         return;
-0004     end
-0005     validateattributes(x, {'logical'}, {'scalar'});
-0006 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/utils/emptyOrTextOrCellOfText.html b/doc/utils/emptyOrTextOrCellOfText.html deleted file mode 100644 index 72298c9a3..000000000 --- a/doc/utils/emptyOrTextOrCellOfText.html +++ /dev/null @@ -1,90 +0,0 @@ - - - - Description of emptyOrTextOrCellOfText - - - - - - - - - -
Home > utils > emptyOrTextOrCellOfText.m
- - - -

emptyOrTextOrCellOfText -

- -

PURPOSE ^

-
Validate [] OR text scalar (char row or string scalar) OR cell array of such text.
- -

SYNOPSIS ^

-
function mustBeEmptyOrTextOrCellOfText(x)
- -

DESCRIPTION ^

-
 Validate [] OR text scalar (char row or string scalar) OR cell array of such text.
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function mustBeEmptyOrTextOrCellOfText(x)
-0002 % Validate [] OR text scalar (char row or string scalar) OR cell array of such text.
-0003 
-0004 % Allow explicit empty
-0005 if isempty(x)
-0006     return;
-0007 end
-0008 
-0009 % Allow a single text scalar
-0010 if ischar(x)
-0011     if ~isrow(x)
-0012         error('Text must be a character row vector, a string scalar, or empty.');
-0013     end
-0014     return;
-0015 elseif isstring(x)
-0016     if ~isscalar(x)
-0017         error('Text must be a string scalar, a character row vector, or empty.');
-0018     end
-0019     return;
-0020 end
-0021 
-0022 % Allow a cell array of text
-0023 if iscell(x)
-0024     for k = 1:numel(x)
-0025         v = x{k};
-0026         if ischar(v)
-0027             if ~isrow(v)   % '' is 1x0 char, which is a row -> allowed
-0028                 error('Each cell element must be a character row vector or a string scalar.');
-0029             end
-0030         elseif isstring(v)
-0031             if ~isscalar(v)  % "" is a scalar string -> allowed
-0032                 error('Each cell element must be a string scalar or a character row vector.');
-0033             end
-0034         else
-0035             error('Each cell element must be text (string scalar or character row vector).');
-0036         end
-0037     end
-0038     return;
-0039 end
-0040 
-0041 % Anything else is invalid
-0042 error('Value must be empty, a text value, or a cell array of text values.');
-0043 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/utils/emptyOrTextScalar.html b/doc/utils/emptyOrTextScalar.html deleted file mode 100644 index 7d53acd3c..000000000 --- a/doc/utils/emptyOrTextScalar.html +++ /dev/null @@ -1,59 +0,0 @@ - - - - Description of emptyOrTextScalar - - - - - - - - - -
Home > utils > emptyOrTextScalar.m
- - - -

emptyOrTextScalar -

- -

PURPOSE ^

-
- -

SYNOPSIS ^

-
function mustBeEmptyOrTextScalar(x)
- -

DESCRIPTION ^

-
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function mustBeEmptyOrTextScalar(x)
-0002     if isempty(x)
-0003         return;
-0004     end
-0005     if isstring(x)
-0006         if ~isscalar(x), error('Value must be a string scalar or empty.'); end
-0007     elseif ischar(x)
-0008         if ~isrow(x), error('Char input must be a row vector or empty.'); end
-0009     else
-0010         error('Value must be a string/char scalar or empty.');
-0011     end
-0012 end
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/utils/index.html b/doc/utils/index.html deleted file mode 100644 index 9a1637b6a..000000000 --- a/doc/utils/index.html +++ /dev/null @@ -1,29 +0,0 @@ - - - - Index for Directory utils - - - - - - - - - - -
< Master indexIndex for utils >
- -

Index for utils

- -

Matlab files in this directory:

- -
 emptyOrLogicalScalar
 emptyOrTextOrCellOfTextValidate [] OR text scalar (char row or string scalar) OR cell array of such text.
 emptyOrTextScalar
 runRAVENtestsrunRAVENtests
- - - - -
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/utils/runRAVENtests.html b/doc/utils/runRAVENtests.html deleted file mode 100644 index da9c79b70..000000000 --- a/doc/utils/runRAVENtests.html +++ /dev/null @@ -1,60 +0,0 @@ - - - - Description of runRAVENtests - - - - - - - - - -
Home > utils > runRAVENtests.m
- - - -

runRAVENtests -

- -

PURPOSE ^

-
runRAVENtests
- -

SYNOPSIS ^

-
function testResults = runRAVENtests
- -

DESCRIPTION ^

-
 runRAVENtests
-  Runs all unit tests found at RAVEN/test/unit_tests, and prints output in
-  command window.
- - -

CROSS-REFERENCE INFORMATION ^

-This function calls: -
    -
-This function is called by: -
    -
- - - - -

SOURCE CODE ^

-
0001 function testResults = runRAVENtests
-0002 % runRAVENtests
-0003 %  Runs all unit tests found at RAVEN/test/unit_tests, and prints output in
-0004 %  command window.
-0005 
-0006 ravenPath = findRAVENroot;
-0007 curwd = pwd;
-0008 cd(fullfile(ravenPath,'testing','unit_tests'));
-0009 testResults = runtests(struct2table(dir('*.m')).name);
-0010 
-0011 cd(curwd);
-
Generated by m2html © 2005
- - \ No newline at end of file diff --git a/doc/windows.png b/doc/windows.png deleted file mode 100644 index 6cec95b8815d3d5dab8c97c41c75197fdb014135..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 286 zcmV+(0pb3MP)4J#NJjgjrM8h9Te~(8G kcWyrh{e1gnl+pf{?#tSrFr=&ZY5)KL07*qoM6N<$f*5RoFaQ7m From 0092b8dfcfd3f1aca60e5d18b95cf7783e317d34 Mon Sep 17 00:00:00 2001 From: Eduard Kerkhoven Date: Wed, 30 Sep 2026 12:22:25 +0200 Subject: [PATCH 6/7] Restore and update documentation --- doc/INIT/INITStepDesc.html | 126 ++ doc/INIT/ftINIT.html | 580 +++++++ doc/INIT/ftINITFillGaps.html | 207 +++ doc/INIT/ftINITFillGapsForAllTasks.html | 462 ++++++ doc/INIT/ftINITFillGapsMILP.html | 312 ++++ doc/INIT/ftINITInternalAlg.html | 551 +++++++ doc/INIT/getExprForRxnScore.html | 85 ++ doc/INIT/getINITModel.html | 609 ++++++++ doc/INIT/getINITSteps.html | 210 +++ doc/INIT/groupRxnScores.html | 124 ++ doc/INIT/index.html | 29 + doc/INIT/mergeLinear.html | 281 ++++ doc/INIT/prepINITModel.html | 407 +++++ doc/INIT/removeLowScoreGenes.html | 372 +++++ doc/INIT/rescaleModelForINIT.html | 129 ++ doc/INIT/reverseRxns.html | 68 + doc/INIT/runINIT.html | 445 ++++++ doc/INIT/scoreComplexModel.html | 482 ++++++ doc/alpha.png | Bin 0 -> 273 bytes doc/c++.png | Bin 0 -> 327 bytes doc/c.png | Bin 0 -> 252 bytes doc/core/FSEOF.html | 224 +++ doc/core/addExchangeRxns.html | 166 ++ doc/core/addGenesRaven.html | 221 +++ doc/core/addMets.html | 472 ++++++ doc/core/addRxns.html | 846 +++++++++++ doc/core/addRxnsGenesMets.html | 274 ++++ doc/core/addTransport.html | 250 +++ doc/core/analyzeSampling.html | 250 +++ doc/core/buildEquation.html | 122 ++ doc/core/canConsume.html | 83 + doc/core/canProduce.html | 85 ++ doc/core/changeGrRules.html | 116 ++ doc/core/changeRxns.html | 249 +++ doc/core/checkModelStruct.html | 517 +++++++ doc/core/checkProduction.html | 242 +++ doc/core/checkRxn.html | 156 ++ doc/core/checkTasks.html | 351 +++++ doc/core/compareMultipleModels.html | 521 +++++++ doc/core/compareRxnsGenesMetsComps.html | 247 +++ doc/core/constructEquations.html | 182 +++ doc/core/constructS.html | 250 +++ doc/core/consumeSomething.html | 263 ++++ doc/core/contractModel.html | 251 +++ doc/core/convertCharArray.html | 84 ++ doc/core/convertToIrrev.html | 182 +++ doc/core/copyToComps.html | 175 +++ doc/core/deleteUnusedGenes.html | 111 ++ doc/core/dispEM.html | 115 ++ doc/core/expandModel.html | 212 +++ doc/core/fillGaps.html | 325 ++++ doc/core/findGeneDeletions.html | 293 ++++ doc/core/findRAVENroot.html | 78 + doc/core/fitParameters.html | 199 +++ doc/core/fitTasks.html | 409 +++++ doc/core/followChanged.html | 170 +++ doc/core/followFluxes.html | 109 ++ doc/core/gapReport.html | 193 +++ doc/core/generateNewIds.html | 123 ++ doc/core/getAllRxnsFromGenes.html | 96 ++ doc/core/getAllSubGraphs.html | 120 ++ doc/core/getAllowedBounds.html | 146 ++ doc/core/getElementalBalance.html | 215 +++ doc/core/getEssentialRxns.html | 126 ++ doc/core/getExchangeRxns.html | 170 +++ doc/core/getExpressionStructure.html | 180 +++ doc/core/getFluxZ.html | 120 ++ doc/core/getGenesFromGrRules.html | 141 ++ doc/core/getIndexes.html | 201 +++ doc/core/getMetsInComp.html | 80 + doc/core/getMinNrFluxes.html | 237 +++ doc/core/getModelFromHomology.html | 663 ++++++++ doc/core/getRxnsInComp.html | 100 ++ doc/core/getTransportRxns.html | 80 + doc/core/guessComposition.html | 247 +++ doc/core/haveFlux.html | 148 ++ doc/core/index.html | 29 + doc/core/makeSomething.html | 275 ++++ doc/core/mapCompartments.html | 214 +++ doc/core/mergeCompartments.html | 209 +++ doc/core/mergeModels.html | 720 +++++++++ doc/core/parallelPoolRAVEN.html | 123 ++ doc/core/parseFormulas.html | 318 ++++ doc/core/parseRxnEqu.html | 135 ++ doc/core/parseTaskList.html | 441 ++++++ doc/core/permuteModel.html | 228 +++ doc/core/predictLocalization.html | 1247 +++++++++++++++ doc/core/printFluxes.html | 270 ++++ doc/core/printModel.html | 147 ++ doc/core/printModelStats.html | 221 +++ doc/core/printOrange.html | 78 + doc/core/randomSampling.html | 317 ++++ doc/core/removeBadRxns.html | 357 +++++ doc/core/removeGenes.html | 194 +++ doc/core/removeMets.html | 198 +++ doc/core/removeReactions.html | 218 +++ doc/core/replaceMets.html | 226 +++ doc/core/reporterMetabolites.html | 274 ++++ doc/core/runDynamicFBA.html | 218 +++ doc/core/runPhenotypePhasePlane.html | 161 ++ doc/core/runProductionEnvelope.html | 127 ++ doc/core/runRobustnessAnalysis.html | 140 ++ doc/core/runSimpleOptKnock.html | 198 +++ doc/core/setExchangeBounds.html | 309 ++++ doc/core/setParam.html | 202 +++ doc/core/simplifyModel.html | 403 +++++ doc/core/sortModel.html | 249 +++ doc/core/standardizeGrRules.html | 236 +++ doc/demoicon.gif | Bin 0 -> 214 bytes doc/down.png | Bin 0 -> 133 bytes doc/doxysearch.php | 329 ++++ doc/external/combineMetaCycKEGGModels.html | 380 +++++ doc/external/getBlast.html | 267 ++++ doc/external/getBlastFromExcel.html | 185 +++ doc/external/getDiamond.html | 250 +++ doc/external/getWoLFScores.html | 113 ++ doc/external/index.html | 31 + doc/external/kegg/constructMultiFasta.html | 222 +++ doc/external/kegg/getGenesFromKEGG.html | 516 +++++++ .../kegg/getKEGGModelForOrganism.html | 1342 +++++++++++++++++ doc/external/kegg/getMetsFromKEGG.html | 391 +++++ doc/external/kegg/getModelFromKEGG.html | 381 +++++ doc/external/kegg/getPhylDist.html | 208 +++ doc/external/kegg/getRxnsFromKEGG.html | 620 ++++++++ doc/external/kegg/getWSLpath.html | 83 + doc/external/kegg/index.html | 31 + doc/external/makeFakeBlastStructure.html | 129 ++ doc/external/metacyc/addSpontaneousRxns.html | 157 ++ .../metacyc/getEnzymesFromMetaCyc.html | 366 +++++ .../metacyc/getMetaCycModelForOrganism.html | 350 +++++ doc/external/metacyc/getMetsFromMetaCyc.html | 362 +++++ doc/external/metacyc/getModelFromMetaCyc.html | 261 ++++ doc/external/metacyc/getRxnsFromMetaCyc.html | 629 ++++++++ doc/external/metacyc/index.html | 31 + doc/external/metacyc/linkMetaCycKEGGRxns.html | 159 ++ doc/external/parseScores.html | 189 +++ doc/external/updateDocumentation.html | 95 ++ doc/fortran.png | Bin 0 -> 265 bytes doc/hp.png | Bin 0 -> 255 bytes doc/hpa/index.html | 29 + doc/hpa/parseHPA.html | 188 +++ doc/hpa/parseHPArna.html | 136 ++ doc/hpa/scoreModel.html | 428 ++++++ doc/index.html | 81 + doc/installation/addRavenToUserPath.html | 98 ++ doc/installation/checkFunctionUniqueness.html | 161 ++ doc/installation/checkInstallation.html | 501 ++++++ doc/installation/index.html | 29 + doc/installation/removeRavenFromPath.html | 97 ++ doc/io/SBMLFromExcel.html | 94 ++ doc/io/addJavaPaths.html | 76 + doc/io/checkFileExistence.html | 152 ++ doc/io/cleanSheet.html | 170 +++ doc/io/closeModel.html | 115 ++ doc/io/exportForGit.html | 244 +++ doc/io/exportModel.html | 868 +++++++++++ doc/io/exportModelToSIF.html | 148 ++ doc/io/exportToExcelFormat.html | 459 ++++++ doc/io/exportToTabDelimited.html | 407 +++++ doc/io/getFullPath.html | 439 ++++++ doc/io/getMD5Hash.html | 118 ++ doc/io/getToolboxVersion.html | 146 ++ doc/io/importExcelModel.html | 1051 +++++++++++++ doc/io/importModel.html | 1263 ++++++++++++++++ doc/io/index.html | 29 + doc/io/loadSheet.html | 130 ++ doc/io/loadWorkbook.html | 119 ++ doc/io/readYAMLmodel.html | 750 +++++++++ doc/io/sortIdentifiers.html | 83 + doc/io/startup.html | 49 + doc/io/writeSheet.html | 211 +++ doc/io/writeYAMLmodel.html | 448 ++++++ doc/left.png | Bin 0 -> 136 bytes doc/legacy/core/changeGeneAssoc.html | 117 ++ doc/legacy/core/index.html | 29 + .../constructPathwayFromCelldesigner.html | 590 ++++++++ doc/legacy/external/index.html | 29 + doc/linux.png | Bin 0 -> 272 bytes doc/m2html.css | 90 ++ doc/matlabicon.gif | Bin 0 -> 574 bytes doc/mex.png | Bin 0 -> 242 bytes doc/pathway/colorPathway.html | 143 ++ doc/pathway/getPathwayDimensions.html | 109 ++ doc/pathway/index.html | 29 + doc/pathway/mapPathwayRxnNames.html | 98 ++ doc/pathway/markPathwayWithExpression.html | 118 ++ doc/pathway/markPathwayWithFluxes.html | 111 ++ doc/pathway/trimPathway.html | 146 ++ doc/pcode.png | Bin 0 -> 212 bytes doc/plotting/colorSubsystem.html | 121 ++ doc/plotting/drawMap.html | 211 +++ doc/plotting/drawPathway.html | 481 ++++++ doc/plotting/getColorCodes.html | 208 +++ doc/plotting/getObjectiveString.html | 114 ++ doc/plotting/index.html | 29 + doc/plotting/plotAdditionalInfo.html | 189 +++ doc/plotting/plotLabels.html | 76 + doc/plotting/setColorToMapRxns.html | 659 ++++++++ doc/plotting/setOmicDataToRxns.html | 103 ++ doc/plotting/setTitle.html | 70 + doc/right.png | Bin 0 -> 136 bytes doc/sgi.png | Bin 0 -> 263 bytes doc/simulinkicon.gif | Bin 0 -> 977 bytes doc/solaris.png | Bin 0 -> 286 bytes doc/solver/checkSolution.html | 83 + doc/solver/index.html | 29 + doc/solver/optimizeProb.html | 344 +++++ doc/solver/qMOMA.html | 150 ++ doc/solver/setRavenSolver.html | 119 ++ doc/solver/solveLP.html | 310 ++++ doc/solver/solveQP.html | 127 ++ .../addIdentifierPrefix.html | 128 ++ doc/struct_conversion/editMiriam.html | 200 +++ doc/struct_conversion/extractMiriam.html | 156 ++ doc/struct_conversion/index.html | 29 + doc/struct_conversion/ravenCobraWrapper.html | 528 +++++++ .../removeIdentifierPrefix.html | 143 ++ .../standardizeModelFieldOrder.html | 123 ++ doc/testing/manual_tests/ManualINITTests.html | 170 +++ doc/testing/manual_tests/index.html | 29 + doc/testing/unit_tests/blastPlusTests.html | 108 ++ doc/testing/unit_tests/cdhitTests.html | 129 ++ doc/testing/unit_tests/checkTasksTests.html | 138 ++ doc/testing/unit_tests/diamondTests.html | 107 ++ .../unit_tests/fillGapsLargeTests.html | 146 ++ .../unit_tests/fillGapsSmallTests.html | 144 ++ doc/testing/unit_tests/hmmerTests.html | 203 +++ doc/testing/unit_tests/importExportTests.html | 153 ++ doc/testing/unit_tests/index.html | 31 + doc/testing/unit_tests/mafftTests.html | 117 ++ doc/testing/unit_tests/mergeModelsTests.html | 159 ++ doc/testing/unit_tests/miriamTests.html | 86 ++ .../unit_tests/modelAbilitiesTests.html | 173 +++ .../unit_tests/modelConversionTests.html | 75 + .../unit_tests/modelCurationTests.html | 543 +++++++ doc/testing/unit_tests/modelSortingTests.html | 118 ++ doc/testing/unit_tests/solverTests.html | 192 +++ doc/testing/unit_tests/tinitTests.html | 665 ++++++++ doc/tutorial/index.html | 31 + doc/tutorial/tutorial1.html | 194 +++ doc/tutorial/tutorial2.html | 73 + doc/tutorial/tutorial2_solutions.html | 67 + doc/tutorial/tutorial3.html | 134 ++ doc/tutorial/tutorial3_solutions.html | 166 ++ doc/tutorial/tutorial4.html | 84 ++ doc/tutorial/tutorial4_solutions.html | 207 +++ doc/tutorial/tutorial5.html | 252 ++++ doc/tutorial/tutorial6.html | 208 +++ doc/up.png | Bin 0 -> 162 bytes doc/utils/emptyOrLogicalScalar.html | 53 + doc/utils/emptyOrTextOrCellOfText.html | 90 ++ doc/utils/emptyOrTextScalar.html | 59 + doc/utils/index.html | 29 + doc/utils/runRAVENtests.html | 60 + doc/windows.png | Bin 0 -> 286 bytes 255 files changed, 55273 insertions(+) create mode 100644 doc/INIT/INITStepDesc.html create mode 100644 doc/INIT/ftINIT.html create mode 100644 doc/INIT/ftINITFillGaps.html create mode 100644 doc/INIT/ftINITFillGapsForAllTasks.html create mode 100644 doc/INIT/ftINITFillGapsMILP.html create mode 100644 doc/INIT/ftINITInternalAlg.html create mode 100644 doc/INIT/getExprForRxnScore.html create mode 100644 doc/INIT/getINITModel.html create mode 100644 doc/INIT/getINITSteps.html create mode 100644 doc/INIT/groupRxnScores.html create mode 100644 doc/INIT/index.html create mode 100644 doc/INIT/mergeLinear.html create mode 100644 doc/INIT/prepINITModel.html create mode 100644 doc/INIT/removeLowScoreGenes.html create mode 100644 doc/INIT/rescaleModelForINIT.html create mode 100644 doc/INIT/reverseRxns.html create mode 100644 doc/INIT/runINIT.html create mode 100644 doc/INIT/scoreComplexModel.html create mode 100644 doc/alpha.png create mode 100644 doc/c++.png create mode 100644 doc/c.png create mode 100644 doc/core/FSEOF.html create mode 100644 doc/core/addExchangeRxns.html create mode 100644 doc/core/addGenesRaven.html create mode 100644 doc/core/addMets.html create mode 100644 doc/core/addRxns.html create mode 100644 doc/core/addRxnsGenesMets.html create mode 100644 doc/core/addTransport.html create mode 100644 doc/core/analyzeSampling.html create mode 100644 doc/core/buildEquation.html create mode 100644 doc/core/canConsume.html create mode 100644 doc/core/canProduce.html create mode 100644 doc/core/changeGrRules.html create mode 100644 doc/core/changeRxns.html create mode 100644 doc/core/checkModelStruct.html create mode 100644 doc/core/checkProduction.html create mode 100644 doc/core/checkRxn.html create mode 100644 doc/core/checkTasks.html create mode 100644 doc/core/compareMultipleModels.html create mode 100644 doc/core/compareRxnsGenesMetsComps.html create mode 100644 doc/core/constructEquations.html create mode 100644 doc/core/constructS.html create mode 100644 doc/core/consumeSomething.html create mode 100644 doc/core/contractModel.html create mode 100644 doc/core/convertCharArray.html create mode 100644 doc/core/convertToIrrev.html create mode 100644 doc/core/copyToComps.html create mode 100644 doc/core/deleteUnusedGenes.html create mode 100644 doc/core/dispEM.html create mode 100644 doc/core/expandModel.html create mode 100644 doc/core/fillGaps.html create mode 100644 doc/core/findGeneDeletions.html create mode 100644 doc/core/findRAVENroot.html create mode 100644 doc/core/fitParameters.html create mode 100644 doc/core/fitTasks.html create mode 100644 doc/core/followChanged.html create mode 100644 doc/core/followFluxes.html create mode 100644 doc/core/gapReport.html create mode 100644 doc/core/generateNewIds.html create mode 100644 doc/core/getAllRxnsFromGenes.html create mode 100644 doc/core/getAllSubGraphs.html create mode 100644 doc/core/getAllowedBounds.html create mode 100644 doc/core/getElementalBalance.html create mode 100644 doc/core/getEssentialRxns.html create mode 100644 doc/core/getExchangeRxns.html create mode 100644 doc/core/getExpressionStructure.html create mode 100644 doc/core/getFluxZ.html create mode 100644 doc/core/getGenesFromGrRules.html create mode 100644 doc/core/getIndexes.html create mode 100644 doc/core/getMetsInComp.html create mode 100644 doc/core/getMinNrFluxes.html create mode 100644 doc/core/getModelFromHomology.html create mode 100644 doc/core/getRxnsInComp.html create mode 100644 doc/core/getTransportRxns.html create mode 100644 doc/core/guessComposition.html create mode 100644 doc/core/haveFlux.html create mode 100644 doc/core/index.html create mode 100644 doc/core/makeSomething.html create mode 100644 doc/core/mapCompartments.html create mode 100644 doc/core/mergeCompartments.html create mode 100644 doc/core/mergeModels.html create mode 100644 doc/core/parallelPoolRAVEN.html create mode 100644 doc/core/parseFormulas.html create mode 100644 doc/core/parseRxnEqu.html create mode 100644 doc/core/parseTaskList.html create mode 100644 doc/core/permuteModel.html create mode 100644 doc/core/predictLocalization.html create mode 100644 doc/core/printFluxes.html create mode 100644 doc/core/printModel.html create mode 100644 doc/core/printModelStats.html create mode 100644 doc/core/printOrange.html create mode 100644 doc/core/randomSampling.html create mode 100644 doc/core/removeBadRxns.html create mode 100644 doc/core/removeGenes.html create mode 100644 doc/core/removeMets.html create mode 100644 doc/core/removeReactions.html create mode 100644 doc/core/replaceMets.html create mode 100644 doc/core/reporterMetabolites.html create mode 100644 doc/core/runDynamicFBA.html create mode 100644 doc/core/runPhenotypePhasePlane.html create mode 100644 doc/core/runProductionEnvelope.html create mode 100644 doc/core/runRobustnessAnalysis.html create mode 100644 doc/core/runSimpleOptKnock.html create mode 100644 doc/core/setExchangeBounds.html create mode 100644 doc/core/setParam.html create mode 100644 doc/core/simplifyModel.html create mode 100644 doc/core/sortModel.html create mode 100644 doc/core/standardizeGrRules.html create mode 100644 doc/demoicon.gif create mode 100644 doc/down.png create mode 100644 doc/doxysearch.php create mode 100644 doc/external/combineMetaCycKEGGModels.html create mode 100644 doc/external/getBlast.html create mode 100644 doc/external/getBlastFromExcel.html create mode 100644 doc/external/getDiamond.html create mode 100644 doc/external/getWoLFScores.html create mode 100644 doc/external/index.html create mode 100644 doc/external/kegg/constructMultiFasta.html create mode 100644 doc/external/kegg/getGenesFromKEGG.html create mode 100644 doc/external/kegg/getKEGGModelForOrganism.html create mode 100644 doc/external/kegg/getMetsFromKEGG.html create mode 100644 doc/external/kegg/getModelFromKEGG.html create mode 100644 doc/external/kegg/getPhylDist.html create mode 100644 doc/external/kegg/getRxnsFromKEGG.html create mode 100644 doc/external/kegg/getWSLpath.html create mode 100644 doc/external/kegg/index.html create mode 100644 doc/external/makeFakeBlastStructure.html create mode 100644 doc/external/metacyc/addSpontaneousRxns.html create mode 100644 doc/external/metacyc/getEnzymesFromMetaCyc.html create mode 100644 doc/external/metacyc/getMetaCycModelForOrganism.html create mode 100644 doc/external/metacyc/getMetsFromMetaCyc.html create mode 100644 doc/external/metacyc/getModelFromMetaCyc.html create mode 100644 doc/external/metacyc/getRxnsFromMetaCyc.html create mode 100644 doc/external/metacyc/index.html create mode 100644 doc/external/metacyc/linkMetaCycKEGGRxns.html create mode 100644 doc/external/parseScores.html create mode 100644 doc/external/updateDocumentation.html create mode 100644 doc/fortran.png create mode 100644 doc/hp.png create mode 100644 doc/hpa/index.html create mode 100644 doc/hpa/parseHPA.html create mode 100644 doc/hpa/parseHPArna.html create mode 100644 doc/hpa/scoreModel.html create mode 100644 doc/index.html create mode 100644 doc/installation/addRavenToUserPath.html create mode 100644 doc/installation/checkFunctionUniqueness.html create mode 100644 doc/installation/checkInstallation.html create mode 100644 doc/installation/index.html create mode 100644 doc/installation/removeRavenFromPath.html create mode 100644 doc/io/SBMLFromExcel.html create mode 100644 doc/io/addJavaPaths.html create mode 100644 doc/io/checkFileExistence.html create mode 100644 doc/io/cleanSheet.html create mode 100644 doc/io/closeModel.html create mode 100644 doc/io/exportForGit.html create mode 100644 doc/io/exportModel.html create mode 100644 doc/io/exportModelToSIF.html create mode 100644 doc/io/exportToExcelFormat.html create mode 100644 doc/io/exportToTabDelimited.html create mode 100644 doc/io/getFullPath.html create mode 100644 doc/io/getMD5Hash.html create mode 100644 doc/io/getToolboxVersion.html create mode 100644 doc/io/importExcelModel.html create mode 100644 doc/io/importModel.html create mode 100644 doc/io/index.html create mode 100644 doc/io/loadSheet.html create mode 100644 doc/io/loadWorkbook.html create mode 100644 doc/io/readYAMLmodel.html create mode 100644 doc/io/sortIdentifiers.html create mode 100644 doc/io/startup.html create mode 100644 doc/io/writeSheet.html create mode 100644 doc/io/writeYAMLmodel.html create mode 100644 doc/left.png create mode 100644 doc/legacy/core/changeGeneAssoc.html create mode 100644 doc/legacy/core/index.html create mode 100644 doc/legacy/external/constructPathwayFromCelldesigner.html create mode 100644 doc/legacy/external/index.html create mode 100644 doc/linux.png create mode 100644 doc/m2html.css create mode 100644 doc/matlabicon.gif create mode 100644 doc/mex.png create mode 100644 doc/pathway/colorPathway.html create mode 100644 doc/pathway/getPathwayDimensions.html create mode 100644 doc/pathway/index.html create mode 100644 doc/pathway/mapPathwayRxnNames.html create mode 100644 doc/pathway/markPathwayWithExpression.html create mode 100644 doc/pathway/markPathwayWithFluxes.html create mode 100644 doc/pathway/trimPathway.html create mode 100644 doc/pcode.png create mode 100644 doc/plotting/colorSubsystem.html create mode 100644 doc/plotting/drawMap.html create mode 100644 doc/plotting/drawPathway.html create mode 100644 doc/plotting/getColorCodes.html create mode 100644 doc/plotting/getObjectiveString.html create mode 100644 doc/plotting/index.html create mode 100644 doc/plotting/plotAdditionalInfo.html create mode 100644 doc/plotting/plotLabels.html create mode 100644 doc/plotting/setColorToMapRxns.html create mode 100644 doc/plotting/setOmicDataToRxns.html create mode 100644 doc/plotting/setTitle.html create mode 100644 doc/right.png create mode 100644 doc/sgi.png create mode 100644 doc/simulinkicon.gif create mode 100644 doc/solaris.png create mode 100644 doc/solver/checkSolution.html create mode 100644 doc/solver/index.html create mode 100644 doc/solver/optimizeProb.html create mode 100644 doc/solver/qMOMA.html create mode 100644 doc/solver/setRavenSolver.html create mode 100644 doc/solver/solveLP.html create mode 100644 doc/solver/solveQP.html create mode 100644 doc/struct_conversion/addIdentifierPrefix.html create mode 100644 doc/struct_conversion/editMiriam.html create mode 100644 doc/struct_conversion/extractMiriam.html create mode 100644 doc/struct_conversion/index.html create mode 100644 doc/struct_conversion/ravenCobraWrapper.html create mode 100644 doc/struct_conversion/removeIdentifierPrefix.html create mode 100644 doc/struct_conversion/standardizeModelFieldOrder.html create mode 100644 doc/testing/manual_tests/ManualINITTests.html create mode 100644 doc/testing/manual_tests/index.html create mode 100644 doc/testing/unit_tests/blastPlusTests.html create mode 100644 doc/testing/unit_tests/cdhitTests.html create mode 100644 doc/testing/unit_tests/checkTasksTests.html create mode 100644 doc/testing/unit_tests/diamondTests.html create mode 100644 doc/testing/unit_tests/fillGapsLargeTests.html create mode 100644 doc/testing/unit_tests/fillGapsSmallTests.html create mode 100644 doc/testing/unit_tests/hmmerTests.html create mode 100644 doc/testing/unit_tests/importExportTests.html create mode 100644 doc/testing/unit_tests/index.html create mode 100644 doc/testing/unit_tests/mafftTests.html create mode 100644 doc/testing/unit_tests/mergeModelsTests.html create mode 100644 doc/testing/unit_tests/miriamTests.html create mode 100644 doc/testing/unit_tests/modelAbilitiesTests.html create mode 100644 doc/testing/unit_tests/modelConversionTests.html create mode 100644 doc/testing/unit_tests/modelCurationTests.html create mode 100644 doc/testing/unit_tests/modelSortingTests.html create mode 100644 doc/testing/unit_tests/solverTests.html create mode 100644 doc/testing/unit_tests/tinitTests.html create mode 100644 doc/tutorial/index.html create mode 100644 doc/tutorial/tutorial1.html create mode 100644 doc/tutorial/tutorial2.html create mode 100644 doc/tutorial/tutorial2_solutions.html create mode 100644 doc/tutorial/tutorial3.html create mode 100644 doc/tutorial/tutorial3_solutions.html create mode 100644 doc/tutorial/tutorial4.html create mode 100644 doc/tutorial/tutorial4_solutions.html create mode 100644 doc/tutorial/tutorial5.html create mode 100644 doc/tutorial/tutorial6.html create mode 100644 doc/up.png create mode 100644 doc/utils/emptyOrLogicalScalar.html create mode 100644 doc/utils/emptyOrTextOrCellOfText.html create mode 100644 doc/utils/emptyOrTextScalar.html create mode 100644 doc/utils/index.html create mode 100644 doc/utils/runRAVENtests.html create mode 100644 doc/windows.png diff --git a/doc/INIT/INITStepDesc.html b/doc/INIT/INITStepDesc.html new file mode 100644 index 000000000..113533f71 --- /dev/null +++ b/doc/INIT/INITStepDesc.html @@ -0,0 +1,126 @@ + + + + Description of INITStepDesc + + + + + + + + + +
Home > INIT > INITStepDesc.m
+ + + +

INITStepDesc +

+ +

PURPOSE ^

+
+ +

SYNOPSIS ^

+
This is a script file.
+ +

DESCRIPTION ^

+
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 classdef INITStepDesc
+0002 % Describes a step in the ftINIT algorithm. A cell array of objects of this
+0003 % class is used as input to ftINIT to specify how the algorithm should be run.
+0004    properties
+0005       PosRevOff
+0006       AllowMetSecr
+0007       HowToUsePrevResults %'ignore', 'exclude', 'essential'
+0008       RxnsToIgnoreMask %Specifies reactions to leave outside the problem in
+0009                        %the MILP.
+0010                        % [b1,b2,b3,b4,b5,b6,b7,b8], bx is either 0 or 1,
+0011                        % where 1 means that the group is excluded.
+0012                        % b1 - Exchange rxns
+0013                        % b2 - Import rxns without GPRs (from s into the cell)
+0014                        % b3 - Simple transport reactions without GPRs (moves one metabolite between compartments)
+0015                        % b4 - Advanced transport reactions without GPRs (moves metabolites between compartments, more complex function such as antiporter)
+0016                        % b5 - Spontaneous reactions
+0017                        % b6 - Reactions in the s compartment without GPRs
+0018                        % b7 - Customly specified rxns (sent in when generating prepData)
+0019                        % b8 - All rxns without GPRs
+0020 
+0021       MetsToIgnore % Structure describing mets that can be removed from the model
+0022                    % before running ftINIT, such as water etc.
+0023                    % .simpleMets
+0024                    %      .mets        Names of metabolites to remove
+0025                    %      .compsToKeep Compartments for which metabolites should be kept.
+0026       MILPParams %Cell array of MILPparams - dictates how many iterations that will be run in this step.
+0027                  %Typically, MIPGap and TimeLimit is specified. ftINIT additionally
+0028                  %defaults Threads to 1 (single-threaded Gurobi) for determinism;
+0029                  %set Threads here to override (0 = use all cores).
+0030       AbsMIPGaps %If the objective is close to zero, a percentage of that is very small.
+0031                  %Therefore, also set an absolut value for this (typically 10 or 20).
+0032                  %For practical reasons, the first number is not used
+0033    end
+0034    methods
+0035       function obj = INITStepDesc(posRevOff_, AllowMetSecr_, howToUsePrevResults_, rxnsToIgnoreMask_, metsToIgnore_, MILPParams_, absMIPGaps_)
+0036          if nargin > 0
+0037             obj.PosRevOff = posRevOff_;
+0038          else
+0039             obj.PosRevOff = false;
+0040          end
+0041          if nargin > 1
+0042             obj.AllowMetSecr = AllowMetSecr_;
+0043          else
+0044             obj.AllowMetSecr = false;
+0045          end
+0046          if nargin > 2
+0047             obj.HowToUsePrevResults = howToUsePrevResults_;
+0048          else
+0049             obj.HowToUsePrevResults = 'essential';
+0050          end
+0051          if nargin > 3
+0052             obj.RxnsToIgnoreMask = rxnsToIgnoreMask_;
+0053          else
+0054             obj.RxnsToIgnoreMask = [1;0;0;0;0;0;0;0];
+0055          end
+0056          if nargin > 4
+0057             obj.MetsToIgnore = metsToIgnore_;
+0058          else
+0059             obj.MetsToIgnore = [1;0;0;0;0;0;0;0];
+0060          end
+0061          if nargin > 5
+0062             obj.MILPParams = MILPParams_;
+0063          else
+0064             params = struct();
+0065             params.TimeLimit = 5000;
+0066             params.MIPGap = 0.0004;            
+0067             obj.MILPParams = {params};
+0068          end
+0069          
+0070          if nargin > 6
+0071             obj.AbsMIPGaps = absMIPGaps_;
+0072          else
+0073             obj.AbsMIPGaps = 10;            
+0074          end
+0075       end
+0076    end
+0077 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/INIT/ftINIT.html b/doc/INIT/ftINIT.html new file mode 100644 index 000000000..6133e894d --- /dev/null +++ b/doc/INIT/ftINIT.html @@ -0,0 +1,580 @@ + + + + Description of ftINIT + + + + + + + + + +
Home > INIT > ftINIT.m
+ + + +

ftINIT +

+ +

PURPOSE ^

+
ftINIT
+ +

SYNOPSIS ^

+
function [model, metProduction, addedRxnsForTasks, deletedRxnsInINIT, fullMipRes] = ftINIT(prepData, tissue, celltype, hpaData, transcrData, metabolomicsData, INITSteps, removeGenes, useScoresForTasks, paramsFT, verbose)
+ +

DESCRIPTION ^

+
 ftINIT
+   Main function for generates a model using the ftINIT algorithm, based 
+   on proteomics and/or transcriptomics and/or metabolomics and/or metabolic 
+   tasks. The algorithm is not designed for running with metabolomics only.
+   The function prepINITModel needs to be run first for the template
+   model (such as the generic Human-GEM), but only need to be run once. This
+   function precalculates things independent of the omics to speed up the model
+   generation process, and outputs the prepData, which is input to this function.
+
+   prepData            The prepdata for the model.
+   tissue              tissue to score for. Should exist in either
+                       hpaData.tissues or transcrData.tissues
+   celltype            cell type to score for. Should exist in either
+                       hpaData.celltypes or transcrData.celltypes for this
+                       tissue (optional, default is to use the max values
+                       among all the cell types for the tissue.
+   hpaData             HPA data structure from parseHPA (optional if transcrData
+                       is supplied, default [])
+   transcrData         gene expression data structure (optional if hpaData is
+                       supplied, default []). Used to be called arrayData.
+       genes           cell array with the unique gene names
+       tissues         cell array with the tissue names. The list may not
+                       be unique, as there can be multiple cell types per
+                       tissue.
+       celltypes       cell array with the cell type names for each tissue
+       levels          GENESxTISSUES array with the expression level for
+                       each gene in each tissue/celltype. NaN should be
+                       used when no measurement was performed
+       threshold       a single value or a vector of gene expression 
+                       thresholds, above which genes are considered to be
+                       "expressed". default = 1(optional, by default, the mean expression
+                       levels of each gene across all tissues in transcrData
+                       will be used as the threshold values)
+       singleCells     binary value selecting whether to use the
+                       single-cell algorithm to identify expressed genes.
+                       If used, specify cell subpopulations in CELLTYPES
+                       (optional, default [])
+       plotResults     true if single cell probability distributions
+                       should be plotted (optional, default = false)
+   metabolomicsData    cell array with metabolite names that the model
+                       should produce (optional, default [])
+   INITSteps           Specifies the steps in the algorithm. For more info,
+                       see INITStepDesc and getINITSteps. 
+                       (optional, default getINITSteps(), which is the standard ftINIT).
+   removeGenes         if true, low-abundance genes will be removed from
+                       grRules, unless they are the only gene associated 
+                       with a reaction, or a subunit of an enzyme complex
+                       (see "removeLowScoreGenes" function for details).
+                       If false, grRules will not be modified; however,
+                       genes that were associated only with removed 
+                       reactions will not be present in the final model.
+                       (optional, default true).
+   useScoresForTasks   true if the calculated reaction scored should be 
+                       used as weights when fitting to tasks (optional, default
+                       true)
+   paramsFT            *obsolete option*
+   verbose             if true, the MILP progression will be shown. 
+                       (optional, default false)
+
+   model                   the resulting model structure
+   metProduction           array that indicates which of the
+                           metabolites in metabolomicsData that could be
+                           produced. Note that this is before the
+                           gap-filling process to enable defined tasks. To
+                           see which metabolites that can be produced in
+                           the final model, use canProduce.
+                           -2: metabolite name not found in model
+                           -1: metabolite found, but it could not be produced
+                           1: metabolite could be produced
+   addedRxnsForTasks       cell array of the reactions which were added in
+                           order to perform the tasks
+   deletedRxnsInINIT       cell array of reactions deleted because they
+                           could not carry flux (INIT requires a
+                           functional input model)
+   fullMipRes              The solver results from the last MILP step run
+
+   This is the main function for automatic reconstruction of models based
+   on the ftINIT algorithm (). 
+
+   NOTE: Exchange metabolites should normally not be removed from the model
+   when using this approach, since checkTasks/fitTasks rely on putting specific
+   constraints for each task. The INIT algorithm will remove exchange metabolites
+   if any are present. Use importModel(file,false) to import a model with
+   exchange metabolites remaining.
+
+ Usage: [model, metProduction, addedRxnsForTasks, deletedRxnsInINIT, ...
+               fullMipRes] = ...
+               ftINIT(prepData, tissue, celltype, hpaData, transcrData, ...
+               metabolomicsData, INITSteps, removeGenes, useScoresForTasks, ...
+               paramsFT);
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 function [model, metProduction, addedRxnsForTasks, deletedRxnsInINIT, fullMipRes] = ftINIT(prepData, tissue, celltype, hpaData, transcrData, metabolomicsData, INITSteps, removeGenes, useScoresForTasks, paramsFT, verbose)
+0002 % ftINIT
+0003 %   Main function for generates a model using the ftINIT algorithm, based
+0004 %   on proteomics and/or transcriptomics and/or metabolomics and/or metabolic
+0005 %   tasks. The algorithm is not designed for running with metabolomics only.
+0006 %   The function prepINITModel needs to be run first for the template
+0007 %   model (such as the generic Human-GEM), but only need to be run once. This
+0008 %   function precalculates things independent of the omics to speed up the model
+0009 %   generation process, and outputs the prepData, which is input to this function.
+0010 %
+0011 %   prepData            The prepdata for the model.
+0012 %   tissue              tissue to score for. Should exist in either
+0013 %                       hpaData.tissues or transcrData.tissues
+0014 %   celltype            cell type to score for. Should exist in either
+0015 %                       hpaData.celltypes or transcrData.celltypes for this
+0016 %                       tissue (optional, default is to use the max values
+0017 %                       among all the cell types for the tissue.
+0018 %   hpaData             HPA data structure from parseHPA (optional if transcrData
+0019 %                       is supplied, default [])
+0020 %   transcrData         gene expression data structure (optional if hpaData is
+0021 %                       supplied, default []). Used to be called arrayData.
+0022 %       genes           cell array with the unique gene names
+0023 %       tissues         cell array with the tissue names. The list may not
+0024 %                       be unique, as there can be multiple cell types per
+0025 %                       tissue.
+0026 %       celltypes       cell array with the cell type names for each tissue
+0027 %       levels          GENESxTISSUES array with the expression level for
+0028 %                       each gene in each tissue/celltype. NaN should be
+0029 %                       used when no measurement was performed
+0030 %       threshold       a single value or a vector of gene expression
+0031 %                       thresholds, above which genes are considered to be
+0032 %                       "expressed". default = 1(optional, by default, the mean expression
+0033 %                       levels of each gene across all tissues in transcrData
+0034 %                       will be used as the threshold values)
+0035 %       singleCells     binary value selecting whether to use the
+0036 %                       single-cell algorithm to identify expressed genes.
+0037 %                       If used, specify cell subpopulations in CELLTYPES
+0038 %                       (optional, default [])
+0039 %       plotResults     true if single cell probability distributions
+0040 %                       should be plotted (optional, default = false)
+0041 %   metabolomicsData    cell array with metabolite names that the model
+0042 %                       should produce (optional, default [])
+0043 %   INITSteps           Specifies the steps in the algorithm. For more info,
+0044 %                       see INITStepDesc and getINITSteps.
+0045 %                       (optional, default getINITSteps(), which is the standard ftINIT).
+0046 %   removeGenes         if true, low-abundance genes will be removed from
+0047 %                       grRules, unless they are the only gene associated
+0048 %                       with a reaction, or a subunit of an enzyme complex
+0049 %                       (see "removeLowScoreGenes" function for details).
+0050 %                       If false, grRules will not be modified; however,
+0051 %                       genes that were associated only with removed
+0052 %                       reactions will not be present in the final model.
+0053 %                       (optional, default true).
+0054 %   useScoresForTasks   true if the calculated reaction scored should be
+0055 %                       used as weights when fitting to tasks (optional, default
+0056 %                       true)
+0057 %   paramsFT            *obsolete option*
+0058 %   verbose             if true, the MILP progression will be shown.
+0059 %                       (optional, default false)
+0060 %
+0061 %   model                   the resulting model structure
+0062 %   metProduction           array that indicates which of the
+0063 %                           metabolites in metabolomicsData that could be
+0064 %                           produced. Note that this is before the
+0065 %                           gap-filling process to enable defined tasks. To
+0066 %                           see which metabolites that can be produced in
+0067 %                           the final model, use canProduce.
+0068 %                           -2: metabolite name not found in model
+0069 %                           -1: metabolite found, but it could not be produced
+0070 %                           1: metabolite could be produced
+0071 %   addedRxnsForTasks       cell array of the reactions which were added in
+0072 %                           order to perform the tasks
+0073 %   deletedRxnsInINIT       cell array of reactions deleted because they
+0074 %                           could not carry flux (INIT requires a
+0075 %                           functional input model)
+0076 %   fullMipRes              The solver results from the last MILP step run
+0077 %
+0078 %   This is the main function for automatic reconstruction of models based
+0079 %   on the ftINIT algorithm ().
+0080 %
+0081 %   NOTE: Exchange metabolites should normally not be removed from the model
+0082 %   when using this approach, since checkTasks/fitTasks rely on putting specific
+0083 %   constraints for each task. The INIT algorithm will remove exchange metabolites
+0084 %   if any are present. Use importModel(file,false) to import a model with
+0085 %   exchange metabolites remaining.
+0086 %
+0087 % Usage: [model, metProduction, addedRxnsForTasks, deletedRxnsInINIT, ...
+0088 %               fullMipRes] = ...
+0089 %               ftINIT(prepData, tissue, celltype, hpaData, transcrData, ...
+0090 %               metabolomicsData, INITSteps, removeGenes, useScoresForTasks, ...
+0091 %               paramsFT);
+0092 %
+0093 
+0094 
+0095 if nargin < 5
+0096     transcrData = [];
+0097 end
+0098 if nargin < 6
+0099     metabolomicsData = [];
+0100 end
+0101 if nargin < 7 || isempty(INITSteps)
+0102     INITSteps = getINITSteps([],'1+1');
+0103 end
+0104 if nargin < 8 || isempty(removeGenes)
+0105     removeGenes = true;
+0106 end
+0107 if nargin < 9 || isempty(useScoresForTasks)
+0108     useScoresForTasks = true;
+0109 end
+0110 if nargin < 10
+0111     paramsFT = [];
+0112 end
+0113 
+0114 if nargin < 11
+0115     verbose = false;
+0116 end
+0117 %Handle detected mets:
+0118 %Previously, this was handled by giving a bonus for secreting those metabolites,
+0119 %but that doesn't work since the metabolite secretion and uptake can be lost when
+0120 %we merge linearly dependent reactions.
+0121 %Instead, we need to figure out which reactions either produce or take up the mets.
+0122 %We then give a bonus if any of them carry flux.
+0123 %To simplify things, we focus on reactions that produce the metabolite (since there must be one such reaction).
+0124 %It is still a bit complicated though. In this step, we focus on identifying
+0125 %producer reactions. We further reason that the direction doesn't matter -
+0126 %we can force one of these reactions in any direction - if it becomes a consumer, it will
+0127 %automatically force another producer on as well (otherwise we'll have a net consumption).
+0128 
+0129 if (~isempty(metabolomicsData))
+0130     if length(unique(upper(metabolomicsData))) ~= length(metabolomicsData)
+0131         dispEM('Metabolomics contains the same metabolite multiple times');
+0132     end
+0133     metData = false(numel(metabolomicsData), length(prepData.minModel.rxns)); %one row per metabolite that is a boolean vector
+0134     for i=1:numel(metabolomicsData)
+0135         %Get the matching mets
+0136         metSel = ismember(upper(prepData.refModel.metNames),upper(metabolomicsData{i}));
+0137         prodRxnsSel = any(prepData.refModel.S(metSel,:) > 0,1) | ... %direct producers
+0138                      (any(prepData.refModel.S(metSel,:) < 0,1) & prepData.refModel.rev.'); %reversible reactions that are consumers
+0139         %convert the production rxns from refModel to minModel
+0140         prepData.groupIds;
+0141         [~,ia,ib] = intersect(prepData.minModel.rxns,prepData.refModel.rxns);
+0142         grpIdsMerged = nan(length(prepData.minModel.rxns),1);
+0143         grpIdsMerged(ia) = prepData.groupIds(ib);
+0144         
+0145         groupIdsPos = unique(prepData.groupIds(prodRxnsSel));%gets all group ids which includes a production rxn
+0146         groupIdsPos = groupIdsPos(groupIdsPos ~= 0);%remove the 0 id, it means there is no group
+0147         %the other option is that there is a direct match between the rxn id in minModel and refModel:
+0148         posRxns = prepData.refModel.rxns(prodRxnsSel);
+0149         directMatch = ismember(prepData.minModel.rxns, posRxns).';
+0150         
+0151         metData(i,:) = ismember(grpIdsMerged, groupIdsPos).' | directMatch;
+0152     end
+0153     metData = sparse(metData);
+0154 else
+0155     metData = [];
+0156 end
+0157 
+0158 % Get rxn scores and adapt them to the minimized model
+0159 origRxnScores = scoreComplexModel(prepData.refModel,hpaData,transcrData,tissue,celltype);
+0160 origRxnScores(origRxnScores > -0.1 & origRxnScores <= 0) = -0.1;%we don't want reaction scores that are exactly 0 (or close), this causes problems in the milp
+0161 origRxnScores(origRxnScores < 0.1 & origRxnScores > 0) = 0.1;
+0162 
+0163 rxnsTurnedOn = false(length(prepData.minModel.rxns),1);
+0164 fluxes = zeros(length(prepData.minModel.rxns),1);
+0165 
+0166 rxnsToIgnoreLastStep = [1;1;1;1;1;1;1;1];
+0167 
+0168 %We assume that all essential rxns are irrev - this is taken care of in
+0169 %prepINITModel. We then use an initial flux "from last run" of 0.1 for all
+0170 %reactions. This is used for knowing what flux should be forced through an
+0171 %essential rxn.
+0172 fluxes = ones(length(prepData.minModel.rxns), 1).*0.1;
+0173 
+0174 for initStep = 1:length(INITSteps)
+0175     disp(['ftINIT: Running step ' num2str(initStep)])
+0176     stp = INITSteps{initStep};
+0177     
+0178     if any ((rxnsToIgnoreLastStep - stp.RxnsToIgnoreMask) < 0)
+0179         dispEM('RxnsToIgnoreMask may not cover rxns not covered in previous steps, but the other way around is fine.');
+0180     end
+0181     rxnsToIgnoreLastStep = stp.RxnsToIgnoreMask;
+0182     
+0183     mm = prepData.minModel;
+0184     
+0185     if (~isempty(stp.MetsToIgnore))
+0186         if (~isempty(stp.MetsToIgnore.simpleMets))
+0187             %Here, we remove simple metabolites that will not really affect the milp but
+0188             %are very common in the S matrix. For example H2O, H+, etc.
+0189             %It is also possible to leave compartments untouched, for example the i compartment in the mitochondria (for H+).
+0190             metsToRem = ismember(mm.metNames,stp.MetsToIgnore.simpleMets.mets);
+0191             compsToKeep = find(ismember(mm.comps, stp.MetsToIgnore.simpleMets.compsToKeep));
+0192             metsToRem = metsToRem & ~ismember(mm.metComps, compsToKeep);
+0193             mm.S(metsToRem,:) = 0;
+0194         end    
+0195     end
+0196 
+0197     %Set up the reaction scores and essential rxns
+0198     rxnsToIgnore = getRxnsFromPattern(stp.RxnsToIgnoreMask, prepData);
+0199     rxnScores = groupRxnScores(prepData.minModel, origRxnScores, prepData.refModel.rxns, prepData.groupIds, rxnsToIgnore);
+0200 
+0201     essentialRxns = prepData.essentialRxns;
+0202     toRev = false(numel(mm.rxns),1);
+0203     %Handle the results from previous steps ('ignore', 'exclude', 'essential')
+0204     if strcmp(stp.HowToUsePrevResults, 'exclude')
+0205         rxnScores(rxnsTurnedOn) = 0; %This is not used anymore in any step setup.
+0206     elseif strcmp(stp.HowToUsePrevResults, 'essential')
+0207         %Make all reversible reactions turned on in previous steps reversible
+0208         %in the direction that they were previously carrying flux
+0209         
+0210         %first reverse the reactions that need to be reversed
+0211         rev = mm.rev == 1;
+0212         toRev = rxnsTurnedOn & rev & fluxes < 0;
+0213         mm = reverseRxns(mm, mm.rxns(toRev));
+0214         
+0215         %Then make them irreversible
+0216         mm.rev(rxnsTurnedOn) = 0;
+0217         mm.lb(rxnsTurnedOn) = 0;
+0218 
+0219         essentialRxns = unique([prepData.essentialRxns;mm.rxns(rxnsTurnedOn)]);
+0220     end
+0221 
+0222     
+0223     mipGap = 1;
+0224     first = true;
+0225     success = false;
+0226     fullMipRes = [];
+0227     for rn = 1:length(stp.MILPParams)
+0228         params = stp.MILPParams{rn};
+0229         if ~isfield(params, 'MIPGap')
+0230             params.MIPGap = 0.0004;
+0231         end
+0232         
+0233         if ~isfield(params, 'TimeLimit')
+0234             params.TimeLimit = 5000;
+0235         end
+0236 
+0237         %Default to single-threaded Gurobi MILP solving. Multi-threaded Gurobi
+0238         %can non-deterministically report the MILP as infeasible (issue #607).
+0239         %Override by setting 'Threads' in the step's MILPParams (0 = all cores).
+0240         if ~isfield(params, 'Threads')
+0241             params.Threads = 1;
+0242         end
+0243         
+0244         if ~first 
+0245             %There is sometimes a problem with that the objective function becomes close to zero,
+0246             %which leads to that a small percentage of that (which is the MIPGap sent in) is very small
+0247             %and the MILP hence takes a lot of time to finish. We also therefore use an absolute MIP gap,
+0248             %converted to a percentage using the last value of the objective function.
+0249             params.MIPGap = min(max(params.MIPGap, stp.AbsMIPGaps{rn}/abs(lastObjVal)),1);
+0250             params.seed = 1234;%use another seed, may work better
+0251 
+0252             if mipGap <= params.MIPGap
+0253                 success = true;
+0254                 break; %we're done - this will not happen the first time
+0255             else
+0256                 disp(['MipGap too high, trying with a different run. MipGap = ' num2str(mipGap) ' New MipGap Limit = ' num2str(params.MIPGap)])
+0257             end
+0258         end
+0259         
+0260         first = false;
+0261         
+0262         %now run the MILP
+0263         try
+0264             %The prodweight for metabolomics is currently set to 5 - 0.5 was default in the old version, which I deemed very small?
+0265             %There could be a need to specify this somewhere in the call at some point.
+0266             %This value has not been evaluated, but is assumed in the test cases - if changed, update the test case
+0267             startVals = [];
+0268             if ~isempty(fullMipRes)
+0269                 startVals = fullMipRes.full;
+0270             end
+0271             [deletedRxnsInINIT1, metProduction,fullMipRes,rxnsTurnedOn1,fluxes1] = ftINITInternalAlg(mm,rxnScores,metData,essentialRxns,5,stp.AllowMetSecr,stp.PosRevOff,params, startVals, fluxes, verbose);
+0272             %This is a bit tricky - since we reversed some reactions, those fluxes also need to be reversed
+0273             fluxes1(toRev) = -fluxes1(toRev);
+0274             
+0275             mipGap = fullMipRes.mipgap;
+0276             lastObjVal = fullMipRes.obj;
+0277         catch e
+0278             mipGap = Inf;
+0279             lastObjVal = Inf; %we need to set something here, Inf leads to that this doesn't come into play
+0280         end
+0281         
+0282         success = mipGap <= params.MIPGap;
+0283     end
+0284     
+0285     if ~success
+0286         dispEM(['Failed to find good enough solution within the time frame. MIPGap: ' num2str(mipGap)]);
+0287     end
+0288     
+0289     %save the reactions turned on and their fluxes for the next step
+0290     rxnsTurnedOn = rxnsTurnedOn | rxnsTurnedOn1.';
+0291     %The fluxes are a bit tricky - what if they change direction between the steps?
+0292     %The fluxes are used to determine the direction in which reactions are forced on
+0293     %(to simplify the problem it is good if they are unidirectional).
+0294     %We use the following strategy:
+0295     %1. Use the fluxes from the most recent step.
+0296     %2. If any flux is very low there (i.e. basically zero), use the flux from the previous steps
+0297     %This could in theory cause problems, but seems to work well practically
+0298     fluxesOld = fluxes;
+0299     fluxes = fluxes1;
+0300     %make sure that all reactions that are on actually has a flux - otherwise
+0301     %things could go bad, since the flux will be set to essential in a random direction
+0302     %This sometimes happens for rxns with negative score - let's just accept that.
+0303     %if (sum(abs(fluxes1) < 10^-7 & rxnsTurnedOn))
+0304     %    dispEM('There are rxns turned on without flux - this might cause problems');
+0305     %end
+0306     %fluxes(abs(fluxes1) < 10^-7) = fluxesOld(abs(fluxes1) < 10^-9);
+0307 end
+0308 
+0309 
+0310 %get the essential rxns
+0311 essential = ismember(prepData.minModel.rxns,prepData.essentialRxns);
+0312 %So, we only add reactions where the linearly merged scores are zero for all linearly dependent reactions
+0313 % (this cannot happen by chance, taken care of in the function groupRxnScores)
+0314 rxnsToIgn = rxnScores == 0; 
+0315 deletedRxnsInINITSel = ~(rxnsTurnedOn | rxnsToIgn | essential);
+0316 deletedRxnsInINIT = prepData.minModel.rxns(deletedRxnsInINITSel);
+0317 
+0318 %Here we need to figure out which original reactions (before the linear merge)
+0319 %that were removed. These are all reactions with the same group ids as the removed reactions
+0320 groupIdsRemoved = prepData.groupIds(ismember(prepData.refModel.rxns, deletedRxnsInINIT)); %can improve this slightly, use sel above
+0321 groupIdsRemoved = groupIdsRemoved(groupIdsRemoved ~= 0);%zero means that the reaction was not grouped, all with zeros are not a group!
+0322 rxnsToRem = union(prepData.refModel.rxns(ismember(prepData.groupIds,groupIdsRemoved)), deletedRxnsInINIT);%make a union here to include the ungrouped (unmerged) as well
+0323 
+0324 initModel = removeReactions(prepData.refModel,rxnsToRem,false,true);
+0325 
+0326 % remove metabolites separately to avoid removing those needed for tasks
+0327 unusedMets = initModel.mets(all(initModel.S == 0,2));
+0328 initModel = removeMets(initModel, setdiff(unusedMets, prepData.essentialMetsForTasks));
+0329 
+0330 %if printReport == true
+0331 %    printScores(initModel,'INIT model statistics',hpaData,transcrData,tissue,celltype);
+0332 %    printScores(removeReactions(cModel,setdiff(cModel.rxns,rxnsToRem),true,true),'Reactions deleted by INIT',hpaData,transcrData,tissue,celltype);
+0333 %end
+0334 
+0335 %The full model has exchange reactions in it. ftINITFillGapsForAllTasks calls
+0336 %ftINITFillGaps, which automatically removes exchange metabolites (because it
+0337 %assumes that the reactions are constrained when appropriate). In this case the
+0338 %uptakes/outputs are retrieved from the task sheet instead. To prevent
+0339 %exchange reactions being used to fill gaps, they are deleted from the
+0340 %reference model here.
+0341 initModel.id = 'INITModel';
+0342 
+0343 %If gaps in the model should be filled using a task list
+0344 if ~isempty(prepData.taskStruct)
+0345     %Remove exchange reactions and reactions already included in the INIT
+0346     %model
+0347     %We changed strategy and instead include all rxns except the exchange rxns in the ref model
+0348     %But we do keep the exchange rxns that are essential.
+0349     %Let's test to remove all, that should work
+0350     
+0351     %At this stage the model is fully connected and most of the genes with
+0352     %good scores should have been included. The final gap-filling should
+0353     %take the scores of the genes into account, so that "rather bad"
+0354     %reactions are preferred to "very bad" reactions. However, reactions
+0355     %with positive scores will be included even if they are not connected
+0356     %in the current formulation. Therefore, such reactions will have to be
+0357     %assigned a small negative score instead.
+0358     exchRxns = getExchangeRxns(prepData.refModel);
+0359     refModelNoExc = removeReactions(prepData.refModelWithBM,exchRxns,false,true);
+0360     exchRxns = getExchangeRxns(initModel);
+0361     initModelNoExc = removeReactions(closeModel(initModel),exchRxns,false,true);
+0362     
+0363     if useScoresForTasks == true
+0364         %map the rxn scores to the model without exchange rxns
+0365         [~,ia,ib] = intersect(refModelNoExc.rxns,prepData.refModel.rxns);
+0366         rxnScores2nd = NaN(length(refModelNoExc.rxns),1);
+0367         rxnScores2nd(ia) = origRxnScores(ib);
+0368         %all(rxnScores2nd == refRxnScores);%should be the same, ok!
+0369         [outModel,addedRxnMat] = ftINITFillGapsForAllTasks(initModelNoExc,refModelNoExc,[],true,min(rxnScores2nd,-0.1),prepData.taskStruct,paramsFT,verbose);
+0370     else
+0371         [outModel,addedRxnMat] = ftINITFillGapsForAllTasks(initModelNoExc,refModelNoExc,[],true,[],prepData.taskStruct,paramsFT,verbose);
+0372     end
+0373     %if printReport == true
+0374     %    printScores(outModel,'Functional model statistics',hpaData,transcrData,tissue,celltype);
+0375     %    printScores(removeReactions(outModel,intersect(outModel.rxns,initModel.rxns),true,true),'Reactions added to perform the tasks',hpaData,transcrData,tissue,celltype);
+0376     %end
+0377     
+0378     addedRxnsForTasks = refModelNoExc.rxns(any(addedRxnMat,2));
+0379 else
+0380     outModel = initModel;
+0381     addedRxnMat = [];
+0382     addedRxnsForTasks = {};
+0383 end
+0384 
+0385 % The model can now perform all the tasks defined in the task list.
+0386 model = outModel;
+0387 
+0388 
+0389 % At this stage the model will contain some exchange reactions but probably
+0390 % not all (and maybe zero). This can be inconvenient, so all exchange
+0391 % reactions from the reference model are added, except for those which
+0392 % involve metabolites that are not in the model.
+0393 
+0394 %Start from the original model, and just remove the reactions that are no longer there (and keep exchange rxns). The model we got out
+0395 %from the problem is not complete, it doesn't have GRPs etc.
+0396 %The logic below is a bit complicated. We identify the reactions that should be removed from the full model as
+0397 %reactions that have been removed in the init model except the ones that were added back. In addition, we make
+0398 %sure that no exchange rxns are removed - they can be removed in the init model if they were linearly merged with other
+0399 %reactions that were decided to be removed from the model. We want to keep all exchange rxns to make sure the tasks can
+0400 %be performed also without manipulating the b vector in the model (which is what is done in the gap-filling).
+0401 exchRxns = getExchangeRxns(prepData.refModel);
+0402 deletedRxnsInINIT = setdiff(prepData.refModel.rxns,union(union(initModel.rxns, addedRxnsForTasks), exchRxns));
+0403 outModel = removeReactions(prepData.refModel, deletedRxnsInINIT, true); %we skip removing the genes for now, I'm not sure it is desirable
+0404 
+0405 % If requested, attempt to remove negative-score genes from the model,
+0406 % depending on their role (isozyme or complex subunit) in each grRule.
+0407 % See the "removeLowScoreGenes" function more more details, and to adjust
+0408 % any default parameters therein.
+0409 if ( removeGenes )
+0410     [~, geneScores] = scoreComplexModel(outModel,hpaData,transcrData,tissue,celltype);
+0411     outModel = removeLowScoreGenes(outModel,geneScores);
+0412 end
+0413 
+0414 
+0415 model = outModel;
+0416 
+0417 end
+0418 
+0419 %This is for printing a summary of a model
+0420 function [rxnS, geneS] = printScores(model,name,hpaData,transcrData,tissue,celltype)
+0421     [a, b] = scoreComplexModel(model,hpaData,transcrData,tissue,celltype);
+0422     rxnS = mean(a);
+0423     geneS = mean(b,'omitnan');
+0424     fprintf([name ':\n']);
+0425     fprintf(['\t' num2str(numel(model.rxns)) ' reactions, ' num2str(numel(model.genes)) ' genes\n']);
+0426     fprintf(['\tMean reaction score: ' num2str(rxnS) '\n']);
+0427     fprintf(['\tMean gene score: ' num2str(geneS) '\n']);
+0428     fprintf(['\tReactions with positive scores: ' num2str(100*sum(a>0)/numel(a)) '%%\n\n']);
+0429 end
+0430 
+0431 function rxnsToIgnore = getRxnsFromPattern(rxnsToIgnorePattern, prepData)
+0432     rxnsToIgnore = false(length(prepData.toIgnoreExch),1);
+0433     if rxnsToIgnorePattern(1) rxnsToIgnore = rxnsToIgnore | prepData.toIgnoreExch; end;
+0434     if rxnsToIgnorePattern(2) rxnsToIgnore = rxnsToIgnore | prepData.toIgnoreImportRxns; end;
+0435     if rxnsToIgnorePattern(3) rxnsToIgnore = rxnsToIgnore | prepData.toIgnoreSimpleTransp; end;
+0436     if rxnsToIgnorePattern(4) rxnsToIgnore = rxnsToIgnore | prepData.toIgnoreAdvTransp; end;
+0437     if rxnsToIgnorePattern(5) rxnsToIgnore = rxnsToIgnore | prepData.toIgnoreSpont; end;
+0438     if rxnsToIgnorePattern(6) rxnsToIgnore = rxnsToIgnore | prepData.toIgnoreS; end;
+0439     if rxnsToIgnorePattern(7) rxnsToIgnore = rxnsToIgnore | prepData.toIgnoreCustomRxns; end;
+0440     if rxnsToIgnorePattern(8) rxnsToIgnore = rxnsToIgnore | prepData.toIgnoreAllWithoutGPRs; end;
+0441 end
+0442
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/INIT/ftINITFillGaps.html b/doc/INIT/ftINITFillGaps.html new file mode 100644 index 000000000..6a6661e79 --- /dev/null +++ b/doc/INIT/ftINITFillGaps.html @@ -0,0 +1,207 @@ + + + + Description of ftINITFillGaps + + + + + + + + + +
Home > INIT > ftINITFillGaps.m
+ + + +

ftINITFillGaps +

+ +

PURPOSE ^

+
ftINITFillGaps
+ +

SYNOPSIS ^

+
function [addedRxns, newModel, exitFlag]=ftINITFillGaps(tModel, origModel, tRefModel,allowNetProduction,supressWarnings,rxnScores,params,verbose)
+ +

DESCRIPTION ^

+
 ftINITFillGaps
+   Variant of fillGaps specially adapted to speed up generation of ftINIT models.
+
+   tModel              model that contains the task-specific rxns.
+   origModel           model without task-specific rxns.         
+   tRefModel           reference tModel - the full tModel, containing all rxns
+                       used for gap-filling of tModel + the task-specific rxns
+   allowNetProduction  true if net production of all metabolites is
+                       allowed. A reaction can be unable to carry flux because one of
+                       the reactants is unavailable or because one of the
+                       products can't be further processed. If this
+                       parameter is true, only the first type of
+                       unconnectivity is considered (optional, default false)
+   useModelConstraints true if the constraints specified in the tModel
+                       structure should be used. If false then reactions
+                       included from the template tModel(s) so that as many
+                       reactions as possible in tModel can carry flux
+                       (optional, default false)
+   supressWarnings     false if warnings should be displayed (optional, default
+                       false)
+   rxnScores           scores for each of the reactions in the
+                       reference tModel. 
+                       The solver will try to maximize the sum of the
+                       scores for the included reactions
+   params              *obsolete option*
+   verbose             if true, the MILP progression will be shown. 
+
+   addedRxns           the rxns added
+   newModel            the tModel with reactions added to fill gaps
+   exitFlag            1: optimal solution found
+                      -1: no feasible solution found
+                      -2: optimization time out
+
+   This method works by merging the tModel to the reference model and
+   checking which reactions can carry flux. All reactions that can't
+   carry flux are removed.
+   If useModelConstraints is false it then solves the MILP problem of
+   minimizing the number of active reactions from the reference model
+   that are required to have flux in all the reactions in model. This
+   requires that the input tModel has exchange reactions present for the
+   nutrients that are needed for its metabolism. If useModelConstraints is
+   true then the problem is to include as few reactions as possible from
+   the reference models in order to satisfy the tModel constraints.
+   The intended use is that the user can attempt a general gap-filling using
+   useModelConstraint=false or a more targeted gap-filling by setting
+   constraints in the model structure and then use
+   useModelConstraints=true. Say that the user want to include reactions
+   so that all biomass components can be synthesized. He/she could then
+   define a biomass equation and set the lower bound to >0. Running this
+   function with useModelConstraints=true would then give the smallest set
+   of reactions that have to be included in order for the tModel to produce
+   biomass.
+
+ Usage: [newModel, exitFlag]=...
+           fillGaps(tModel,models,allowNetProduction,...
+           supressWarnings,rxnScores,params)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function [addedRxns, newModel, exitFlag]=ftINITFillGaps(tModel, origModel, tRefModel,allowNetProduction,supressWarnings,rxnScores,params,verbose)
+0002 % ftINITFillGaps
+0003 %   Variant of fillGaps specially adapted to speed up generation of ftINIT models.
+0004 %
+0005 %   tModel              model that contains the task-specific rxns.
+0006 %   origModel           model without task-specific rxns.
+0007 %   tRefModel           reference tModel - the full tModel, containing all rxns
+0008 %                       used for gap-filling of tModel + the task-specific rxns
+0009 %   allowNetProduction  true if net production of all metabolites is
+0010 %                       allowed. A reaction can be unable to carry flux because one of
+0011 %                       the reactants is unavailable or because one of the
+0012 %                       products can't be further processed. If this
+0013 %                       parameter is true, only the first type of
+0014 %                       unconnectivity is considered (optional, default false)
+0015 %   useModelConstraints true if the constraints specified in the tModel
+0016 %                       structure should be used. If false then reactions
+0017 %                       included from the template tModel(s) so that as many
+0018 %                       reactions as possible in tModel can carry flux
+0019 %                       (optional, default false)
+0020 %   supressWarnings     false if warnings should be displayed (optional, default
+0021 %                       false)
+0022 %   rxnScores           scores for each of the reactions in the
+0023 %                       reference tModel.
+0024 %                       The solver will try to maximize the sum of the
+0025 %                       scores for the included reactions
+0026 %   params              *obsolete option*
+0027 %   verbose             if true, the MILP progression will be shown.
+0028 %
+0029 %   addedRxns           the rxns added
+0030 %   newModel            the tModel with reactions added to fill gaps
+0031 %   exitFlag            1: optimal solution found
+0032 %                      -1: no feasible solution found
+0033 %                      -2: optimization time out
+0034 %
+0035 %   This method works by merging the tModel to the reference model and
+0036 %   checking which reactions can carry flux. All reactions that can't
+0037 %   carry flux are removed.
+0038 %   If useModelConstraints is false it then solves the MILP problem of
+0039 %   minimizing the number of active reactions from the reference model
+0040 %   that are required to have flux in all the reactions in model. This
+0041 %   requires that the input tModel has exchange reactions present for the
+0042 %   nutrients that are needed for its metabolism. If useModelConstraints is
+0043 %   true then the problem is to include as few reactions as possible from
+0044 %   the reference models in order to satisfy the tModel constraints.
+0045 %   The intended use is that the user can attempt a general gap-filling using
+0046 %   useModelConstraint=false or a more targeted gap-filling by setting
+0047 %   constraints in the model structure and then use
+0048 %   useModelConstraints=true. Say that the user want to include reactions
+0049 %   so that all biomass components can be synthesized. He/she could then
+0050 %   define a biomass equation and set the lower bound to >0. Running this
+0051 %   function with useModelConstraints=true would then give the smallest set
+0052 %   of reactions that have to be included in order for the tModel to produce
+0053 %   biomass.
+0054 %
+0055 % Usage: [newModel, exitFlag]=...
+0056 %           fillGaps(tModel,models,allowNetProduction,...
+0057 %           supressWarnings,rxnScores,params)
+0058 
+0059 if isempty(rxnScores)
+0060     rxnScores=cell(numel(models),1);
+0061     for i=1:numel(models)
+0062         rxnScores{i}=ones(numel(models{i}.rxns),1)*-1;
+0063     end
+0064 end
+0065 
+0066 %Simplify the template models to remove constrained rxns. At the same time,
+0067 %check that the id of the template models isn't the same as the tModel. That
+0068 %would cause an error further down
+0069 tRefModel.rxnScores=rxnScores;
+0070 tRefModel=simplifyModel(tRefModel,false,false,true);
+0071 
+0072 %This is a rather ugly solution to the issue that it's a bit tricky to keep
+0073 %track of which scores belong to which reactions. This requires that
+0074 %removeReactions and mergeModels are modified to check for the new field.
+0075 tModel.rxnScores=zeros(numel(tModel.rxns),1);
+0076 
+0077 %First merge all models into one big one
+0078 fullModel = tRefModel;%mergeModels([{tModel};models],'metNames',true);
+0079 
+0080 %Add that net production is ok
+0081 if allowNetProduction==true
+0082     %A second column in tModel.b means that the b field is lower and upper
+0083     %bound on the RHS.
+0084     tModel.b=[tModel.b(:,1) inf(numel(tModel.mets),1)];
+0085     fullModel.b=[fullModel.b(:,1) inf(numel(fullModel.mets),1)];
+0086 end
+0087 
+0088 
+0089 fullModel.c(:)=0;
+0090 
+0091 %Then minimize for the number of fluxes used. The fixed rxns doesn't need
+0092 %to participate
+0093 templateRxns = find(~ismember(fullModel.rxns, tModel.rxns)); %Check if this is slow, in that case keep track of this in fitTasksOpt and send it in
+0094 
+0095 [~, J, exitFlag]=ftINITFillGapsMILP(fullModel,templateRxns,params,fullModel.rxnScores(templateRxns),verbose);%only the scores from the template rxns are used, so the others doesn't matter
+0096 
+0097 %Remove everything except for the added ones
+0098 addedRxns = fullModel.rxns(templateRxns(J));
+0099 rxnsToAdd.rxns = addedRxns;
+0100 rxnsToAdd.equations = constructEquations(fullModel, addedRxns);
+0101 rxnsToAdd.ub = fullModel.ub(templateRxns(J));
+0102 rxnsToAdd.lb = fullModel.lb(templateRxns(J));
+0103 newModel = addRxns(origModel,rxnsToAdd, 3, [], true); %we ignore gene rules etc here, they are not needed - we regenerate the model in the end by subtracting rxns from the full model.
+0104 
+0105 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/INIT/ftINITFillGapsForAllTasks.html b/doc/INIT/ftINITFillGapsForAllTasks.html new file mode 100644 index 000000000..ae7fdaf2f --- /dev/null +++ b/doc/INIT/ftINITFillGapsForAllTasks.html @@ -0,0 +1,462 @@ + + + + Description of ftINITFillGapsForAllTasks + + + + + + + + + +
Home > INIT > ftINITFillGapsForAllTasks.m
+ + + +

ftINITFillGapsForAllTasks +

+ +

PURPOSE ^

+
ftINITFillGapsForAllTasks
+ +

SYNOPSIS ^

+
function [outModel, addedRxns]=ftINITFillGapsForAllTasks(model,refModel,inputFile,printOutput,rxnScores,taskStructure,params,verbose)
+ +

DESCRIPTION ^

+
 ftINITFillGapsForAllTasks
+   Fills gaps in a model by including reactions from a reference model,
+   so that the resulting model can perform all the tasks in a task list
+   This is similar to the old fitTasks function but optimized for ftINIT.
+
+   Input:
+   model           model structure
+   refModel        reference model from which to include reactions
+   inputFile       a task list in Excel format. See the function
+                   parseTaskList for details (optional if taskStructure is
+                   supplied)
+   printOutput     true if the results of the test should be displayed
+                   (optional, default true)
+   rxnScores       scores for each of the reactions in the reference
+                   model. Only negative scores are allowed. The solver will
+                   try to maximize the sum of the scores for the included
+                   reactions (optional, default is -1 for all reactions)
+   taskStructure   structure with the tasks, as from parseTaskList. If
+                   this is supplied then inputFile is ignored
+   params          *obsolete option*
+   verbose         if true, the MILP progression will be shown. 
+
+
+   Output:
+   outModel        model structure with reactions added to perform the
+                   tasks
+   addedRxns       MxN matrix with the added reactions (M) from refModel
+                   for each task (N). An element is true if the corresponding
+                   reaction is added in the corresponding task.
+                   Failed tasks and SHOULD FAIL tasks are ignored
+
+   This function fills gaps in a model by using a reference model, so
+   that the resulting model can perform a list of metabolic tasks. The
+   gap-filling is done in a task-by-task manner, rather than solving for
+   all tasks at once. This means that the order of the tasks could influence
+   the result.
+
+ Usage: [outModel, addedRxns]=fitTasks(model,refModel,inputFile,printOutput,...
+           rxnScores,taskStructure,params)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function [outModel, addedRxns]=ftINITFillGapsForAllTasks(model,refModel,inputFile,printOutput,rxnScores,taskStructure,params,verbose)
+0002 % ftINITFillGapsForAllTasks
+0003 %   Fills gaps in a model by including reactions from a reference model,
+0004 %   so that the resulting model can perform all the tasks in a task list
+0005 %   This is similar to the old fitTasks function but optimized for ftINIT.
+0006 %
+0007 %   Input:
+0008 %   model           model structure
+0009 %   refModel        reference model from which to include reactions
+0010 %   inputFile       a task list in Excel format. See the function
+0011 %                   parseTaskList for details (optional if taskStructure is
+0012 %                   supplied)
+0013 %   printOutput     true if the results of the test should be displayed
+0014 %                   (optional, default true)
+0015 %   rxnScores       scores for each of the reactions in the reference
+0016 %                   model. Only negative scores are allowed. The solver will
+0017 %                   try to maximize the sum of the scores for the included
+0018 %                   reactions (optional, default is -1 for all reactions)
+0019 %   taskStructure   structure with the tasks, as from parseTaskList. If
+0020 %                   this is supplied then inputFile is ignored
+0021 %   params          *obsolete option*
+0022 %   verbose         if true, the MILP progression will be shown.
+0023 %
+0024 %
+0025 %   Output:
+0026 %   outModel        model structure with reactions added to perform the
+0027 %                   tasks
+0028 %   addedRxns       MxN matrix with the added reactions (M) from refModel
+0029 %                   for each task (N). An element is true if the corresponding
+0030 %                   reaction is added in the corresponding task.
+0031 %                   Failed tasks and SHOULD FAIL tasks are ignored
+0032 %
+0033 %   This function fills gaps in a model by using a reference model, so
+0034 %   that the resulting model can perform a list of metabolic tasks. The
+0035 %   gap-filling is done in a task-by-task manner, rather than solving for
+0036 %   all tasks at once. This means that the order of the tasks could influence
+0037 %   the result.
+0038 %
+0039 % Usage: [outModel, addedRxns]=fitTasks(model,refModel,inputFile,printOutput,...
+0040 %           rxnScores,taskStructure,params)
+0041 
+0042 if isempty(rxnScores)
+0043     rxnScores=ones(numel(refModel.rxns),1)*-1;
+0044 end
+0045 
+0046 if isempty(taskStructure) && ~isfile(inputFile)
+0047     error('Task file %s cannot be found',string(inputFile));
+0048 end
+0049 
+0050 if strcmpi(model.id,refModel.id)
+0051     fprintf('NOTE: The model and reference model have the same IDs. The ID for the reference model was set to "refModel" in order to keep track of the origin of reactions.\n');
+0052     refModel.id='refModel';
+0053 end
+0054 
+0055 if any(rxnScores>=0)
+0056     EM='Only negative values are allowed in rxnScores';
+0057     dispEM(EM);
+0058 end
+0059 
+0060 %Prepare the input models a little
+0061 model.b=zeros(numel(model.mets),2);
+0062 modelMets=upper(strcat(model.metNames,'[',model.comps(model.metComps),']'));
+0063 %This is the mets in the reference model. Used if the tasks involve
+0064 %metabolites that doesn't exist in the model
+0065 largeModelMets=upper(strcat(refModel.metNames,'[',refModel.comps(refModel.metComps),']'));
+0066 
+0067 if ~isfield(model,'unconstrained')
+0068     EM='Exchange metabolites should normally not be removed from the model when using checkTasks. Inputs and outputs are defined in the task file instead. Use importModel(file,false) to import a model with exchange metabolites remaining';
+0069     dispEM(EM,false);
+0070 end
+0071 
+0072 if isempty(taskStructure)
+0073     taskStructure=parseTaskList(inputFile);
+0074 end
+0075 
+0076 tModel=model;
+0077 addedRxns=false(numel(refModel.rxns),numel(taskStructure));
+0078 supressWarnings=false;
+0079 nAdded=0;
+0080 
+0081 for i=1:numel(taskStructure)
+0082     if ~taskStructure(i).shouldFail
+0083         
+0084         tRefModel = refModel;%we need to add stuff to this one as well...
+0085         tRxnScores = rxnScores;%these need to be extended (with zeros) when rxns are added in tasks
+0086         %Set the inputs
+0087         if ~isempty(taskStructure(i).inputs)
+0088             [I, J]=ismember(upper(taskStructure(i).inputs),modelMets);
+0089             [I2, J2]=ismember(upper(taskStructure(i).inputs),largeModelMets);
+0090             K=ismember(upper(taskStructure(i).inputs),'ALLMETS');
+0091             L=~cellfun('isempty',strfind(upper(taskStructure(i).inputs),'ALLMETSIN'));
+0092             %Check that all metabolites are either real metabolites or
+0093             %ALLMETS/ALLMETSIN
+0094             goodMets=I|K|L;
+0095             if ~all(goodMets)
+0096                 %Not all of the inputs could be found in the small model.
+0097                 %Check if they exist in the large model
+0098                 [found, metMatch]=ismember(upper(taskStructure(i).inputs(~goodMets)),largeModelMets);
+0099                 if ~all(found)
+0100                     EM=['Could not find all inputs in "[' taskStructure(i).id '] ' taskStructure(i).description '" in either model'];
+0101                     disp(EM);
+0102                 else
+0103                     %Otherwise add them to the model
+0104                     met.metNames=refModel.metNames(metMatch);
+0105                     met.compartments=refModel.comps(refModel.metComps(metMatch));
+0106                     
+0107                     %Add the metabolite both to the base model and the
+0108                     %model used in the current task
+0109                     model=addMets(model,met);
+0110                     tModel=addMets(tModel,met);
+0111                     modelMets=[modelMets;upper(taskStructure(i).inputs(~goodMets))];
+0112                 end
+0113                 
+0114                 %By now the indexes might be getting a bit confusing, but
+0115                 %this is to update the indexes of the "real" metabolites to
+0116                 %point to the newly added ones
+0117                 I(~goodMets)=true; %All the bad ones are fixed at this stage
+0118                 J(~goodMets)=numel(modelMets)-numel(metMatch)+1:numel(modelMets);
+0119             end
+0120             if numel(J(I))~=numel(unique(J(I)))
+0121                 EM=['The constraints on some input(s) in "[' taskStructure(i).id '] ' taskStructure(i).description '" are defined more than one time'];
+0122                 dispEM(EM);
+0123             end
+0124             %If all metabolites should be added
+0125             if any(K)
+0126                 %Check if ALLMETS is the first metabolite. Otherwise print
+0127                 %a warning since it will write over any other constraints
+0128                 %that are set
+0129                 if K(1)==0
+0130                     EM=['ALLMETS is used as an input in "[' taskStructure(i).id '] ' taskStructure(i).description '" but it it not the first metabolite in the list. Constraints defined for the metabolites before it will be over-written'];
+0131                     dispEM(EM,false);
+0132                 end
+0133                 %Use the first match of ALLMETS. There should only be one,
+0134                 %but still..
+0135                 tModel.b(:,1)=taskStructure(i).UBin(find(K,1))*-1;
+0136                 tRefModel.b(:,1)=taskStructure(i).UBin(find(K,1))*-1;
+0137             end
+0138             %If metabolites in a specific compartment should be used
+0139             if any(L)
+0140                 L=find(L);
+0141                 for j=1:numel(L)
+0142                     %The compartment defined
+0143                     compartment=upper(taskStructure(i).inputs{L(j)}(11:end-1));
+0144                     %Check if it exists in the model
+0145                     C=find(ismember(upper(model.comps),compartment));
+0146                     if any(C)
+0147                         %Match to metabolites
+0148                         tModel.b(model.metComps==C,1)=taskStructure(i).UBin(L(j))*-1;
+0149                     else
+0150                         EM=['The compartment defined for ALLMETSIN in "[' taskStructure(i).id '] ' taskStructure(i).description '" does not exist'];
+0151                         dispEM(EM);
+0152                     end
+0153                     %also need to do this for the t ref model
+0154                     C=find(ismember(upper(tRefModel.comps),compartment));
+0155                     if any(C)
+0156                         %Match to metabolites
+0157                         tRefModel.b(tRefModel.metComps==C,1)=taskStructure(i).UBin(L(j))*-1;
+0158                     else
+0159                         EM=['The compartment defined for ALLMETSIN in "[' taskStructure(i).id '] ' taskStructure(i).description '" does not exist'];
+0160                         dispEM(EM);
+0161                     end
+0162                 end
+0163             end
+0164             %Then add the normal constraints
+0165             if any(J(I))
+0166                 tModel.b(J(I),1)=taskStructure(i).UBin(I)*-1;
+0167                 tModel.b(J(I),2)=taskStructure(i).LBin(I)*-1;
+0168             end
+0169             %for the tRefModel as well
+0170             if any(J2(I2))
+0171                 tRefModel.b(J2(I2),1)=taskStructure(i).UBin(I2)*-1;
+0172                 tRefModel.b(J2(I2),2)=taskStructure(i).LBin(I2)*-1;
+0173             end
+0174         end
+0175         %Set the outputs
+0176         if ~isempty(taskStructure(i).outputs)
+0177             [I, J]=ismember(upper(taskStructure(i).outputs),modelMets);
+0178             [I2, J2]=ismember(upper(taskStructure(i).outputs),largeModelMets);
+0179             K=ismember(upper(taskStructure(i).outputs),'ALLMETS');
+0180             L=~cellfun('isempty',strfind(upper(taskStructure(i).outputs),'ALLMETSIN'));
+0181             %Check that all metabolites are either real metabolites or
+0182             %ALLMETS/ALLMETSIN
+0183             goodMets=I|K|L;
+0184             if ~all(goodMets)
+0185                 %Not all of the outputs could be found in the small model.
+0186                 %Check if they exist in the large model
+0187                 [found, metMatch]=ismember(upper(taskStructure(i).outputs(~goodMets)),largeModelMets);
+0188                 if ~all(found)
+0189                     EM=['Could not find all outputs in "[' taskStructure(i).id '] ' taskStructure(i).description '" in either model'];
+0190                     dispEM(EM);
+0191                 else
+0192                     %Otherwise add them to the model
+0193                     met.metNames=refModel.metNames(metMatch);
+0194                     met.compartments=refModel.comps(refModel.metComps(metMatch));
+0195                     
+0196                     %Add the metabolite both to the base model and the
+0197                     %model used in the current task
+0198                     model=addMets(model,met);
+0199                     tModel=addMets(tModel,met);
+0200                     modelMets=[modelMets;upper(taskStructure(i).outputs(~goodMets))];
+0201                 end
+0202                 
+0203                 %By now the indexes might be getting a bit confusing, but
+0204                 %this is to update the indexes of the "real" metabolites to
+0205                 %point to the newly added ones
+0206                 I(~goodMets)=true; %All the bad ones are fixed at this stage
+0207                 J(~goodMets)=numel(modelMets)-numel(metMatch)+1:numel(modelMets);
+0208             end
+0209             if numel(J(I))~=numel(unique(J(I)))
+0210                 EM=['The constraints on some output(s) in "[' taskStructure(i).id '] ' taskStructure(i).description '" are defined more than one time'];
+0211                 dispEM(EM);
+0212             end
+0213             %If all metabolites should be added
+0214             if any(K)
+0215                 %Check if ALLMETS is the first metabolite. Otherwise print
+0216                 %a warning since it will write over any other constraints
+0217                 %that are set
+0218                 if K(1)==0
+0219                     EM=['ALLMETS is used as an output in "[' taskStructure(i).id '] ' taskStructure(i).description '" but it it not the first metabolite in the list. Constraints defined for the metabolites before it will be over-written'];
+0220                     dispEM(EM,false);
+0221                 end
+0222                 %Use the first match of ALLMETS. There should only be one,
+0223                 %but still..
+0224                 tModel.b(:,2)=taskStructure(i).UBout(find(K,1));
+0225                 tRefModel.b(:,2)=taskStructure(i).UBout(find(K,1));
+0226             end
+0227             %If metabolites in a specific compartment should be used
+0228             if any(L)
+0229                 L=find(L);
+0230                 for j=1:numel(L)
+0231                     %The compartment defined
+0232                     compartment=upper(taskStructure(i).outputs{L(j)}(11:end-1));
+0233                     %Check if it exists in the model
+0234                     C=find(ismember(upper(model.comps),compartment));
+0235                     if any(C)
+0236                         %Match to metabolites
+0237                         tModel.b(model.metComps==C,2)=taskStructure(i).UBout(L(j));
+0238                     else
+0239                         EM=['The compartment defined for ALLMETSIN in "[' taskStructure(i).id '] ' taskStructure(i).description '" does not exist'];
+0240                         dispEM(EM);
+0241                     end
+0242                     %for the tRefModel as well
+0243                     C=find(ismember(upper(tRefModel.comps),compartment));
+0244                     if any(C)
+0245                         %Match to metabolites
+0246                         tRefModel.b(tRefModel.metComps==C,2)=taskStructure(i).UBout(L(j));
+0247                     else
+0248                         EM=['The compartment defined for ALLMETSIN in "[' taskStructure(i).id '] ' taskStructure(i).description '" does not exist'];
+0249                         dispEM(EM);
+0250                     end
+0251                 end
+0252             end
+0253             %Then add the normal constraints
+0254             if any(J(I))
+0255                 %Verify that IN and OUT bounds are consistent. Cannot require
+0256                 %that a metabolite is simultaneously input AND output at some
+0257                 %nonzero flux.
+0258                 J = J(I);
+0259                 I = find(I);  % otherwise indexing becomes confusing
+0260                 nonzero_LBin = tModel.b(J,2) < 0;
+0261                 nonzero_LBout = taskStructure(i).LBout(I) > 0;
+0262                 if any(nonzero_LBin & nonzero_LBout)
+0263                     EM=['The IN LB and OUT LB in "[' taskStructure(i).id '] ' taskStructure(i).description '" cannot be nonzero for the same metabolite'];
+0264                     dispEM(EM);
+0265                 end
+0266                 tModel.b(J(nonzero_LBout),1)=taskStructure(i).LBout(I(nonzero_LBout));
+0267                 tModel.b(J,2)=taskStructure(i).UBout(I);
+0268             end
+0269             %and for the ref model
+0270             if any(J2(I2))
+0271                 %Verify that IN and OUT bounds are consistent. Cannot require
+0272                 %that a metabolite is simultaneously input AND output at some
+0273                 %nonzero flux.
+0274                 J2 = J2(I2);
+0275                 I2 = find(I2);  % otherwise indexing becomes confusing
+0276                 nonzero_LBin = tRefModel.b(J2,2) < 0;
+0277                 nonzero_LBout = taskStructure(i).LBout(I2) > 0;
+0278                 if any(nonzero_LBin & nonzero_LBout)
+0279                     EM=['The IN LB and OUT LB in "[' taskStructure(i).id '] ' taskStructure(i).description '" cannot be nonzero for the same metabolite'];
+0280                     dispEM(EM);
+0281                 end
+0282                 tRefModel.b(J2(nonzero_LBout),1)=taskStructure(i).LBout(I2(nonzero_LBout));
+0283                 tRefModel.b(J2,2)=taskStructure(i).UBout(I2);
+0284             end
+0285         end
+0286         
+0287         %Add new rxns
+0288         if ~isempty(taskStructure(i).equations)
+0289             rxn.equations=taskStructure(i).equations;
+0290             rxn.lb=taskStructure(i).LBequ;
+0291             rxn.ub=taskStructure(i).UBequ;
+0292             rxn.rxns=strcat({'TEMPORARY_'},num2str((1:numel(taskStructure(i).equations))'));
+0293             tModel=addRxns(tModel,rxn,3);
+0294             tRefModel=addRxns(tRefModel,rxn,3);
+0295             tRxnScores = [tRxnScores;zeros(length(rxn.lb),1)];
+0296         end
+0297         %Add changed bounds
+0298         if ~isempty(taskStructure(i).changed)
+0299             tModel=setParam(tModel,'lb',taskStructure(i).changed,taskStructure(i).LBrxn);
+0300             tModel=setParam(tModel,'ub',taskStructure(i).changed,taskStructure(i).UBrxn);
+0301             tRefModel=setParam(tRefModel,'lb',taskStructure(i).changed,taskStructure(i).LBrxn);
+0302             tRefModel=setParam(tRefModel,'ub',taskStructure(i).changed,taskStructure(i).UBrxn);
+0303         end
+0304         
+0305         %Solve and print. Display a warning if the problem is not solveable
+0306         sol=solveLP(tModel);
+0307         if isempty(sol.x)
+0308             %Only do gap-filling if it cannot be solved
+0309             failed=false;
+0310             try
+0311                 [newRxns, newModel, exitFlag]=ftINITFillGaps(tModel,model,tRefModel,false,supressWarnings,tRxnScores,params,verbose);
+0312                 if exitFlag==-2
+0313                     EM=['"[' taskStructure(i).id '] ' taskStructure(i).description '" was aborted before reaching optimality. Consider increasing params.maxTime\n'];
+0314                     dispEM(EM,false);
+0315                 end
+0316             catch e
+0317                 EM=['"[' taskStructure(i).id '] ' taskStructure(i).description '" could not be performed for any set of reactions\n'];
+0318                 dispEM(EM,false);
+0319                 failed=true;
+0320             end
+0321             if failed==false
+0322                 if ~isempty(newRxns)
+0323                     nAdded=nAdded+numel(newRxns);
+0324                     
+0325                     disp(['task: ' num2str(i)])
+0326                     for iii = 1:numel(newRxns)
+0327                         disp(newRxns{iii})
+0328                     end
+0329                     
+0330                     %Add the reactions to the base model. It is not correct
+0331                     %to use newModel directly, as it may contain
+0332                     %reactions/constraints that are specific to this task
+0333                     %model=mergeModels({model,removeReactions(newModel,setdiff(newModel.rxns,newRxns),true,true)},'metNames',true);
+0334                     model = newModel;
+0335                     
+0336                     %Keep track of the added reactions
+0337                     addedRxns(ismember(refModel.rxns,newRxns),i)=true;
+0338                 end
+0339                 if printOutput==true
+0340                     fprintf(['[' taskStructure(i).id '] ' taskStructure(i).description ': Added ' num2str(numel(newRxns)) ' reaction(s), ' num2str(nAdded) ' reactions added in total\n']);
+0341                 end
+0342             end
+0343         else
+0344             if printOutput==true
+0345                 fprintf(['[' taskStructure(i).id '] ' taskStructure(i).description ': Added 0 reaction(s), ' num2str(nAdded) ' reactions added in total\n']);
+0346             end
+0347         end
+0348         supressWarnings=true;
+0349         
+0350         %Print the output if chosen
+0351         if taskStructure(i).printFluxes && printOutput
+0352             if ~isempty(sol.x)
+0353                 sol=solveLP(tModel,1);
+0354                 printFluxes(tModel,sol.x,false,10^-5,[],'%rxnID (%eqn):%flux\n');
+0355                 fprintf('\n');
+0356             else
+0357                 %If the problem wasn't solveable then the gap-filled model
+0358                 %should be used
+0359                 if failed==false
+0360                     sol=solveLP(newModel,1);
+0361                     printFluxes(newModel,sol.x,false,10^-5,[],'%rxnID (%eqn):%flux\n');
+0362                     fprintf('\n');
+0363                 end
+0364             end
+0365         end
+0366         
+0367         tModel=model;
+0368         %Since new mets are added by merging the new reactions and not only
+0369         %from the task sheet
+0370         modelMets=upper(strcat(model.metNames,'[',model.comps(model.metComps),']'));
+0371     else
+0372         EM=['"[' taskStructure(i).id '] ' taskStructure(i).description '" is set as SHOULD FAIL. Such tasks cannot be modelled using this approach and the task is therefore ignored\n'];
+0373         dispEM(EM,false);
+0374     end
+0375 end
+0376 outModel=model;
+0377 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/INIT/ftINITFillGapsMILP.html b/doc/INIT/ftINITFillGapsMILP.html new file mode 100644 index 000000000..888479a1e --- /dev/null +++ b/doc/INIT/ftINITFillGapsMILP.html @@ -0,0 +1,312 @@ + + + + Description of ftINITFillGapsMILP + + + + + + + + + +
Home > INIT > ftINITFillGapsMILP.m
+ + + +

ftINITFillGapsMILP +

+ +

PURPOSE ^

+
ftINITFillGapsMILP
+ +

SYNOPSIS ^

+
function [x,I,exitFlag]=ftINITFillGapsMILP(model, toMinimize, params, scores, verbose)
+ +

DESCRIPTION ^

+
 ftINITFillGapsMILP
+   Returns the minimal set of fluxes that satisfy the model using
+   mixed integer linear programming. This is an optimized variant of the
+   old function "getMinNrFluxes" that is adapted to ftINIT.
+   It does not need to make an irrev model, which takes time. The problem 
+   also becomes smaller (fewer integers but larger matrix). Only tested with 
+   Gurobi.
+
+    model         a model structure
+   toMinimize    either a cell array of reaction IDs, a logical vector
+                 with the same number of elements as reactions in the model,
+                 of a vector of indexes for the reactions that should be
+                 minimized (optional, default model.rxns)
+   params        *obsolete option*
+   scores        vector of weights for the reactions. Negative scores
+                 should not have flux. Positive scores are not possible in this
+                 implementation, and they are changed to max(scores(scores<0)).
+                 Must have the same dimension as toMinimize (find(toMinimize)
+                 if it is a logical vector) (optional, default -1 for all reactions)
+   verbose       if true, the MILP progression will be shown. 
+
+   x             the corresponding fluxes for the full model
+   I             the indexes of the reactions in toMinimize that were used
+                 in the solution
+   exitFlag      1: optimal solution found
+                -1: no feasible solution found
+                -2: optimization time out
+
+   NOTE: Uses 1000 mmol/gDW/h as an arbitary large flux. Could possibly
+   cause problems if the fluxes in the model are larger than that.
+
+ Usage: [x,I,exitFlag]=getMinNrFluxes(model, toMinimize, params, scores)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function [x,I,exitFlag]=ftINITFillGapsMILP(model, toMinimize, params, scores, verbose)
+0002 % ftINITFillGapsMILP
+0003 %   Returns the minimal set of fluxes that satisfy the model using
+0004 %   mixed integer linear programming. This is an optimized variant of the
+0005 %   old function "getMinNrFluxes" that is adapted to ftINIT.
+0006 %   It does not need to make an irrev model, which takes time. The problem
+0007 %   also becomes smaller (fewer integers but larger matrix). Only tested with
+0008 %   Gurobi.
+0009 %
+0010 %    model         a model structure
+0011 %   toMinimize    either a cell array of reaction IDs, a logical vector
+0012 %                 with the same number of elements as reactions in the model,
+0013 %                 of a vector of indexes for the reactions that should be
+0014 %                 minimized (optional, default model.rxns)
+0015 %   params        *obsolete option*
+0016 %   scores        vector of weights for the reactions. Negative scores
+0017 %                 should not have flux. Positive scores are not possible in this
+0018 %                 implementation, and they are changed to max(scores(scores<0)).
+0019 %                 Must have the same dimension as toMinimize (find(toMinimize)
+0020 %                 if it is a logical vector) (optional, default -1 for all reactions)
+0021 %   verbose       if true, the MILP progression will be shown.
+0022 %
+0023 %   x             the corresponding fluxes for the full model
+0024 %   I             the indexes of the reactions in toMinimize that were used
+0025 %                 in the solution
+0026 %   exitFlag      1: optimal solution found
+0027 %                -1: no feasible solution found
+0028 %                -2: optimization time out
+0029 %
+0030 %   NOTE: Uses 1000 mmol/gDW/h as an arbitary large flux. Could possibly
+0031 %   cause problems if the fluxes in the model are larger than that.
+0032 %
+0033 % Usage: [x,I,exitFlag]=getMinNrFluxes(model, toMinimize, params, scores)
+0034 
+0035 % glpk solver as implemented by COBRA does not work well for MILP.
+0036 global CBT_MILP_SOLVER
+0037 if strcmp(getpref('RAVEN','solver'),'cobra') && strcmp(CBT_MILP_SOLVER,'glpk')
+0038     dispEM('The current solver is set to ''cobra'', while in COBRA the MILP solver has been set to ''glpk''. The COBRA implementation of glpk is not well suitable for solving MILPs. Please install the Gurobi or an alternative MILP solver.',true);
+0039 end
+0040 
+0041 exitFlag=1;
+0042 
+0043 if nargin<2
+0044     toMinimize=model.rxns;
+0045 else
+0046     if ~iscell(toMinimize)
+0047         toMinimize=model.rxns(toMinimize);
+0048     end
+0049 end
+0050 
+0051 %For passing parameters to the solver
+0052 if nargin<3
+0053     params=struct();
+0054 end
+0055 
+0056 if nargin<4
+0057     %It says that the default is -1, but that is to fit with other code
+0058     scores=ones(numel(toMinimize),1)*1;
+0059 else
+0060     if numel(scores)~=numel(toMinimize)
+0061         EM='The number of scores must be the same as the number of reactions to minimize';
+0062         dispEM(EM);
+0063     end
+0064     
+0065     %Change positive scores to have a small negative weight. This is a
+0066     %temporary solution.
+0067     scores(scores>=0)=max(scores(scores<0));
+0068     
+0069     %It says that the default is -1, but that is to fit with other code
+0070     scores=scores*-1;
+0071 end
+0072 
+0073 %The trick to make this possible using a reversible model is that for
+0074 %reversible reactions, we do the following. Set the flux Vi == Vipos - Vineg.
+0075 %What happens then is that if the flux is positive, Vipos will have a nonzero value,
+0076 %and when the flux is negative, Vineg will have a positive value. In addition
+0077 %we can add an arbitrary constant to both Vipos and Vineg. For example, if the
+0078 %flux Vi is -1, Vineg can be 4 and Vipos 3. This is however not a problem,
+0079 %because we can be sure that Vineg + Vipos >= abs(Vi). Since we are interested
+0080 %in forcing the ints to be on when there is a flux, it doesn't matter if we overestimate
+0081 %the flux! So, we can simply constrain the boolean Yi to Yi*Maxflux >= Vineg + Vipos.
+0082 
+0083 %The matrix then becomes as this:
+0084 %         S       p n int b     var
+0085 %         SSSSSSSS        -
+0086 %         SSSSSSSS         -
+0087 %         SSSSSSSS          -
+0088 %         SSSSSSSS           -
+0089 %         SSSSSSSS            -
+0090 %         SSSSSSSS             -
+0091 %         -       1 -
+0092 %               -  1 -
+0093 %           -          M         -
+0094 %             -         M         -
+0095 %                 - - M         -
+0096 %                  - -   M         -
+0097 % An example with 8 rxns and 6 metabolites. - means -1, M max flux, and S is the S matrix.
+0098 % 4 rxns are to be minimized(1,3,5,7) and 1,7 are reversible. The p and n
+0099 % are the Vipos and Vineg variables (2 rxns of each). The ints are the Yi for
+0100 % the variables that are to be minimized (the rest of the rxns doesn't have any).
+0101 % The mets here are the constraints, so right under the S matrix, you have
+0102 % Vi == Vipos - Vineg for the reactions 1 and 7 while the two next rows represent
+0103 % the non-reversible rxns 3 and 5, where we simply say that yi*M >= Vi. The last
+0104 % 2 rows are the reactions yi*M >= Vipos + Vineg. To the right, we first have a
+0105 % -I matrix for setting the b constraints, and under that we have rxns that are
+0106 % just variables (rxns) between 0 and Inf to complete the constraints mentioned above.
+0107 %Ex: yi*M >= Vipos + Vineg is impl. as yi*M - Vipos - Vineg - var == 0, 0 <= var <= Inf.
+0108 %
+0109 %All rows should be equal to zero, so we don't set the b vector in the problem
+0110 %The reactions should be constrained as follows
+0111 %S - as given in model.lb and model.ub
+0112 %pos and neg - between 0 and inf
+0113 %ints - between 0 and 1
+0114 %b - as stated in the model.b vector - if this has one column, that is lb and ub (fixed value), if two columns, that is lb and ub
+0115 %var - between zero and inf
+0116 
+0117 [minLog, I]=ismember(model.rxns,toMinimize);
+0118 indexes=find(minLog);
+0119 revIndexes = find(minLog & (model.rev == 1));
+0120 irrevIndexes = find(minLog & (model.rev == 0));
+0121 revIndexesInInd = find(model.rev(indexes) == 1);
+0122 irrevIndexesInInd = find(model.rev(indexes) == 0);
+0123 
+0124 %Add binary constraints in the following manner: -  Add one unique
+0125 %"metabolite" for each integer reaction as a substrate.
+0126 %   These metabolites can have net production
+0127 %-  Add reactions for the production of each of those metabolites. The
+0128 %   amount produced in one reaction unit must be larger than the largest
+0129 %   possible flux in the model (but not too large to avoid bad scaling)
+0130 
+0131 maxFlux=1000;
+0132 %we build the total matrix as blocks: [S pos neg int b var]
+0133 
+0134 %s block
+0135 intArray=speye(numel(model.rxns))*-1;
+0136 intArrayRev=intArray(revIndexes,:);
+0137 intArrayIrrev = intArray(irrevIndexes,:);
+0138 sBlock=[model.S;intArrayRev;intArrayIrrev;sparse(numel(revIndexes), numel(model.rxns))]; %the S matrix and what is below
+0139 
+0140 %pos/neg blocks
+0141 revposorneg1 = sparse(numel(model.mets), numel(revIndexes));
+0142 revpos2 = speye(numel(revIndexes));
+0143 revneg2 = -revpos2;
+0144 revposneg3 = sparse(numel(irrevIndexes), numel(revIndexes));
+0145 revposneg4 = revneg2;
+0146 posBlock = [revposorneg1;revpos2;revposneg3;revposneg4];
+0147 negBlock = [revposorneg1;revneg2;revposneg3;revposneg4];
+0148 
+0149 %int block
+0150 int1 = sparse(numel(model.mets), numel(indexes));
+0151 int2 = sparse(numel(revIndexes), numel(indexes));
+0152 tmpEye = speye(numel(indexes))*maxFlux;
+0153 int3 = tmpEye(irrevIndexesInInd,:);%we here select only the irrev indexes from the indexes
+0154 int4 = tmpEye(revIndexesInInd,:);
+0155 intBlock = [int1;int2;int3;int4];
+0156 
+0157 %b block
+0158 b1 = speye(numel(model.mets))*-1;
+0159 b2 = sparse(numel(indexes) + numel(revIndexes), numel(model.mets));
+0160 bBlock = [b1;b2];
+0161 
+0162 %var block
+0163 var1 = sparse(numel(model.mets), numel(indexes));
+0164 var2 = sparse(numel(revIndexes), numel(indexes));
+0165 tmpEye = speye(numel(indexes))*-1;
+0166 var3 = tmpEye(irrevIndexesInInd,:);
+0167 var4 = tmpEye(revIndexesInInd,:);
+0168 varBlock = [var1;var2;var3;var4];
+0169 
+0170 prob.A = [sBlock posBlock negBlock intBlock bBlock varBlock];
+0171 prob.a = prob.A;%I think this is needed as well
+0172 
+0173 prob.c=[zeros(numel(model.rxns),1);zeros(numel(revIndexes)*2,1); scores(:);zeros(numel(model.mets) + numel(indexes),1)]; %Minimize the sum of reaction scores for reactions that are on
+0174 
+0175 %ub and lb, text copied from above
+0176 %S - as given in model.lb and model.ub
+0177 %pos and neg - between 0 and inf
+0178 %ints - between 0 and 1
+0179 %b - as stated in the model.b vector - if this has one column, that is lb and ub (fixed value), if two columns, that is lb and ub
+0180 %var - between zero and inf
+0181 
+0182 if size(model.b,2)==2
+0183     bub = model.b(:,2);
+0184 else
+0185     bub = model.b(:,1);
+0186 end
+0187 
+0188 prob.lb = [model.lb;zeros(numel(revIndexes)*2,1);zeros(numel(indexes),1);model.b(:,1);zeros(numel(indexes),1)];
+0189 prob.ub = [model.ub;inf(numel(revIndexes)*2,1);ones(numel(indexes),1);bub;inf(numel(indexes),1)];
+0190 
+0191 prob.b=zeros(size(prob.a,1), 1);
+0192 
+0193 %Use the output from the linear solution as starting point. Only the values
+0194 %for the integer variables will be used, but all are supplied.
+0195 intsIndexes = find(prob.c ~= 0);
+0196 %The start point is not important (solved quickly anyway), so just skip it.
+0197 %prob.sol.int.xx=zeros(numel(prob.c),1);
+0198 %prob.sol.int.xx(intsIndexes(sol.x(indexes)>10^-3))=1;%these doesn't work for gurobi anyways...
+0199 prob.x0=[];
+0200 prob.vartype=repmat('C', 1, size(prob.A,2));
+0201 prob.vartype(intsIndexes) = 'B';
+0202 prob.csense = repmat('E', 1, size(prob.A,1));
+0203 prob.osense=1; %minimize the objective
+0204 
+0205 %prob=rmfield(prob,{'blx','bux','blc','buc'});
+0206 params.intTol = 10^-9; %experment with this value
+0207 params.TimeLimit = 300;
+0208 params.Seed = 26;%This is weird - although it says "optimal solution found", we can get different results with different
+0209                  %values of the objective function, where one is more optimal than the other (pretty big difference...)
+0210 params.Threads = 1; %single-threaded Gurobi MILP for determinism, see issue #607
+0211 %params.CSClientLog = 3;%generates a warning in gurobi, but may be of interest for other solvers
+0212 
+0213 % Optimize the problem
+0214 res = optimizeProb(prob,params,verbose);
+0215 isFeasible=checkSolution(res);
+0216 
+0217 if ~isFeasible
+0218     x=[];
+0219     I=[];
+0220     exitFlag=-1;
+0221     return;
+0222 end
+0223 
+0224 x=res.full(1:numel(model.rxns));%the fluxes
+0225 I=res.full(intsIndexes) > 10^-3;%The margin for integers in gurobi is 10^-5, not 10^-12 that was previously used! Use 10^-3 to have some margin!
+0226 
+0227 tmp = res.full(intsIndexes);
+0228 sel = (tmp > 10^-12) & (tmp < 0.5);
+0229 if sum(sel) > 0
+0230     %This may indicate that there is a problem with the tolerances in the solver
+0231     disp(['ftINITFillGapsMILP: Some variables meant to be boolean in the MILP have intermediate values. Num vars: ' num2str(sum(sel))])
+0232 end
+0233 
+0234 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/INIT/ftINITInternalAlg.html b/doc/INIT/ftINITInternalAlg.html new file mode 100644 index 000000000..d03684e08 --- /dev/null +++ b/doc/INIT/ftINITInternalAlg.html @@ -0,0 +1,551 @@ + + + + Description of ftINITInternalAlg + + + + + + + + + +
Home > INIT > ftINITInternalAlg.m
+ + + +

ftINITInternalAlg +

+ +

PURPOSE ^

+
ftINITInternalAlg
+ +

SYNOPSIS ^

+
function [deletedRxns,metProduction,res,turnedOnRxns,fluxes]=ftINITInternalAlg(model,rxnScores,metData,essentialRxns,prodWeight,allowExcretion,remPosRev,params,startVals,fluxes,verbose)
+ +

DESCRIPTION ^

+
 ftINITInternalAlg
+    This function runs the MILP for a step in ftINIT.
+
+   model           a reference model structure
+   rxnScores       a vector of scores for the reactions in the model.
+                   Positive scores are reactions to keep and negative
+                   scores are reactions to exclude. Rxns set to 0 are excluded
+                   from the problem.
+   metData         boolean matrix with mets as rows and rxns as columns
+                   saying which reaction produces each detected met (optional, default [])
+   essentialRxns   cell array of reactions that are essential and that
+                   have to be in the resulting model. This is normally
+                   used when fitting a model to task (see fitTasks)
+   prodWeight      a score that determines the value of having
+                   net-production of metabolites. This is a way of having
+                   a more functional network as it provides a reason for
+                   including bad reactions for connectivity reasons. This
+                   score is for each metabolite, and the sum of these weights
+                   and the scores for the reactions is what is optimized
+   allowExcretion  true if excretion of all metabolites should be allowed.
+                   This results in fewer reactions being considered
+                   dead-ends, but all reactions in the resulting model may
+                   not be able to carry flux. If this is "false" then the
+                   equality constraints are taken from model.b. If the
+                   input model lacks exchange reactions then this should
+                   probably be "true", or a large proportion of the model
+                   would be excluded for connectivity reasons
+   remPosRev       If true, the positive reversible reactions are removed from the problem.
+                   This is used in step 1 of ftINIT
+   params          parameters for the MILP, for example MIPGap and TimeLimit
+   startVals       Start values for the MILP, typically used when rerunning
+                   with a higher MIPGap, to use the results from the previous
+                   run
+   fluxes          Fluxes from the last run.
+   verbose         If true, the MILP progression will be shown. 
+
+   deletedRxns     reactions which were deleted by the algorithm (only 
+                   rxns included in the problem)
+   metProduction   array that indicates which of the
+                   metabolites in presentMets that could be
+                   produced
+                   0: metabolite could not be produced
+                   1: metabolite could be produced
+   res             The result from the MILP
+   turnedOnRxns    The reactions determined to be present (only 
+                   rxns included in the problem) 
+   fluxes          The fluxes from the MILP
+
+   This function is the actual implementation of the algorithm. See
+   ftINIT for a higher-level function for model reconstruction. 
+
+ Usage: [deletedRxns,metProduction,res,turnedOnRxns,fluxes]=runINIT9(model,...
+           rxnScores,presentMets,essentialRxns,prodWeight,allowExcretion,...
+           remPosRev,params)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function [deletedRxns,metProduction,res,turnedOnRxns,fluxes]=ftINITInternalAlg(model,rxnScores,metData,essentialRxns,prodWeight,allowExcretion,remPosRev,params,startVals,fluxes,verbose)
+0002 % ftINITInternalAlg
+0003 %    This function runs the MILP for a step in ftINIT.
+0004 %
+0005 %   model           a reference model structure
+0006 %   rxnScores       a vector of scores for the reactions in the model.
+0007 %                   Positive scores are reactions to keep and negative
+0008 %                   scores are reactions to exclude. Rxns set to 0 are excluded
+0009 %                   from the problem.
+0010 %   metData         boolean matrix with mets as rows and rxns as columns
+0011 %                   saying which reaction produces each detected met (optional, default [])
+0012 %   essentialRxns   cell array of reactions that are essential and that
+0013 %                   have to be in the resulting model. This is normally
+0014 %                   used when fitting a model to task (see fitTasks)
+0015 %   prodWeight      a score that determines the value of having
+0016 %                   net-production of metabolites. This is a way of having
+0017 %                   a more functional network as it provides a reason for
+0018 %                   including bad reactions for connectivity reasons. This
+0019 %                   score is for each metabolite, and the sum of these weights
+0020 %                   and the scores for the reactions is what is optimized
+0021 %   allowExcretion  true if excretion of all metabolites should be allowed.
+0022 %                   This results in fewer reactions being considered
+0023 %                   dead-ends, but all reactions in the resulting model may
+0024 %                   not be able to carry flux. If this is "false" then the
+0025 %                   equality constraints are taken from model.b. If the
+0026 %                   input model lacks exchange reactions then this should
+0027 %                   probably be "true", or a large proportion of the model
+0028 %                   would be excluded for connectivity reasons
+0029 %   remPosRev       If true, the positive reversible reactions are removed from the problem.
+0030 %                   This is used in step 1 of ftINIT
+0031 %   params          parameters for the MILP, for example MIPGap and TimeLimit
+0032 %   startVals       Start values for the MILP, typically used when rerunning
+0033 %                   with a higher MIPGap, to use the results from the previous
+0034 %                   run
+0035 %   fluxes          Fluxes from the last run.
+0036 %   verbose         If true, the MILP progression will be shown.
+0037 %
+0038 %   deletedRxns     reactions which were deleted by the algorithm (only
+0039 %                   rxns included in the problem)
+0040 %   metProduction   array that indicates which of the
+0041 %                   metabolites in presentMets that could be
+0042 %                   produced
+0043 %                   0: metabolite could not be produced
+0044 %                   1: metabolite could be produced
+0045 %   res             The result from the MILP
+0046 %   turnedOnRxns    The reactions determined to be present (only
+0047 %                   rxns included in the problem)
+0048 %   fluxes          The fluxes from the MILP
+0049 %
+0050 %   This function is the actual implementation of the algorithm. See
+0051 %   ftINIT for a higher-level function for model reconstruction.
+0052 %
+0053 % Usage: [deletedRxns,metProduction,res,turnedOnRxns,fluxes]=runINIT9(model,...
+0054 %           rxnScores,presentMets,essentialRxns,prodWeight,allowExcretion,...
+0055 %           remPosRev,params)
+0056 
+0057 if isempty(essentialRxns)
+0058     essentialRxns={};
+0059 end
+0060 essentialRxns=essentialRxns(:);
+0061 if isempty(prodWeight)
+0062     prodWeight=0.5;
+0063 end
+0064 
+0065 
+0066 %The model should be in the reversible format and all relevant exchange
+0067 %reactions should be open
+0068 if isfield(model,'unconstrained')
+0069     EM='Exchange metabolites are still present in the model. Use simplifyModel if this is not intended';
+0070     dispEM(EM,false);
+0071 end
+0072 
+0073 
+0074 essential = ismember(model.rxns,essentialRxns);
+0075 
+0076 %Some nice to have numbers
+0077 nMets=numel(model.mets);
+0078 nRxns=numel(model.rxns);
+0079 nRxnsWithOnOff = nRxns;
+0080 
+0081 %Reactions with score 0 will just be left in the model, and will not be part of the problem (but can carry flux).
+0082 %It is possible to set score = 0 for e.g. spontaneous reactions, exchange rxns, etc., which may not be that interesting
+0083 %to remove.
+0084 
+0085 %if makeIrrev is on, we can just as well skip all positive reversible rxns - they will be turned on without carrying any flux
+0086 %since they can form a loop within themself (fwd-rev)
+0087 if remPosRev
+0088     rxnScores(rxnScores > 0 & model.rev~=0) = 0;
+0089 end
+0090 
+0091 %Handle metabolomics
+0092 %A problem with the metabolomics is that some of the producer reactions
+0093 %for a metabolite could be excluded from the problem. We solve this by
+0094 %adding them with score 0. They can still be seen as positive, since they
+0095 %either don't matter (there is another producer) or they can contribute to an
+0096 %increased score.
+0097 revRxns=model.rev~=0; 
+0098 essRevRxns = find(revRxns & essential);
+0099 essIrrevRxns = find(~revRxns & essential);
+0100 
+0101 if ~isempty(metData)
+0102     %remove any metData rows that is connected to an essential rxn -
+0103     %these will be on regardless and will cause problems below.
+0104     containsEssential = any(metData(:,essential),2);
+0105     metData = metData(~containsEssential,:);
+0106 end
+0107 
+0108 if ~isempty(metData)
+0109     metRxns = any(metData,1).';
+0110     posRxns = rxnScores > 0 | ((rxnScores == 0) & metRxns);
+0111 else
+0112     posRxns = rxnScores > 0;
+0113 end
+0114 negRxns = rxnScores < 0;
+0115 
+0116 posRevRxns = find(posRxns & revRxns & ~essential);
+0117 negRevRxns = find(negRxns & revRxns & ~essential);
+0118 posIrrevRxns = find(posRxns & ~revRxns & ~essential);
+0119 negIrrevRxns = find(negRxns & ~revRxns & ~essential);
+0120 nPosRev = numel(posRevRxns);
+0121 nNegRev = numel(negRevRxns);
+0122 nPosIrrev = numel(posIrrevRxns);
+0123 nNegIrrev = numel(negIrrevRxns);
+0124 nEssRev = numel(essRevRxns);
+0125 nEssIrrev = numel(essIrrevRxns); %not used, but left for symmetry
+0126 nMetabolMets = size(metData,1);
+0127 
+0128 if ~isempty(metData)
+0129     metNegRev = negRxns & revRxns & ~essential & metRxns;
+0130     metNegIrrev = negRxns & ~revRxns & ~essential & metRxns;
+0131     nMetNegRev = sum(metNegRev);
+0132     nMetNegIrrev = sum(metNegIrrev);
+0133 end
+0134 
+0135 
+0136 milpModel = model;
+0137 
+0138 %These six categories need to be handled separately:
+0139 %
+0140 %PosIrrev (positive reaction score, irreversible):
+0141 %flux >= 0.1*Yi, flux - 0.1*Yi - VPI == 0, 0 <= Yi(onoff) <= 1, 0 <= VPI <= Inf
+0142 %The nice thing with rxns with positive score is that they do not require a boolean. The optimizer will
+0143 %strive for maximizing the Yi here, so it can be a continuous variable, where we just force a flux if
+0144 %the variable is on.
+0145 %PosRev:
+0146 % 1: Split up the flux into positive and negative: flux - vnrp + vnrn == 0, 0 <= vprp,vprn <= Inf.
+0147 % 2. Force one of the fluxes on: vprp + vprn >= 0.1*Yi, vprp + vprn - 0.1*Yi - vprv1 == 0. 0 <= Yi(onoff) <= 1, vprv1 >= 0
+0148 % 3. We need a bool to make sure that one of vprp and vprn are always zero:
+0149 %    vprb E {0,1}:  vprp <= 100*vprb (if bool is 0, vprp is zero): vprp - 100*vprb + vprv2 == 0, vprv2 >= 0
+0150 %    vprn <= (1-vprb)*100 (if bool is one, vprn is zero): vprn + 100*vprb + vprv3 == 0, -100 <= vprv3 <= inf
+0151 %Neg Irrev:
+0152 %For negative scores, we need to use an integer, I see no way around that.
+0153 % flux < 100*Yi, Yi E {0,1}. Flux - 100*Yi + vni == 0
+0154 %Neg Rev:
+0155 %Two cases:
+0156 %A: Without irrev model
+0157 % 1: Split up the flux into positive and negative: flux - vnrp + vnrn == 0, 0 <= vprp,vprn <= Inf.
+0158 % 2: Force the Yi (on/off) var on if the flux is on: vnrp + vnrn <= 0.1 * Yi, Yi E {0,1}: vnrp + vnrn - 0.1 * Yi + vnrv1 == 0, vnrv1 >= 0.
+0159 %B: Irrev model (Not used for now)
+0160 % 1. We now have two reactions, but still just boolean variable. We know that
+0161 %    the flux can only be positive, so we just say that flux1 + flux2 <= 0.1 * Yi, Yi E {0,1}: flux1 + flux2 - 0.1 * Yi + vnrv1 == 0, vnrv1 >= 0.
+0162 %    We don't care if there is any loop - there is just no benefit for the objective to generate one, and it doesn't matter.
+0163 %Ess Irrev (essential rxn, i.e. forced to carry flux, irreversible):
+0164 %flux >= 0.1 - solved with lb = 0.1.
+0165 %Ess Rev (these are not really used):
+0166 % 1: Split up the flux into positive and negative: flux - verp + vern == 0, 0 <= verp,vern <= Inf.
+0167 % 2. Force one of the fluxes on: verp + vern >= 0.1, verp + vern - verv1 == 0. verv1 >= 0.1
+0168 % 3. We need a bool to make sure that one of verp and vern are always zero:
+0169 %    verb E {0,1}:  verp <= 100*verb (if bool is 0, verp is zero): verp - 100*verb + verv2 == 0, verv2 >= 0
+0170 %    vern <= (1-verb)*100 (if bool is one, vern is zero): vern + 100*verb + verv3 == 0, -100 <= verv3 <= inf
+0171 
+0172 % Now metabolomics
+0173 % The basic idea is that the bonus is gotten if any of the producer reactions are on. We can
+0174 % therefore use the "on" variables directly for the reactions that are included. We therefore add one variable per met, mon, which can be
+0175 % continuous and between 0 and 1. We then say that mon <= v1 + v2 + ... + vn, i.e. that
+0176 % mon + mv1 - v1 - v2 ... - vn == 0, 0 <= mon <= 1, 0 <= mv1 <= inf
+0177 % mon gets -prodWeight in the c vector (i.e. objective function)
+0178 % A tricky part is that some of the reactions producing a metabolite are left outside the problem
+0179 % This is solved by moving them into the problem, but with the score 0. They can still be treated as positive
+0180 % reactions. In the end, we are not interested if they are on though, but they may
+0181 % allow for production of a metabolite, giving no benefit of turning on another producer reaction.
+0182 % Another tricky thing is that some metabolite producers have negative score. There is
+0183 % no automatic mechanism for forcing flux on if the variable is on - this is simply
+0184 % not needed for negative variables - unless they are a metabolite producer. We therefore need
+0185 % to add an extra constraint there, similar to the case of positive. It gets a bit complicated.
+0186 % For reversible, we need a bool to make sure that one of vnrp and vnrn stays zero:
+0187 %    vnrbm E {0,1}:  vnrp <= 100*vnrbm (if bool is 0, vnrp is zero): vnrp - 100*vnrbm + vnrvm1 == 0, vnrvm1 >= 0
+0188 %    vnrn <= (1-vnrbm)*100 (if bool is one, vnrn is zero): vnrn + 100*vnrbm + vnrvm2 == 0, -100 <= vnrvm2 <= inf
+0189 % We then also say that vnrp + vnrn >= 0.1*Yi, vnrp + vnrn - 0.1*Yi - vnrvm3 == 0, vnrvm3 >= 0
+0190 % For irreversible, it is fairly straight-forward. We just say that flux >= 0.1*Yi, i.e. flux - 0.1*Yi - vnim == 0, 0 <= vnim <= Inf.
+0191 
+0192 
+0193 %The total matrix then looks like this. Note that we have ordered the categories, two reactions each,
+0194 %in the S matrix to make it easier to follow the figure. In practice, they come in random order, which
+0195 %is why the SEye variable is used further down.
+0196 %all categories below have two columns - the two column starts where label starts
+0197 %since the label cannot fit in two chars, they are on multiple lines
+0198 %
+0199 %The met variables and constraints are not in this figure for practical reasons.
+0200 %
+0201 %                           vprb  vprv3 vnrn  vern  verv2 mv1
+0202 % pi  ni  ei  Ypi Yni vpi vprn  vprv2 vnrp  verp  verb  mon
+0203 %   pr  nr  er  Ypr Ynr vprp  vprv1 vni   vnrv1 verv1 verv3
+0204 % SSSSSSSSSSSS0000000000000000000000000000000000000000000000
+0205 % SSSSSSSSSSSS0000000000000000000000000000000000000000000000 S block
+0206 % SSSSSSSSSSSS0000000000000000000000000000000000000000000000
+0207 % 1           N       -                                      Pos irrev block
+0208 %  1           N       -
+0209 %   1                   - 1                                  Pos rev block 1
+0210 %    1                   - 1
+0211 %               N       1 1   -                              Pos rev block 2
+0212 %                N       1 1   -
+0213 %                       1   M   1                            Pos rev block 3
+0214 %                        1   M   1
+0215 %                         1 C     1                          Pos rev block 4
+0216 %                          1 C     1
+0217 %     1           M                 1                        Neg irrev block
+0218 %      1           M                 1
+0219 %       1                             - 1                    Neg rev block 1
+0220 %        1                             - 1
+0221 %                   M                 1 1 1                  Neg rev block 2
+0222 %                    M                 1 1 1
+0223 %           1                               - 1              Ess rev block 1
+0224 %            1                               - 1
+0225 %                                           1 1 -            Ess rev block 2
+0226 %                                            1 1 -
+0227 %                                           1     M 1        Ess rev block 3
+0228 %                                            1     M 1
+0229 %                                             1   C   1      Ess rev block 4
+0230 %                                              1   C   1
+0231 %             --------                                  1 1  Met block - Here, we assume that all variables support each met.
+0232 %             --------                                   1 1             In practice, fewer of the "on" variables with -1 should be included
+0233 %
+0234 %
+0235 %M = -100
+0236 %N = -0.1
+0237 %D = 0.1
+0238 %C = 100
+0239 %- = -1
+0240 %
+0241 %It looks a bit different for the irrev model, but still quite similar
+0242 
+0243 %build the A matrix
+0244 %S row
+0245 %When forcing on essential rxns, use the flux value of the previous run (set to 0.1 the first time)
+0246 %Don't set it above 0.1, may starve something else out. Leave a margin of 1% from the last run.
+0247 forceOnLim = 0.1;
+0248 forceOnLimEss=min(abs(fluxes)*0.99,0.1);
+0249 
+0250 varsPerNegRev = 3;
+0251 
+0252 
+0253 %Figure out the number of variables needed for metabolomics
+0254 if ~isempty(metData)
+0255     nMetVars = 2*size(metData,1) + 4*nMetNegRev + nMetNegIrrev; %mon,mv1; vnrbm,vnrvm1,vnrvm2,vnrvm3; vnim
+0256 else
+0257     nMetVars = 0;
+0258 end
+0259 
+0260 
+0261 sRow = [milpModel.S sparse(nMets, nPosIrrev*2+nPosRev*7+nNegIrrev*2+nNegRev*(1+varsPerNegRev)+nEssRev*6 + nMetVars)];
+0262 sEye = speye(nRxns);
+0263 nYBlock = nPosIrrev+nPosRev+nNegIrrev+nNegRev;
+0264 piRows = [sEye(posIrrevRxns,:) speye(nPosIrrev)*-forceOnLim sparse(nPosIrrev,nPosRev+nNegIrrev+nNegRev) speye(nPosIrrev)*-1 sparse(nPosIrrev,nPosRev*6+nNegIrrev+nNegRev*varsPerNegRev+nEssRev*6+nMetVars)];
+0265 
+0266 prRows1 = [sEye(posRevRxns,:) sparse(nPosRev,nYBlock + nPosIrrev) speye(nPosRev)*-1 speye(nPosRev) sparse(nPosRev,nPosRev*4+nNegIrrev+nNegRev*varsPerNegRev+nEssRev*6+nMetVars)];
+0267 prRows2 = [sparse(nPosRev,nRxns + nPosIrrev) speye(nPosRev)*-forceOnLim sparse(nPosRev,nNegIrrev + nNegRev + nPosIrrev) speye(nPosRev) speye(nPosRev) sparse(nPosRev,nPosRev) speye(nPosRev)*-1 sparse(nPosRev,nPosRev*2+nNegIrrev+nNegRev*varsPerNegRev+nEssRev*6+nMetVars)];
+0268 prRows3 = [sparse(nPosRev,nRxns + nYBlock + nPosIrrev) speye(nPosRev) sparse(nPosRev,nPosRev) speye(nPosRev)*-100 sparse(nPosRev,nPosRev) speye(nPosRev) sparse(nPosRev,nPosRev+nNegIrrev+nNegRev*varsPerNegRev+nEssRev*6+nMetVars)];
+0269 prRows4 = [sparse(nPosRev,nRxns + nYBlock + nPosIrrev + nPosRev) speye(nPosRev) speye(nPosRev)*100 sparse(nPosRev,nPosRev*2) speye(nPosRev) sparse(nPosRev, nNegIrrev+nNegRev*varsPerNegRev+nEssRev*6+nMetVars)];
+0270 
+0271 niRows = [sEye(negIrrevRxns,:) sparse(nNegIrrev,nPosIrrev + nPosRev) speye(nNegIrrev)*-100 sparse(nNegIrrev,nNegRev + nPosIrrev + nPosRev*6) speye(nNegIrrev) sparse(nNegIrrev,nNegRev*varsPerNegRev + nEssRev*6+nMetVars)];
+0272 
+0273 nrRows1 = [sEye(negRevRxns,:) sparse(nNegRev,nYBlock + nPosIrrev + nPosRev*6 + nNegIrrev) speye(nNegRev)*-1 speye(nNegRev) sparse(nNegRev,nNegRev + nEssRev*6+nMetVars)];
+0274 nrRows2 = [sparse(nNegRev,nRxns + nPosIrrev + nPosRev + nNegIrrev) speye(nNegRev)*-100 sparse(nNegRev,nPosIrrev + nPosRev*6 + nNegIrrev) speye(nNegRev) speye(nNegRev) speye(nNegRev) sparse(nNegRev,nEssRev*6+nMetVars)];
+0275 nrRows = [nrRows1;nrRows2];
+0276 
+0277 erRows1 = [sEye(essRevRxns,:) sparse(nEssRev,nYBlock + nPosIrrev + nPosRev*6 + nNegIrrev + nNegRev*varsPerNegRev) speye(nEssRev)*-1 speye(nEssRev) sparse(nEssRev, nEssRev*4+nMetVars)];
+0278 erRows2 = [sparse(nEssRev,nRxns + nYBlock + nPosIrrev + nPosRev*6 + nNegIrrev + nNegRev*varsPerNegRev) speye(nEssRev) speye(nEssRev) speye(nEssRev)*-1 sparse(nEssRev, nEssRev*3+nMetVars)];
+0279 erRows3 = [sparse(nEssRev,nRxns + nYBlock + nPosIrrev + nPosRev*6 + nNegIrrev + nNegRev*varsPerNegRev) speye(nEssRev) sparse(nEssRev, nEssRev*2) speye(nEssRev)*-100 speye(nEssRev) sparse(nEssRev, nEssRev+nMetVars)];
+0280 erRows4 = [sparse(nEssRev,nRxns + nYBlock + nPosIrrev + nPosRev*6 + nNegIrrev + nNegRev*varsPerNegRev + nEssRev) speye(nEssRev) sparse(nEssRev, nEssRev) speye(nEssRev)*100 sparse(nEssRev, nEssRev) speye(nEssRev) sparse(nEssRev, nMetVars)];
+0281 
+0282 %now the mets
+0283 if ~isempty(metData)
+0284     %Order of rxn "on" vars: Ypi Ypr Yni Ynr. This is a bit messy, since they are not in the
+0285     %same order as the reactions in the S matrix or metData. We therefore resort the vars in
+0286     %metData to match the order of the vars.
+0287     srtMetData = sparse([metData(:,posIrrevRxns) metData(:,posRevRxns) metData(:,negIrrevRxns) metData(:,negRevRxns)]);
+0288     
+0289     %First the setup for giving bonus if the met is included.
+0290     %The mon vars come first followed by the mv1 vars
+0291     metRows1 = [sparse(nMetabolMets,nRxns) -srtMetData sparse(nMetabolMets,  nPosIrrev + nPosRev*6 + nNegIrrev + nNegRev*varsPerNegRev + nEssRev*6) speye(nMetabolMets) speye(nMetabolMets) sparse(nMetabolMets, 4*nMetNegRev + nMetNegIrrev)];
+0292     %Then negative rev:
+0293     % Variable order: eye(vnrbm),eye(vnrvm1),eye(vnrvm2),eye(vnrvm3)
+0294     % vnrp,vnrn are the two first variables among the neg rev vars.
+0295     % For reversible, we need a bool to make sure that one of vnrp and vnrn stays zero:
+0296     %    vnrbm E {0,1}:  vnrp <= 100*vnrbm (if bool is 0, vnrp is zero): vnrp - 100*vnrbm + vnrvm1 == 0, vnrvm1 >= 0 (metRows2)
+0297     %    vnrn <= (1-vnrbm)*100 (if bool is one, vnrn is zero): vnrn + 100*vnrbm + vnrvm2 == 0, -100 <= vnrvm2 <= inf (metRows3)
+0298     % We then also say that vnrp + vnrn >= 0.1*Yi, -0.1*Yi + vnrp + vnrn - vnrvm3 == 0, vnrvm3 >= 0 (metRows4)
+0299     nrEye = speye(nNegRev);
+0300     %vnrp - 100*vnrbm + vnrvm1 == 0
+0301     metRows2 = [sparse(nMetNegRev,nRxns + nYBlock + nPosIrrev + nPosRev*6 + nNegIrrev) ... %zeros up to vnrp
+0302                 nrEye(metNegRev(negRevRxns),:) ... %vnrp 
+0303                 sparse(nMetNegRev, nNegRev*(varsPerNegRev-1) + nEssRev*6 + nMetabolMets*2) ... %zeros up to vnrbm
+0304                 speye(nMetNegRev)*-100 ... %vnrbm
+0305                 speye(nMetNegRev) ... % vnrvm1
+0306                 sparse(nMetNegRev, nMetNegRev*2 + nMetNegIrrev)];%fill up the rest with zeros
+0307     %vnrn + 100*vnrbm + vnrvm2 == 0
+0308     metRows3 = [sparse(nMetNegRev,nRxns + nYBlock + nPosIrrev + nPosRev*6 + nNegIrrev + nNegRev) ... %zeros up to vnrn
+0309                 nrEye(metNegRev(negRevRxns),:) ... %vnrp 
+0310                 sparse(nMetNegRev, nNegRev*(varsPerNegRev-2) + nEssRev*6 + nMetabolMets*2) ... %zeros up to vnrbm
+0311                 speye(nMetNegRev)*100 ... %vnrbm
+0312                 sparse(nMetNegRev, nMetNegRev) ... %zeros up to vnrvm2
+0313                 speye(nMetNegRev) ... % vnrvm2
+0314                 sparse(nMetNegRev, nMetNegRev + nMetNegIrrev)];%fill up the rest with zeros
+0315     %-0.1*Yi + vnrp + vnrn - vnrvm3 == 0
+0316     metRows4 = [sparse(nMetNegRev,nRxns + nPosIrrev + nPosRev + nNegIrrev) ... %zeros up to Yi for neg rev
+0317                 nrEye(metNegRev(negRevRxns),:)*-0.1 ... %Yi for met neg rev
+0318                 sparse(nMetNegRev, nPosIrrev + nPosRev*6 + nNegIrrev) ... %zeros up to vnrp
+0319                 nrEye(metNegRev(negRevRxns),:) ... %vnrp
+0320                 nrEye(metNegRev(negRevRxns),:) ... %vnrn
+0321                 sparse(nMetNegRev, nNegRev*(varsPerNegRev-2) + nEssRev*6 + nMetabolMets*2 + nMetNegRev*3) ...%zeros up to vnrvm3
+0322                 speye(nMetNegRev)*-1 ... % vnrvm3
+0323                 sparse(nMetNegRev, nMetNegIrrev)];%fill up the rest with zeros
+0324     
+0325     %Then negative irrev, i.e. flux - 0.1*Yi - vnim == 0
+0326     niEye = speye(nNegIrrev);
+0327     metRows5 = [sEye(metNegIrrev,:) ... %flux
+0328                 sparse(nMetNegIrrev, nPosIrrev + nPosRev) ... % zeros up to Yi for neg irrev
+0329                 niEye(metNegIrrev(negIrrevRxns),:)*-0.1 ... %Yi for met neg irrev
+0330                 sparse(nMetNegIrrev, nNegRev + nPosIrrev + nPosRev*6 + nNegIrrev + nNegRev*varsPerNegRev + nEssRev*6 + nMetabolMets*2 + 4*nMetNegRev) ... %zeros up to vnim
+0331                 -speye(nMetNegIrrev) ]; %vnim
+0332     metRows = [metRows1;metRows2;metRows3;metRows4;metRows5];
+0333     metVarC = [ones(nMetabolMets,1)*-prodWeight;zeros(nMetVars - nMetabolMets,1)];
+0334     %vnrbm is boolean, so between 0 and 1
+0335     %vnrvm1 >= 0
+0336     %-100 <= vnrvm2 <= inf
+0337     % vnrvm3 >= 0
+0338     %0 <= vnim <= Inf
+0339     metLb = [zeros(nMetabolMets*2 + 2*nMetNegRev,1);ones(nMetNegRev,1)*-100;zeros(nMetNegRev + nMetNegIrrev,1)];
+0340     metUb = [ones(nMetabolMets,1);inf(nMetabolMets,1);ones(nMetNegRev,1);inf(3*nMetNegRev + nMetNegIrrev,1)];
+0341     metVartype = [repmat('C', 1, nMetabolMets*2), ...
+0342                   repmat('B', 1, nMetNegRev), ...
+0343                   repmat('C', 1, 3*nMetNegRev + nMetNegIrrev)];
+0344 
+0345 else
+0346     metRows = [];
+0347     metVarC = [];
+0348     metLb = [];
+0349     metUb = [];
+0350     metVartype = [];
+0351 end
+0352 
+0353 prob.a = [sRow;piRows;prRows1;prRows2;prRows3;prRows4;niRows;nrRows;erRows1;erRows2;erRows3;erRows4;metRows];
+0354 prob.A = prob.a;
+0355 prob.b = zeros(size(prob.A,1),1);
+0356 prob.c = [zeros(nRxns,1);rxnScores(posIrrevRxns)*-1;rxnScores(posRevRxns)*-1;rxnScores(negIrrevRxns)*-1;rxnScores(negRevRxns)*-1;zeros(nPosIrrev + nPosRev*6 + nNegIrrev + nNegRev*varsPerNegRev + nEssRev*6,1);metVarC];
+0357 prob.lb = [milpModel.lb;zeros(nYBlock + nPosIrrev + 5*nPosRev,1);ones(nPosRev,1)*-100;zeros(nNegIrrev+nNegRev*varsPerNegRev+nEssRev*2,1);ones(nEssRev,1)*forceOnLim;zeros(nEssRev*2,1);ones(nEssRev,1)*-100;metLb];
+0358 prob.lb(essIrrevRxns) = forceOnLimEss(essIrrevRxns);%force flux for the ess irrev rxns - this is the only way these are handled
+0359 prob.ub = [milpModel.ub;ones(nYBlock,1);inf(nPosIrrev+nPosRev*2,1);ones(nPosRev,1);inf(3*nPosRev+nNegIrrev+varsPerNegRev*nNegRev+3*nEssRev,1);ones(nEssRev,1);inf(2*nEssRev,1);metUb];
+0360 
+0361 prob.vartype = [repmat('C', 1, nRxns + nPosIrrev + nPosRev), ...
+0362                 repmat('B', 1, nNegIrrev + nNegRev), ...
+0363                 repmat('C', 1, nPosIrrev + 2*nPosRev), ... 
+0364                 repmat('B', 1, nPosRev), ...
+0365                 repmat('C', 1, 3*nPosRev + nNegIrrev + varsPerNegRev*nNegRev + 3*nEssRev), ...
+0366                 repmat('B', 1, nEssRev), ...
+0367                 repmat('C', 1, 2*nEssRev), ...
+0368                 metVartype];
+0369             
+0370 onoffVarInd = (1:(nPosIrrev + nPosRev + nNegIrrev + nNegRev)) + nRxns;
+0371 onoffPosIrrev = onoffVarInd(1:nPosIrrev);
+0372 onoffPosRev = onoffVarInd((1:nPosRev)+nPosIrrev);
+0373 onoffNegIrrev = onoffVarInd((1:nNegIrrev)+nPosIrrev+nPosRev);
+0374 onoffNegRev = onoffVarInd((1:nNegRev)+nPosIrrev+nPosRev+nNegIrrev);
+0375 
+0376 metVarInd = (1:nMetabolMets) + (length(prob.vartype) - nMetVars);
+0377 
+0378 if allowExcretion
+0379     prob.csense = [repmat('L', 1, length(milpModel.mets)), ...
+0380                   repmat('E', 1, length(prob.b) - length(milpModel.mets))];
+0381 else
+0382     prob.csense = '=';
+0383 end
+0384 
+0385 params.intTol = 10^-7; %This value is very important. If set too low
+0386                        %there is a risk that gurobi fails due to numerical
+0387                        %issues - this happened for Gurobi v. 10.0 with TestModelL.
+0388                        %On the other hand, it shouldn't be too large
+0389                        %either. With this value, fluxes of 10-7 can slip
+0390                        %through, which should be fine. Another option if
+0391                        %this becomes a problem is to set NumericFocus=2,
+0392                        %which makes the solver slower but fixes the issue
+0393                        %with TestModelL.
+0394 
+0395 prob.osense = 1; %minimize
+0396 
+0397 if ~isempty(startVals)
+0398      prob.start = startVals; %This doesn't work...
+0399 end
+0400 
+0401 res=optimizeProb(prob,params,verbose);
+0402 
+0403 
+0404 if ~checkSolution(res)
+0405     if strcmp(res.origStat, 'TIME_LIMIT')
+0406         EM='Time limit reached without finding a solution. Try increasing the TimeLimit parameter.';
+0407     else
+0408         EM='The problem is infeasible';
+0409     end
+0410     dispEM(EM);
+0411 end
+0412 
+0413 %get the on/off vals
+0414 onoff = ones(nRxnsWithOnOff,1);%standard is on, i.e. all reactions not included in the problem + ess is on
+0415 onoff(posIrrevRxns) = res.full(onoffPosIrrev);
+0416 onoff(posRevRxns) = res.full(onoffPosRev);
+0417 onoff(negIrrevRxns) = res.full(onoffNegIrrev);
+0418 onoff(negRevRxns) = res.full(onoffNegRev);
+0419 
+0420 onoff2 = zeros(nRxnsWithOnOff,1);%standard is off, i.e. all reactions not included in the problem + ess is off
+0421 onoff2(posIrrevRxns) = res.full(onoffPosIrrev);
+0422 onoff2(posRevRxns) = res.full(onoffPosRev);
+0423 onoff2(negIrrevRxns) = res.full(onoffNegIrrev);
+0424 onoff2(negRevRxns) = res.full(onoffNegRev);
+0425 
+0426 
+0427 %investigate a bit - this code could be used for fault finding. We have
+0428 %this code commented out, but it is definitely worth testing this if for example
+0429 %the solver is changed.
+0430 %problematic = onoff < 0.99 & onoff > 0.01 & (rxnScores ~= 0).';
+0431 %if sum(problematic) > 0
+0432 %    disp('There are reactions that are in between on and off in the MILP. This may be due to the MILP parameter settings, the tolerances may be too large.')
+0433 %    disp(['No problematic reactions: ', num2str(sum(problematic))])
+0434 %end
+0435 
+0436 %so, it is only positive that are problematic. Likely because the 0.1 is too large. Test to change to 0.01
+0437 %unique(onoff(onoff < 0.99 & onoff > 0.01))
+0438 
+0439 %Get all reactions used in the irreversible model
+0440 %The reaction score check is for metabolomics - we add those reactions as
+0441 %positive even though the score is 0. And, we don't want them included in the
+0442 %results.
+0443 deletedRxns=(onoff < 0.5).' & (rxnScores ~= 0).'; 
+0444 turnedOnRxns=(onoff2 >= 0.5).' & (rxnScores ~= 0).';
+0445 
+0446 fluxes = res.full(1:nRxns);
+0447 
+0448 %extract the met data
+0449 metProduction = logical(round(res.full(metVarInd)));
+0450 
+0451 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/INIT/getExprForRxnScore.html b/doc/INIT/getExprForRxnScore.html new file mode 100644 index 000000000..e97beb72a --- /dev/null +++ b/doc/INIT/getExprForRxnScore.html @@ -0,0 +1,85 @@ + + + + Description of getExprForRxnScore + + + + + + + + + +
Home > INIT > getExprForRxnScore.m
+ + + +

getExprForRxnScore +

+ +

PURPOSE ^

+
getExprForRxnScore
+ +

SYNOPSIS ^

+
function expr = getExprForRxnScore(scores, threshold)
+ +

DESCRIPTION ^

+
 getExprForRxnScore
+   Converts a reaction score to the gene expression (CPM or TPM) required 
+   to get that reaction score, if the GPR is only a single gene.
+   Useful function primarily in test cases, where you want to be able to
+   define the reaction scores of rxns, but need to send in gene expression.
+
+   scores        Vector of scores to convert
+   threshold     Gene threshold (optional, default 1)
+
+   expr          The resulting gene expression vector.
+
+ Usage: expr = getExprForRxnScore(scores, threshold)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function expr = getExprForRxnScore(scores, threshold)
+0002 % getExprForRxnScore
+0003 %   Converts a reaction score to the gene expression (CPM or TPM) required
+0004 %   to get that reaction score, if the GPR is only a single gene.
+0005 %   Useful function primarily in test cases, where you want to be able to
+0006 %   define the reaction scores of rxns, but need to send in gene expression.
+0007 %
+0008 %   scores        Vector of scores to convert
+0009 %   threshold     Gene threshold (optional, default 1)
+0010 %
+0011 %   expr          The resulting gene expression vector.
+0012 %
+0013 % Usage: expr = getExprForRxnScore(scores, threshold)
+0014 
+0015 if nargin < 2
+0016     threshold = 1;
+0017 end
+0018 
+0019 %This is how the score is calculated: 5*log(expression./threshold)
+0020 %expression = threshold*10.^(scores/5)
+0021 %This is a bit confusing - it seems that it is threshold*e.^(scores/5)
+0022 %This is probably what is being used in scoreComplexModel, this code
+0023 %negates that perfectly, see the T0009 test case.
+0024 
+0025 expr = threshold*exp(scores/5);
+0026 
+0027 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/INIT/getINITModel.html b/doc/INIT/getINITModel.html new file mode 100644 index 000000000..d09135107 --- /dev/null +++ b/doc/INIT/getINITModel.html @@ -0,0 +1,609 @@ + + + + Description of getINITModel + + + + + + + + + +
Home > INIT > getINITModel.m
+ + + +

getINITModel +

+ +

PURPOSE ^

+
getINITModel_legacy
+ +

SYNOPSIS ^

+
function [model, metProduction, essentialRxnsForTasks, addedRxnsForTasks, deletedDeadEndRxns, deletedRxnsInINIT, taskReport]=getINITModel(refModel, tissue, celltype, hpaData, arrayData, metabolomicsData, taskFile, useScoresForTasks, printReport, taskStructure)
+ +

DESCRIPTION ^

+
 getINITModel_legacy
+   Generates a model using the INIT algorithm, based on proteomics and/or
+   transcriptomics and/or metabolomics and/or metabolic tasks. This is the original 
+   implementation of tINIT, which is replaced by ftINIT.
+
+ Input:
+   refModel            a model structure. The model should be in the
+                       closed form (no exchange reactions open). Import
+                       using import(filename,false). If the model is not
+                       loaded using importModel, it might be that there
+                       is no "unconstrained" field. In that case,
+                       manually add the field like:
+                       model.unconstrained=false(numel(model.mets),1);
+   tissue              tissue to score for. Should exist in either
+                       hpaData.tissues or arrayData.tissues
+   celltype            cell type to score for. Should exist in either
+                       hpaData.celltypes or arrayData.celltypes for this
+                       tissue (optional, default is to use the best values
+                       among all the cell types for the tissue. Use [] if
+                       you want to supply more arguments)
+   hpaData             HPA data structure from parseHPA (optional if arrayData is
+                       supplied, default [])
+   arrayData           gene expression data structure (optional if hpaData is
+                       supplied, default [])
+       genes           cell array with the unique gene names
+       tissues         cell array with the tissue names. The list may not be
+                       unique, as there can be multiple cell types per tissue
+       celltypes       cell array with the cell type names for each tissue
+       levels          GENESxTISSUES array with the expression level for
+                       each gene in each tissue/celltype. NaN should be
+                       used when no measurement was performed
+       threshold       a single value or a vector of gene expression 
+                       thresholds, above which genes are considered to be
+                       "expressed". (optional, by default, the mean expression
+                       levels of each gene across all tissues in arrayData
+                       will be used as the threshold values)
+       singleCells     binary value selecting whether to use the
+                       single-cell algorithm to identify expressed genes.
+                       If used, specify cell subpopulations in CELLTYPES
+                       (optional, default [])
+       plotResults     true if single cell probability distributions
+                       should be plotted (optional, default = False)
+   metabolomicsData    cell array with metabolite names that the model
+                       should produce (optional, default [])
+   taskFile            a task list in Excel format. See parseTaskList for
+                       details (optional, default [])
+   useScoresForTasks   true if the calculated reaction scored should be used as
+                       weights in the fitting to tasks (optional, default true)
+   printReport         true if a report should be printed to the screen
+                       (optional, default true)
+   taskStructure       task structure as from parseTaskList. Can be used
+                       as an alternative way to define tasks when Excel
+                       sheets are not suitable. Overrides taskFile (optional,
+                       default [])
+
+ Output:
+   model                   the resulting model structure
+   metProduction           array that indicates which of the
+                           metabolites in metabolomicsData that could be
+                           produced. Note that this is before the
+                           gap-filling process to enable defined tasks. To
+                           see which metabolites that can be produced in
+                           the final model, use canProduce.
+                           -2: metabolite name not found in model
+                           -1: metabolite found, but it could not be produced
+                           1: metabolite could be produced
+   essentialRxnsForTasks   cell array of the reactions which were
+                           essential to perform the tasks
+   addedRxnsForTasks       cell array of the reactions which were added in
+                           order to perform the tasks
+   deletedDeadEndRxns      cell array of reactions deleted because they
+                           could not carry flux (INIT requires a
+                           functional input model)
+   deletedRxnsInINIT       cell array of the reactions which were deleted by
+                           the INIT algorithm
+   taskReport              structure with the results for each task
+       id                  cell array with the id of the task
+       description         cell array with the description of the task
+       ok                  boolean array with true if the task was successful
+       essential           cell array with cell arrays of essential
+                           reactions for the task
+       gapfill             cell array of cell arrays of reactions included
+                           in the gap-filling for the task
+
+   This is the main function for automatic reconstruction of models based
+   on the (t)INIT algorithm (PLoS Comput Biol. 2012;8(5):e1002518, 
+   Mol Syst Biol. 2014;10:721). Not all settings are possible using this
+   function, and you may want to call the functions scoreModel, runINIT
+   and fitTasks individually instead.
+
+   NOTE: Exchange metabolites should normally not be removed from the model
+   when using this approach, since checkTasks/fitTasks rely on putting specific
+   constraints for each task. The INIT algorithm will remove exchange metabolites
+   if any are present. Use importModel(file,false) to import a model with
+   exchange metabolites remaining.
+
+ Usage: [model, metProduction, essentialRxnsForTasks, addedRxnsForTasks,...
+               deletedDeadEndRxns, deletedRxnsInINIT, taskReport]=...
+               getINITModel(refModel, tissue, celltype, hpaData, arrayData,...
+               metabolomicsData, taskFile, useScoresForTasks, printReport,...
+               taskStructure, params, paramsFT)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 function [model, metProduction, essentialRxnsForTasks, addedRxnsForTasks, deletedDeadEndRxns, deletedRxnsInINIT, taskReport]=getINITModel(refModel, tissue, celltype, hpaData, arrayData, metabolomicsData, taskFile, useScoresForTasks, printReport, taskStructure)
+0002 % getINITModel_legacy
+0003 %   Generates a model using the INIT algorithm, based on proteomics and/or
+0004 %   transcriptomics and/or metabolomics and/or metabolic tasks. This is the original
+0005 %   implementation of tINIT, which is replaced by ftINIT.
+0006 %
+0007 % Input:
+0008 %   refModel            a model structure. The model should be in the
+0009 %                       closed form (no exchange reactions open). Import
+0010 %                       using import(filename,false). If the model is not
+0011 %                       loaded using importModel, it might be that there
+0012 %                       is no "unconstrained" field. In that case,
+0013 %                       manually add the field like:
+0014 %                       model.unconstrained=false(numel(model.mets),1);
+0015 %   tissue              tissue to score for. Should exist in either
+0016 %                       hpaData.tissues or arrayData.tissues
+0017 %   celltype            cell type to score for. Should exist in either
+0018 %                       hpaData.celltypes or arrayData.celltypes for this
+0019 %                       tissue (optional, default is to use the best values
+0020 %                       among all the cell types for the tissue. Use [] if
+0021 %                       you want to supply more arguments)
+0022 %   hpaData             HPA data structure from parseHPA (optional if arrayData is
+0023 %                       supplied, default [])
+0024 %   arrayData           gene expression data structure (optional if hpaData is
+0025 %                       supplied, default [])
+0026 %       genes           cell array with the unique gene names
+0027 %       tissues         cell array with the tissue names. The list may not be
+0028 %                       unique, as there can be multiple cell types per tissue
+0029 %       celltypes       cell array with the cell type names for each tissue
+0030 %       levels          GENESxTISSUES array with the expression level for
+0031 %                       each gene in each tissue/celltype. NaN should be
+0032 %                       used when no measurement was performed
+0033 %       threshold       a single value or a vector of gene expression
+0034 %                       thresholds, above which genes are considered to be
+0035 %                       "expressed". (optional, by default, the mean expression
+0036 %                       levels of each gene across all tissues in arrayData
+0037 %                       will be used as the threshold values)
+0038 %       singleCells     binary value selecting whether to use the
+0039 %                       single-cell algorithm to identify expressed genes.
+0040 %                       If used, specify cell subpopulations in CELLTYPES
+0041 %                       (optional, default [])
+0042 %       plotResults     true if single cell probability distributions
+0043 %                       should be plotted (optional, default = False)
+0044 %   metabolomicsData    cell array with metabolite names that the model
+0045 %                       should produce (optional, default [])
+0046 %   taskFile            a task list in Excel format. See parseTaskList for
+0047 %                       details (optional, default [])
+0048 %   useScoresForTasks   true if the calculated reaction scored should be used as
+0049 %                       weights in the fitting to tasks (optional, default true)
+0050 %   printReport         true if a report should be printed to the screen
+0051 %                       (optional, default true)
+0052 %   taskStructure       task structure as from parseTaskList. Can be used
+0053 %                       as an alternative way to define tasks when Excel
+0054 %                       sheets are not suitable. Overrides taskFile (optional,
+0055 %                       default [])
+0056 %
+0057 % Output:
+0058 %   model                   the resulting model structure
+0059 %   metProduction           array that indicates which of the
+0060 %                           metabolites in metabolomicsData that could be
+0061 %                           produced. Note that this is before the
+0062 %                           gap-filling process to enable defined tasks. To
+0063 %                           see which metabolites that can be produced in
+0064 %                           the final model, use canProduce.
+0065 %                           -2: metabolite name not found in model
+0066 %                           -1: metabolite found, but it could not be produced
+0067 %                           1: metabolite could be produced
+0068 %   essentialRxnsForTasks   cell array of the reactions which were
+0069 %                           essential to perform the tasks
+0070 %   addedRxnsForTasks       cell array of the reactions which were added in
+0071 %                           order to perform the tasks
+0072 %   deletedDeadEndRxns      cell array of reactions deleted because they
+0073 %                           could not carry flux (INIT requires a
+0074 %                           functional input model)
+0075 %   deletedRxnsInINIT       cell array of the reactions which were deleted by
+0076 %                           the INIT algorithm
+0077 %   taskReport              structure with the results for each task
+0078 %       id                  cell array with the id of the task
+0079 %       description         cell array with the description of the task
+0080 %       ok                  boolean array with true if the task was successful
+0081 %       essential           cell array with cell arrays of essential
+0082 %                           reactions for the task
+0083 %       gapfill             cell array of cell arrays of reactions included
+0084 %                           in the gap-filling for the task
+0085 %
+0086 %   This is the main function for automatic reconstruction of models based
+0087 %   on the (t)INIT algorithm (PLoS Comput Biol. 2012;8(5):e1002518,
+0088 %   Mol Syst Biol. 2014;10:721). Not all settings are possible using this
+0089 %   function, and you may want to call the functions scoreModel, runINIT
+0090 %   and fitTasks individually instead.
+0091 %
+0092 %   NOTE: Exchange metabolites should normally not be removed from the model
+0093 %   when using this approach, since checkTasks/fitTasks rely on putting specific
+0094 %   constraints for each task. The INIT algorithm will remove exchange metabolites
+0095 %   if any are present. Use importModel(file,false) to import a model with
+0096 %   exchange metabolites remaining.
+0097 %
+0098 % Usage: [model, metProduction, essentialRxnsForTasks, addedRxnsForTasks,...
+0099 %               deletedDeadEndRxns, deletedRxnsInINIT, taskReport]=...
+0100 %               getINITModel(refModel, tissue, celltype, hpaData, arrayData,...
+0101 %               metabolomicsData, taskFile, useScoresForTasks, printReport,...
+0102 %               taskStructure, params, paramsFT)
+0103 
+0104 if nargin<3
+0105     celltype=[];
+0106 else
+0107     celltype=char(celltype);
+0108 end
+0109 if nargin<4
+0110     hpaData=[];
+0111 end
+0112 if nargin<5
+0113     arrayData=[];
+0114 end
+0115 if nargin<6
+0116     metabolomicsData=[];
+0117 end
+0118 if nargin<7
+0119     taskFile=[];
+0120 else
+0121     taskFile=char(taskFile);
+0122 end
+0123 if nargin<8 || isempty(useScoresForTasks)
+0124     useScoresForTasks=true;
+0125 end
+0126 if nargin<9 || isempty(printReport)
+0127     printReport=true;
+0128 end
+0129 if nargin<10
+0130     taskStructure=[];
+0131 end
+0132 if nargin<11
+0133     params=[];
+0134 end
+0135 if nargin<12
+0136     paramsFT=[];
+0137 end
+0138 
+0139 %Check that the model is in the closed form
+0140 if ~isfield(refModel,'unconstrained')
+0141     EM='Exchange metabolites should normally not be removed from the model when using getINITModel. Use importModel(file,false) to import a model with exchange metabolites remaining (see the documentation for details)';
+0142     dispEM(EM);
+0143 end
+0144 
+0145 %Create the task structure if not supplied
+0146 if any(taskFile) && isempty(taskStructure)
+0147     taskStructure=parseTaskList(taskFile);
+0148 end
+0149 
+0150 
+0151 % sc-tINIT to identify confidence levels of gene expression
+0152 if ~isempty(arrayData) && isfield(arrayData,'singleCells')
+0153     if arrayData.singleCells == 1
+0154         % Check to ensure cell type is defined
+0155         if ~isfield(arrayData,'celltypes')
+0156             dispEM('arrayData must contain cell type information if sc-tINIT is to be used','false');   
+0157         end
+0158         if ~ismember(upper(celltype),upper(arrayData.celltypes))
+0159             dispEM('The cell type name does not match');   
+0160         end
+0161         
+0162         % Analyze only cell type of interest
+0163         J= strcmpi(arrayData.celltypes,celltype);
+0164         
+0165         % Analyze only genes included in the reference model
+0166         I=ismember(arrayData.genes,refModel.genes);
+0167         
+0168         % Convert expression data to population fractions
+0169         binary_levels = arrayData.levels(I,J)~=0; % Classify each gene as detected (1) or not (0) in each cell
+0170         cell_count_levels = sum(binary_levels,2); % Number of cells expressing each transcript
+0171         cell_frac_levels = cell_count_levels/size(binary_levels,2); % Number of cells expressing each transcript
+0172 
+0173         % Bin cell_frac_counts manually
+0174         x = 0:.01:1;
+0175         for(i = 1:length(x))
+0176             cell_frac_count(i) = sum(round(cell_frac_levels,2)==x(i));
+0177         end
+0178         
+0179         % Fit four beta distributions
+0180         cell_frac_count(cell_frac_count==0) = NaN; % Remove zeros from optimization
+0181         cell_frac_count(1) = NaN; % Remove non-expressed genes from optimization
+0182         x_lim = 1; % Somewhat arbitrary parameter to fit left tail of distr.
+0183         myfun = @(par) nansum((cell_frac_count(1:find(x>=x_lim,1)) - ...
+0184             abs(par(1))*betapdf(x(1:find(x>=x_lim,1)),abs(par(2)),abs(par(3))) - ...
+0185             abs(par(4))*betapdf(x(1:find(x>=x_lim,1)),abs(par(5)),abs(par(6))) - ...
+0186             abs(par(7))*betapdf(x(1:find(x>=x_lim,1)),abs(par(8)),abs(par(9))) - ...
+0187             abs(par(10))*betapdf(x(1:find(x>=x_lim,1)),abs(par(11)),abs(par(12)))).^2);
+0188         
+0189         par0 = [4,2,100,7,2,30,7,5,20,5,15,20];
+0190         opts = optimset('Display','off');
+0191         [par,f_val] = fminsearch(myfun,par0,opts);
+0192         par = abs(par);
+0193         
+0194         % Plot results
+0195         if (isfield(arrayData,'plotResults'))
+0196             if arrayData.plotResults == true
+0197                 figure(); hold on; plot(x,cell_frac_count,'ko','MarkerSize',5);
+0198                 plot(x,abs(par(1))*betapdf(x,abs(par(2)),abs(par(3))),'b-','LineWidth',1)
+0199                 plot(x,abs(par(4))*betapdf(x,abs(par(5)),abs(par(6))),'b-','LineWidth',1)
+0200                 plot(x,abs(par(7))*betapdf(x,abs(par(8)),abs(par(9))),'b-','LineWidth',1)
+0201                 plot(x,abs(par(10))*betapdf(x,abs(par(11)),abs(par(12))),'b-','LineWidth',1)
+0202                 plot(x,abs(par(1))*betapdf(x,abs(par(2)),abs(par(3))) + ...
+0203                     abs(par(4))*betapdf(x,abs(par(5)),abs(par(6))) + ...
+0204                     abs(par(7))*betapdf(x,abs(par(8)),abs(par(9))) + ...
+0205                     abs(par(10))*betapdf(x,abs(par(11)),abs(par(12))),'-','Color',[.5 .5 .5],'LineWidth',2)
+0206                 xlabel('Expression Probability');ylabel('# of genes');set(gca,'FontSize',14,'LineWidth',1.25);
+0207                 title('Expression prediction','FontSize',18,'FontWeight','bold')
+0208             end
+0209         end
+0210         
+0211         % Score genes based on population expression (p = .05)
+0212         exprs_cutoff_1 = find(cdf('beta',x,par(2),par(3)) >.95,1)-1; % Find index of no confidence genes
+0213         exprs_cutoff_2 = find(cdf('beta',x,par(5),par(6)) >.95,1)-1; % Find index of low confidence genes
+0214         exprs_cutoff_3 = find(cdf('beta',x,par(8),par(9)) >.95,1)-1; % Find index of low confidence genes
+0215         exprs_cutoffs = sort([exprs_cutoff_1,exprs_cutoff_2,exprs_cutoff_3]);
+0216         gene_scores = cell_frac_levels*0;
+0217         gene_scores(cell_frac_levels <= x(exprs_cutoffs(1))) = 4; % Not detected
+0218         gene_scores(logical((cell_frac_levels >= x(exprs_cutoffs(1))).*(cell_frac_levels < x(exprs_cutoffs(2))))) = 3; % Low detection
+0219         gene_scores(logical((cell_frac_levels >= x(exprs_cutoffs(2))).*(cell_frac_levels < x(exprs_cutoffs(3))))) = 2; % Medium detection
+0220         gene_scores(cell_frac_levels > x(exprs_cutoffs(3))) = 1; % High detection
+0221 
+0222         % Replace hpaData with singleCellData
+0223         if printReport==true
+0224             dispEM('Single cell data is not currently compatible with HPA data. \n         Replacing hpaData with single cell-based scoring.',false);
+0225         end
+0226         hpaData.genes = arrayData.genes;
+0227         hpaData.tissues = arrayData.tissues;
+0228         hpaData.celltypes = arrayData.celltypes;
+0229         hpaData.levels = [{'High'},{'Medium'},{'Low'},{'None'}];
+0230         hpaData.gene2Level = zeros(length(arrayData.genes),length(arrayData.celltypes));
+0231         for i = 1:length(find(J))
+0232             find_var = find(J,i);
+0233             hpaData.gene2Level(I,find_var(end)) = gene_scores;
+0234         end
+0235         
+0236         % Remove arrayData from the analysis (Might be a bad idea)
+0237         clear arrayData
+0238         arrayData=[];
+0239     end
+0240 end
+0241 
+0242 
+0243 if printReport==true
+0244     if any(celltype)
+0245         fprintf(['***Generating model for: ' tissue ' - ' celltype '\n']);
+0246     else
+0247         fprintf(['***Generating model for: ' tissue '\n']);
+0248     end
+0249     if ~isempty(hpaData)
+0250         fprintf('-Using HPA data\n');
+0251     end
+0252     if ~isempty(arrayData)
+0253         fprintf('-Using array data\n');
+0254     end
+0255     if ~isempty(metabolomicsData)
+0256         fprintf('-Using metabolomics data\n');
+0257     end
+0258     if ~isempty(taskFile) || ~isempty(taskStructure)
+0259         fprintf('-Using metabolic tasks\n');
+0260     end
+0261     fprintf('\n');
+0262     
+0263     printScores(refModel,'Reference model statistics',hpaData,arrayData,tissue,celltype);
+0264 end
+0265 
+0266 %Remove dead-end reactions to speed up the optimization and to
+0267 %differentiate between reactions removed by INIT and those that are
+0268 %dead-end
+0269 [~, deletedDeadEndRxns]=simplifyModel(refModel,true,false,true,true,true);
+0270 cModel=removeReactions(refModel,deletedDeadEndRxns,false,true);
+0271 
+0272 %Store the connected model like this to keep track of stuff
+0273 if printReport==true
+0274     printScores(cModel,'Pruned model statistics',hpaData,arrayData,tissue,celltype);
+0275 end
+0276 
+0277 %If tasks have been defined, then go through them and get essential
+0278 %reactions
+0279 if ~isempty(taskStructure)
+0280     [taskReport, essentialRxnMat]=checkTasks(cModel,[],printReport,true,true,taskStructure);
+0281     
+0282     essentialRxnsForTasks=cModel.rxns(any(essentialRxnMat,2));
+0283     
+0284     %Remove tasks that cannot be performed
+0285     taskStructure(taskReport.ok==false)=[];
+0286     if printReport==true
+0287         printScores(removeReactions(cModel,setdiff(cModel.rxns,essentialRxnsForTasks),true,true),'Reactions essential for tasks',hpaData,arrayData,tissue,celltype);
+0288     end
+0289 else
+0290     essentialRxnsForTasks={};
+0291 end
+0292 
+0293 %Score the connected model
+0294 [rxnScores, geneScores]=scoreModel(cModel,hpaData,arrayData,tissue,celltype);
+0295 
+0296 %Run the INIT algorithm. The exchange reactions that are used in the final
+0297 %reactions will be open, which doesn't fit with the last step. Therefore
+0298 %delete reactions from the original model instead of taking the output. The
+0299 %default implementation does not constrain reversible reactions to only
+0300 %carry flux in one direction. Runs without the constraints on reversibility
+0301 %and with all output allowed. This is to reduce the complexity of the
+0302 %problem.
+0303 [~, deletedRxnsInINIT, metProduction]=runINIT(simplifyModel(cModel),rxnScores,metabolomicsData,essentialRxnsForTasks,0,true,false,params);
+0304 initModel=removeReactions(cModel,deletedRxnsInINIT,true,true);
+0305 if printReport==true
+0306     printScores(initModel,'INIT model statistics',hpaData,arrayData,tissue,celltype);
+0307     printScores(removeReactions(cModel,setdiff(cModel.rxns,deletedRxnsInINIT),true,true),'Reactions deleted by INIT',hpaData,arrayData,tissue,celltype);
+0308 end
+0309 
+0310 %The full model has exchange reactions in it. fitTasks calls on fillGaps,
+0311 %which automatically removes exchange metabolites (because it assumes that
+0312 %the reactions are constrained when appropriate). In this case the
+0313 %uptakes/outputs are retrieved from the task sheet instead. To prevent
+0314 %exchange reactions being used to fill gaps, they are delete from the
+0315 %reference model here.
+0316 initModel.id='INITModel';
+0317 
+0318 %If gaps in the model should be filled using a task list
+0319 if ~isempty(taskStructure)
+0320     %Remove exchange reactions and reactions already included in the INIT
+0321     %model
+0322     refModelNoExc=removeReactions(refModel,union(initModel.rxns,getExchangeRxns(refModel)),true,true);
+0323     
+0324     %At this stage the model is fully connected and most of the genes with
+0325     %good scores should have been included. The final gap-filling should
+0326     %take the scores of the genes into account, so that "rather bad"
+0327     %reactions are preferred to "very bad" reactions. However, reactions
+0328     %with positive scores will be included even if they are not connected
+0329     %in the current formulation. Therefore, such reactions will have to be
+0330     %assigned a small negative score instead.
+0331     if useScoresForTasks==true
+0332         refRxnScores=scoreModel(refModelNoExc,hpaData,arrayData,tissue,celltype);
+0333         [outModel, addedRxnMat]=fitTasks(initModel,refModelNoExc,[],true,min(refRxnScores,-0.1),taskStructure,paramsFT);
+0334     else
+0335         [outModel, addedRxnMat]=fitTasks(initModel,refModelNoExc,[],true,[],taskStructure,paramsFT);
+0336     end
+0337     if printReport==true
+0338         printScores(outModel,'Functional model statistics',hpaData,arrayData,tissue,celltype);
+0339         printScores(removeReactions(outModel,intersect(outModel.rxns,initModel.rxns),true,true),'Reactions added to perform the tasks',hpaData,arrayData,tissue,celltype);
+0340     end
+0341     
+0342     addedRxnsForTasks=refModelNoExc.rxns(any(addedRxnMat,2));
+0343 else
+0344     outModel=initModel;
+0345     addedRxnMat=[];
+0346     addedRxnsForTasks={};
+0347 end
+0348 
+0349 %The model can now perform all the tasks defined in the task list. The
+0350 %algorithm cannot deal with gene-complexes at the moment. It is therefore
+0351 %ok to remove bad genes from a reaction (as long as at least one gene is
+0352 %kept)
+0353 model=outModel;
+0354 
+0355 [~, I]=ismember(model.genes,cModel.genes); %All should be found
+0356 %This is a little weird way to make sure that only one bad gene is included
+0357 %if there are no good ones (since all -Inf==max(-Inf))
+0358 geneScores(isinf(geneScores))=-1000+rand(sum(isinf(geneScores)),1);
+0359 
+0360 model.grRules(:)={''};
+0361 for i=1:numel(model.rxns)
+0362     ids=find(model.rxnGeneMat(i,:));
+0363     if numel(ids)>1
+0364         scores=geneScores(I(ids));
+0365         %Only keep the positive ones if possible
+0366         model.rxnGeneMat(i,ids(~(scores>0 | scores==max(scores))))=0;
+0367     end
+0368     %Rewrite the grRules to be only OR
+0369     if isfield(model,'grRules')
+0370         J=find(model.rxnGeneMat(i,:));
+0371         for j=1:numel(J)
+0372             model.grRules{i}=[model.grRules{i} '(' model.genes{J(j)} ')'];
+0373             if j<numel(J)
+0374                 model.grRules{i}=[model.grRules{i} ' or '];
+0375             end
+0376         end
+0377     end
+0378 end
+0379 
+0380 %Find all genes that are not used and delete them
+0381 I=sum(model.rxnGeneMat)==0;
+0382 model.genes(I)=[];
+0383 model.rxnGeneMat(:,I)=[];
+0384 if isfield(model,'geneShortNames')
+0385     model.geneShortNames(I)=[];
+0386 end
+0387 if isfield(model,'proteins')
+0388     model.proteins(I)=[];
+0389 end
+0390 if isfield(model,'geneMiriams')
+0391     model.geneMiriams(I)=[];
+0392 end
+0393 if isfield(model,'geneFrom')
+0394     model.geneFrom(I)=[];
+0395 end
+0396 if isfield(model,'geneComps')
+0397     model.geneComps(I)=[];
+0398 end
+0399 
+0400 %At this stage the model will contain some exchange reactions but probably
+0401 %not all (and maybe zero). This can be inconvenient, so all exchange
+0402 %reactions from the reference model are added, except for those which
+0403 %involve metabolites that are not in the model.
+0404 
+0405 %First delete and included exchange reactions in order to prevent the order
+0406 %from changing
+0407 model=removeReactions(model,getExchangeRxns(model));
+0408 
+0409 %Create a model with only the exchange reactions in refModel
+0410 excModel=removeReactions(refModel,setdiff(refModel.rxns,getExchangeRxns(refModel)),true,true);
+0411 
+0412 %Find the metabolites there which are not exchange metabolites and which do
+0413 %not exist in the output model
+0414 I=~ismember(excModel.mets,model.mets) & excModel.unconstrained==0;
+0415 
+0416 %Then find those reactions and delete them
+0417 [~, J]=find(excModel.S(I,:));
+0418 excModel=removeReactions(excModel,J,true,true);
+0419 
+0420 %Merge with the output model
+0421 model=mergeModels({model;excModel},'metNames');
+0422 model.id='INITModel';
+0423 model.name=['Automatically generated model for ' tissue];
+0424 if any(celltype)
+0425     model.name=[model.name ' - ' celltype];
+0426 end
+0427 
+0428 if printReport==true
+0429     printScores(model,'Final model statistics',hpaData,arrayData,tissue,celltype);
+0430 end
+0431 
+0432 %Add information about essential reactions and reactions included for
+0433 %gap-filling and return a taskReport
+0434 if ~isempty(taskStructure)
+0435     I=find(taskReport.ok); %Ignore failed tasks
+0436     for i=1:numel(I)
+0437         taskReport.essential{I(i),1}=cModel.rxns(essentialRxnMat(:,I(i)));
+0438         taskReport.gapfill{I(i),1}=refModelNoExc.rxns(addedRxnMat(:,i));
+0439     end
+0440 else
+0441     taskReport=[];
+0442 end
+0443 
+0444 %Fix grRules and reconstruct rxnGeneMat
+0445 [grRules,rxnGeneMat] = standardizeGrRules(model,true);
+0446 model.grRules = grRules;
+0447 model.rxnGeneMat = rxnGeneMat;
+0448 end
+0449 
+0450 %This is for printing a summary of a model
+0451 function [rxnS, geneS]=printScores(model,name,hpaData,arrayData,tissue,celltype)
+0452 [a, b]=scoreModel(model,hpaData,arrayData,tissue,celltype);
+0453 rxnS=mean(a);
+0454 geneS=mean(b(~isinf(b)));
+0455 fprintf([name ':\n']);
+0456 fprintf(['\t' num2str(numel(model.rxns)) ' reactions, ' num2str(numel(model.genes)) ' genes\n']);
+0457 fprintf(['\tMean reaction score: ' num2str(rxnS) '\n']);
+0458 fprintf(['\tMean gene score: ' num2str(geneS) '\n']);
+0459 fprintf(['\tReactions with positive scores: ' num2str(100*sum(a>0)/numel(a)) '%%\n\n']);
+0460 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/INIT/getINITSteps.html b/doc/INIT/getINITSteps.html new file mode 100644 index 000000000..65be54794 --- /dev/null +++ b/doc/INIT/getINITSteps.html @@ -0,0 +1,210 @@ + + + + Description of getINITSteps + + + + + + + + + +
Home > INIT > getINITSteps.m
+ + + +

getINITSteps +

+ +

PURPOSE ^

+
getINITSteps
+ +

SYNOPSIS ^

+
function steps = getINITSteps(metsToIgnore, series)
+ +

DESCRIPTION ^

+
 getINITSteps
+   Converts a reaction score to the gene expression (CPM or TPM) required 
+   to get that reaction score, if the GPR is only a single gene.
+   Useful function primarily in test cases, where you want to be able to
+   define the reaction scores of rxns, but need to send in gene expression.
+   Note that all combinations of steps will not work. In general, avoid 'exclude'
+   if you want to define new ways to run the algorithm.
+
+   metsToIgnore  Structure describing mets that can be removed from the model
+                 before running ftINIT, such as water etc.
+                 (optional, default [])
+       simpleMets
+           mets  Names of metabolites to remove
+           compsToKeep Compartments for which metabolites should be kept.
+   series        Describes the way to run ftINIT: 
+                 '1+1'          Standard behavior. Step 1 and 2 described in
+                                the paper are merged into 1.
+                 '2+1'          The 3-step procedure described in the paper.
+                                Faster and slightly less accurate than '1+1 steps'
+                 '1+0'          Same as '1+1 steps', but skips step 3 in described 
+                                in the paper. This will result in a model including 
+                                a lot of reactions without GPRs. It is particularly 
+                                useful for structural comparison, since the reactions 
+                                removed in step 3 may be a bit random and doesn't 
+                                really add any extra information. Faster than
+                                '1+1 steps'
+                 '2+0'          Same as '2+1 steps', but skips step 3 in described 
+                                in the paper. Faster and slightly less accurate 
+                                than '1+0 steps', but will yield similar results.
+                 'full'         1-step run - similar to the old tINIT version but 
+                                without simplifications. Accurate, but very slow.
+                                This is mainly used for testing purposes.
+                 (optional, default '1+1')
+
+   steps         Cell array of steps, used as input to ftINIT
+
+ Usage: steps = getINITSteps(metsToIgnore, series)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function steps = getINITSteps(metsToIgnore, series)
+0002 % getINITSteps
+0003 %   Converts a reaction score to the gene expression (CPM or TPM) required
+0004 %   to get that reaction score, if the GPR is only a single gene.
+0005 %   Useful function primarily in test cases, where you want to be able to
+0006 %   define the reaction scores of rxns, but need to send in gene expression.
+0007 %   Note that all combinations of steps will not work. In general, avoid 'exclude'
+0008 %   if you want to define new ways to run the algorithm.
+0009 %
+0010 %   metsToIgnore  Structure describing mets that can be removed from the model
+0011 %                 before running ftINIT, such as water etc.
+0012 %                 (optional, default [])
+0013 %       simpleMets
+0014 %           mets  Names of metabolites to remove
+0015 %           compsToKeep Compartments for which metabolites should be kept.
+0016 %   series        Describes the way to run ftINIT:
+0017 %                 '1+1'          Standard behavior. Step 1 and 2 described in
+0018 %                                the paper are merged into 1.
+0019 %                 '2+1'          The 3-step procedure described in the paper.
+0020 %                                Faster and slightly less accurate than '1+1 steps'
+0021 %                 '1+0'          Same as '1+1 steps', but skips step 3 in described
+0022 %                                in the paper. This will result in a model including
+0023 %                                a lot of reactions without GPRs. It is particularly
+0024 %                                useful for structural comparison, since the reactions
+0025 %                                removed in step 3 may be a bit random and doesn't
+0026 %                                really add any extra information. Faster than
+0027 %                                '1+1 steps'
+0028 %                 '2+0'          Same as '2+1 steps', but skips step 3 in described
+0029 %                                in the paper. Faster and slightly less accurate
+0030 %                                than '1+0 steps', but will yield similar results.
+0031 %                 'full'         1-step run - similar to the old tINIT version but
+0032 %                                without simplifications. Accurate, but very slow.
+0033 %                                This is mainly used for testing purposes.
+0034 %                 (optional, default '1+1')
+0035 %
+0036 %   steps         Cell array of steps, used as input to ftINIT
+0037 %
+0038 % Usage: steps = getINITSteps(metsToIgnore, series)
+0039 if nargin < 1
+0040     metsToIgnore = [];
+0041 end
+0042 
+0043 if nargin < 2
+0044     series = '1+1';
+0045 end
+0046 
+0047 if strcmp(series,'1+1') %step 1 and 2 are joined
+0048     params1 = struct();
+0049     params1.MIPGap = 0.0004;
+0050     params1.TimeLimit = 120;
+0051     params2 = struct();
+0052     params2.MIPGap = 0.0030;
+0053     params2.TimeLimit = 5000;
+0054     params = {params1;params2};
+0055     params3 = struct();
+0056     params3.MIPGap = 0.0004;
+0057     params3.TimeLimit = 5;
+0058     paramsStep3 = {params3;params1;params2};
+0059     %The paramsStep3 involves a quick first run. The objective value is often
+0060     %small in the third step (~800), and 0.0004 of that is a very small number
+0061     %With this first step, the rough value of the objective function will be
+0062     %estimated, which will generate an absolute MIPGap limit that is much larger
+0063     %for the second iteration.
+0064     
+0065     steps = { ...
+0066         INITStepDesc(false, false, 'ignore', [1,1,1,1,1,1,1,0], metsToIgnore, params, {10;20}); ...
+0067         INITStepDesc(false, false, 'essential', [1,0,0,0,1,0,0,0], metsToIgnore, paramsStep3, {10;10;20}); ...
+0068         };
+0069 elseif strcmp(series,'2+1') %the 3 step process described in the ftINIT paper
+0070     params1 = struct();
+0071     params1.MIPGap = 0.0004;
+0072     params1.TimeLimit = 120;
+0073     params2 = struct();
+0074     params2.MIPGap = 0.0030;
+0075     params2.TimeLimit = 5000;
+0076     params = {params1;params2};
+0077     params3 = struct();
+0078     params3.MIPGap = 0.0004;
+0079     params3.TimeLimit = 5;
+0080     paramsStep3 = {params3;params1;params2};
+0081     %The paramsStep3 involves a quick first run. The objective value is often
+0082     %small in the third step (~800), and 0.0004 of that is a very small number
+0083     %With this first step, the rough value of the objective function will be
+0084     %estimated, which will generate an absolute MIPGap limit that is much larger
+0085     %for the second iteration.
+0086     
+0087     steps = { ...
+0088         INITStepDesc(true, true, 'ignore', [1,1,1,1,1,1,1,0], metsToIgnore, params, {10;20}); ...
+0089         INITStepDesc(false, false, 'essential', [1,1,1,1,1,1,1,0], metsToIgnore, params, {10;20}); ...
+0090         INITStepDesc(false, false, 'essential', [1,0,0,0,1,0,0,0], metsToIgnore, paramsStep3, {10;10;20}); ...
+0091         };
+0092 elseif strcmp(series,'1+0') %Joins step 1 and 2, skips step 3
+0093     params1 = struct();
+0094     params1.MIPGap = 0.0004;
+0095     params1.TimeLimit = 120;
+0096     params2 = struct();
+0097     params2.MIPGap = 0.0030;
+0098     params2.TimeLimit = 5000;
+0099     params = {params1;params2};
+0100     steps = { ...
+0101         INITStepDesc(false, false, 'ignore', [1,1,1,1,1,1,1,0], metsToIgnore, params, {10;20}); ...
+0102         };
+0103 elseif strcmp(series,'2+0') %Skips step 3
+0104     params1 = struct();
+0105     params1.MIPGap = 0.0004;
+0106     params1.TimeLimit = 120;
+0107     params2 = struct();
+0108     params2.MIPGap = 0.0030;
+0109     params2.TimeLimit = 5000;
+0110     params = {params1;params2};
+0111     steps = { ...
+0112         INITStepDesc(true, true, 'ignore', [1,1,1,1,1,1,1,0], metsToIgnore, params, {10;20}); ...
+0113         INITStepDesc(false, false, 'essential', [1,1,1,1,1,1,1,0], metsToIgnore, params, {10;20}); ...
+0114         };
+0115 elseif strcmp(series,'full') %Just one run, slow on large models, but this is the 'perfect' setup
+0116     params1 = struct();
+0117     params1.MIPGap = 0.0004;
+0118     params1.TimeLimit = 10000;
+0119     params = {params1};
+0120     steps = { ...
+0121         INITStepDesc(false, false, 'ignore', [0,0,0,0,0,0,0,0], [], params) ...
+0122         };
+0123 else
+0124     dispEM(['Invalid series in getINITSteps: ' series])
+0125 end
+0126 
+0127 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/INIT/groupRxnScores.html b/doc/INIT/groupRxnScores.html new file mode 100644 index 000000000..8d1887151 --- /dev/null +++ b/doc/INIT/groupRxnScores.html @@ -0,0 +1,124 @@ + + + + Description of groupRxnScores + + + + + + + + + +
Home > INIT > groupRxnScores.m
+ + + +

groupRxnScores +

+ +

PURPOSE ^

+
groupRxnScores
+ +

SYNOPSIS ^

+
function newRxnScores = groupRxnScores(model, origRxnScores, origRxnIds, groupIds, origRxnsToZero)
+ +

DESCRIPTION ^

+
 groupRxnScores
+ This function sums up the reaction scores for all reactions that were merged 
+ into one by the linear merge.
+ 
+ model          The model with linearly merged rxns.
+ origRxnScores  The rxnScores from the model before the linear merge.
+ origRxnIds     The rxn ids of the model before the linear merge.
+ groupIds       The groupIds vector output from linearMerge.
+                There is one integer for each rxn in origRxnIds. 0 means
+                the reaction was merged. A non-zero integer means that the
+                reaction was merged with all other rxns having the same integer.
+ origRxnsToZero A logical vector saying which of the original rxns that should not
+                be part of the problem. The way this is solved is that all 
+                such reactions have a rxnScore of 0. If any original rxnScore 
+                value should be zero (which is very unlikely) it is changed to 0.01.
+                If the sum of the rxnScores for a merged rxn becomes zero 
+                while some of them are nonzero, the new value will also be 0.01, 
+                to distinguish the rxn from rxns with only rxns to zero.
+                There are two reasons why we don't want zeros in the reaction 
+                scores unless these reactions should be ignored:
+                  1) we want to be able to separate those
+                  2) it is difficult to handle a zero value in the MILP - 
+                     the on/off of such a reaction can be random, so better 
+                     to fix it in one direction.
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function newRxnScores = groupRxnScores(model, origRxnScores, origRxnIds, groupIds, origRxnsToZero)
+0002 % groupRxnScores
+0003 % This function sums up the reaction scores for all reactions that were merged
+0004 % into one by the linear merge.
+0005 %
+0006 % model          The model with linearly merged rxns.
+0007 % origRxnScores  The rxnScores from the model before the linear merge.
+0008 % origRxnIds     The rxn ids of the model before the linear merge.
+0009 % groupIds       The groupIds vector output from linearMerge.
+0010 %                There is one integer for each rxn in origRxnIds. 0 means
+0011 %                the reaction was merged. A non-zero integer means that the
+0012 %                reaction was merged with all other rxns having the same integer.
+0013 % origRxnsToZero A logical vector saying which of the original rxns that should not
+0014 %                be part of the problem. The way this is solved is that all
+0015 %                such reactions have a rxnScore of 0. If any original rxnScore
+0016 %                value should be zero (which is very unlikely) it is changed to 0.01.
+0017 %                If the sum of the rxnScores for a merged rxn becomes zero
+0018 %                while some of them are nonzero, the new value will also be 0.01,
+0019 %                to distinguish the rxn from rxns with only rxns to zero.
+0020 %                There are two reasons why we don't want zeros in the reaction
+0021 %                scores unless these reactions should be ignored:
+0022 %                  1) we want to be able to separate those
+0023 %                  2) it is difficult to handle a zero value in the MILP -
+0024 %                     the on/off of such a reaction can be random, so better
+0025 %                     to fix it in one direction.
+0026 
+0027 
+0028 newRxnScores = zeros(length(model.rxns),1);
+0029 [~,ia,ib] = intersect(model.rxns,origRxnIds);
+0030 grpIdsMerged = nan(length(model.rxns),1);
+0031 grpIdsMerged(ia) = groupIds(ib);
+0032 %check if any of the original scores are 0, in that case change them to 0.01 (unlikely)
+0033 origRxnScores(origRxnScores == 0) = 0.01;
+0034 %Then set the rxn scores for rxns to zero to 0
+0035 origRxnScores(origRxnsToZero) = 0;
+0036 
+0037 %fill in original scores
+0038 newRxnScores(ia) = origRxnScores(ib);
+0039 
+0040 for i = 1:length(model.rxns)
+0041     %for reactions that are not merged with anything, just keep score as it is
+0042     if grpIdsMerged(i) ~= 0
+0043         %find all original rxns in the group
+0044         sel = groupIds == grpIdsMerged(i);
+0045         newRxnScores(i) = sum(origRxnScores(sel));
+0046         if (newRxnScores(i) == 0 && any(origRxnScores(sel) ~= 0))
+0047            %special unfortunate case, where the reactions happen to sum to 0 while some of them are nonzero
+0048            %set to 0.01 in this case (proabably pretty unusual)
+0049            newRxnScores(i) = 0.01;
+0050         end
+0051     end
+0052 end
+0053 
+0054 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/INIT/index.html b/doc/INIT/index.html new file mode 100644 index 000000000..86204bee2 --- /dev/null +++ b/doc/INIT/index.html @@ -0,0 +1,29 @@ + + + + Index for Directory INIT + + + + + + + + + + +
< Master indexIndex for INIT >
+ +

Index for INIT

+ +

Matlab files in this directory:

+ +
 INITStepDesc
 ftINITftINIT
 ftINITFillGapsftINITFillGaps
 ftINITFillGapsForAllTasksftINITFillGapsForAllTasks
 ftINITFillGapsMILPftINITFillGapsMILP
 ftINITInternalAlgftINITInternalAlg
 getExprForRxnScoregetExprForRxnScore
 getINITModelgetINITModel_legacy
 getINITStepsgetINITSteps
 groupRxnScoresgroupRxnScores
 mergeLinearmergeLinear
 prepINITModelprepINITModel
 removeLowScoreGenesremoveLowScoreGenes Remove low-scoring genes from model.
 rescaleModelForINITrescaleModelForINIT
 reverseRxnsreverseRxns
 runINITrunINIT
 scoreComplexModelscoreComplexModel
+ + + + +
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/INIT/mergeLinear.html b/doc/INIT/mergeLinear.html new file mode 100644 index 000000000..16467e80e --- /dev/null +++ b/doc/INIT/mergeLinear.html @@ -0,0 +1,281 @@ + + + + Description of mergeLinear + + + + + + + + + +
Home > INIT > mergeLinear.m
+ + + +

mergeLinear +

+ +

PURPOSE ^

+
mergeLinear
+ +

SYNOPSIS ^

+
function [reducedModel,origRxnIds,groupIds,reversedRxns]=mergeLinear(model, noMergeRxns)
+ +

DESCRIPTION ^

+
 mergeLinear
+   Simplifies a model by merging rxns with linear dependencies. There are two
+   differences from the function in simplifyModel:
+   1) Here we return which reactions were merged
+   2) Here we allow reversible reactions to be merged as well, which will 
+      probably reduce the size of the model more.
+
+   model                 a model structure
+   noMergeRxns           Cell array with reaction IDs that are not allowed to be
+                         merged
+
+   reducedModel          an updated model structure
+   origRxnIds            Cell array: original rxn ids, used together with the groupIds variable
+   groupIds              Vector of ids: merged rxns have the same id, same length as origRxnIds
+                         0 means a reaction was not merged.
+   reversedRxns          Vector of booleans, saying for each rxn if it is reversed in the combined rxns.
+
+ Usage: [reducedModel,origRxnIds,groupIds]=mergeLinear(model,noMergeRxns)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 function [reducedModel,origRxnIds,groupIds,reversedRxns]=mergeLinear(model, noMergeRxns)
+0002 % mergeLinear
+0003 %   Simplifies a model by merging rxns with linear dependencies. There are two
+0004 %   differences from the function in simplifyModel:
+0005 %   1) Here we return which reactions were merged
+0006 %   2) Here we allow reversible reactions to be merged as well, which will
+0007 %      probably reduce the size of the model more.
+0008 %
+0009 %   model                 a model structure
+0010 %   noMergeRxns           Cell array with reaction IDs that are not allowed to be
+0011 %                         merged
+0012 %
+0013 %   reducedModel          an updated model structure
+0014 %   origRxnIds            Cell array: original rxn ids, used together with the groupIds variable
+0015 %   groupIds              Vector of ids: merged rxns have the same id, same length as origRxnIds
+0016 %                         0 means a reaction was not merged.
+0017 %   reversedRxns          Vector of booleans, saying for each rxn if it is reversed in the combined rxns.
+0018 %
+0019 % Usage: [reducedModel,origRxnIds,groupIds]=mergeLinear(model,noMergeRxns)
+0020 
+0021 
+0022 reducedModel=model;
+0023 
+0024 
+0025 reducedModel.genes={};
+0026 reducedModel.rxnGeneMat=sparse(numel(reducedModel.rxns),0);
+0027 reducedModel.grRules(:)={''};
+0028 
+0029 if isfield(reducedModel,'geneShortNames')
+0030     reducedModel.geneShortNames={};
+0031 end
+0032 if isfield(reducedModel,'proteins')
+0033     reducedModel.proteins={};
+0034 end
+0035 if isfield(reducedModel,'geneMiriams')
+0036     reducedModel.geneMiriams={};
+0037 end
+0038 if isfield(reducedModel,'geneComps')
+0039     reducedModel.geneComps=[];
+0040 end
+0041 
+0042 nextGroupId = 1;
+0043 origRxnIds = reducedModel.rxns;
+0044 groupIds = zeros(numel(reducedModel.rxns),1);
+0045 reversedRxns = false(numel(reducedModel.rxns),1);
+0046 
+0047 %Loop through and iteratively group linear reactions
+0048 while 1
+0049     %Get the banned reaction indexes. Note that the indexes will change
+0050     %in each iteration, but the names will not as they won't be merged
+0051     %with any other reaction
+0052     bannedIndexes=getIndexes(reducedModel,noMergeRxns,'rxns');
+0053 
+0054     %Select all metabolites that are only present as reactants/products
+0055     %in one reaction
+0056     twoNonZero = find(sum(reducedModel.S ~= 0, 2) == 2);
+0057 
+0058     mergedSome=false;
+0059 
+0060     %Loop through each of them and see if the reactions should be
+0061     %merged
+0062     for i=1:numel(twoNonZero)
+0063         involvedRxns=find(reducedModel.S(twoNonZero(i),:));
+0064         %Check that we can have one positive and one negative
+0065         pos = sum(reducedModel.S(twoNonZero(i),involvedRxns).' > 0 | reducedModel.rev(involvedRxns));
+0066         neg = sum(reducedModel.S(twoNonZero(i),involvedRxns).' < 0 | reducedModel.rev(involvedRxns));
+0067         
+0068                 
+0069         %Check so that one or both of the reactions haven't been merged
+0070         %already
+0071         if numel(involvedRxns)==2 && isempty(intersect(bannedIndexes,involvedRxns)) && pos >= 1 && neg >= 1
+0072             %first, take care of a special case: If the first reaction is producing the metabolite and if it is reversible,
+0073             %and the second is also producing it and is not reversible, change the order - the code below will not work otherwise
+0074             if reducedModel.rev(involvedRxns(1)) && (~reducedModel.rev(involvedRxns(2))) && ...
+0075                (reducedModel.S(twoNonZero(i),involvedRxns(1)) > 0) && (reducedModel.S(twoNonZero(i),involvedRxns(2)) > 0)
+0076                 involvedRxns = flip(involvedRxns);
+0077             end
+0078             
+0079             %first make sure the first reaction is producing the metabolite
+0080             if reducedModel.S(twoNonZero(i),involvedRxns(1)) < 0
+0081                 %it is not producing the metabolite - fix that
+0082                 %first choice: use the second reaction as producer if it is producing
+0083                 if reducedModel.S(twoNonZero(i),involvedRxns(2)) > 0
+0084                     involvedRxns = flip(involvedRxns);%make the second the first
+0085                 else
+0086                     %now we know that the second reaction is not producing, so we can safely try to make the first a producer
+0087                     if reducedModel.rev(involvedRxns(1)) == 1
+0088                         [reducedModel,reversedRxns] = flipRxn(reducedModel, involvedRxns(1), groupIds, reversedRxns);
+0089                     else %ok, finally try to flip the second reaction
+0090                         if reducedModel.rev(involvedRxns(2)) == 1
+0091                             [reducedModel,reversedRxns] = flipRxn(reducedModel, involvedRxns(2), groupIds, reversedRxns);
+0092                             involvedRxns = flip(involvedRxns);%make the second the first
+0093                         else
+0094                             error('We should never end up here!');
+0095                         end
+0096                     end
+0097                 end
+0098             end
+0099             %Now, make sure the second rxn is a consumer
+0100             if reducedModel.S(twoNonZero(i),involvedRxns(2)) > 0
+0101                 if reducedModel.rev(involvedRxns(2)) == 1
+0102                     [reducedModel,reversedRxns] = flipRxn(reducedModel, involvedRxns(2), groupIds, reversedRxns);
+0103                 else
+0104                     error('We should never end up here!');
+0105                 end
+0106             end
+0107 
+0108             %Calculate how many times the second reaction has to be
+0109             %multiplied before being merged with the first
+0110             stoichRatio=abs(reducedModel.S(twoNonZero(i),involvedRxns(1))/reducedModel.S(twoNonZero(i),involvedRxns(2)));
+0111 
+0112             %Add the second to the first
+0113             reducedModel.S(:,involvedRxns(1))=reducedModel.S(:,involvedRxns(1))+reducedModel.S(:,involvedRxns(2))*stoichRatio;
+0114 
+0115             %Clear the second reaction
+0116             reducedModel.S(:,involvedRxns(2))=0;
+0117 
+0118             %This is to prevent numerical issues. It should be 0
+0119             %already
+0120             reducedModel.S(twoNonZero(i),involvedRxns(1))=0;
+0121 
+0122             %At this point the second reaction is certain to be deleted
+0123             %in a later step and can therefore be ignored
+0124 
+0125             %Recalculate the bounds for the new reaction. This can be
+0126             %problematic since the scale of the bounds may change
+0127             %dramatically. Let the most constraining reaction determine
+0128             %the new bound
+0129             lb1=reducedModel.lb(involvedRxns(1));
+0130             lb2=reducedModel.lb(involvedRxns(2));
+0131             ub1=reducedModel.ub(involvedRxns(1));
+0132             ub2=reducedModel.ub(involvedRxns(2));
+0133 
+0134             if lb2~=-inf
+0135                 reducedModel.lb(involvedRxns(1))=max(lb1,lb2/stoichRatio);
+0136             end
+0137             if ub2~=inf
+0138                 reducedModel.ub(involvedRxns(1))=min(ub1,ub2/stoichRatio);
+0139             end
+0140             
+0141             %take care of the .rev flag - it could be that the combined rxn changes from rev to irrev
+0142             reducedModel.rev(involvedRxns(1)) = reducedModel.rev(involvedRxns(1))*reducedModel.rev(involvedRxns(2));%this is a way to do an "and" operation with 0 and 1 numbers
+0143 
+0144             %Then recalculate the objective coefficient. The resulting
+0145             %coefficient is the weighted sum of the previous
+0146             reducedModel.c(involvedRxns(1))=reducedModel.c(involvedRxns(1))+reducedModel.c(involvedRxns(2))*stoichRatio;
+0147 
+0148             %store which reactions that have been merged
+0149             rxnInd1 = find(strcmp(origRxnIds, reducedModel.rxns(involvedRxns(1))));
+0150             rxnInd2 = find(strcmp(origRxnIds, reducedModel.rxns(involvedRxns(2))));
+0151             grpId = max(groupIds(rxnInd1),groupIds(rxnInd2));
+0152             if grpId == 0
+0153                grpId = nextGroupId;
+0154                nextGroupId = nextGroupId + 1;
+0155             end
+0156 
+0157             if groupIds(rxnInd1) ~= grpId
+0158                if groupIds(rxnInd1) == 0
+0159                    %not merged before, just set the group id
+0160                    groupIds(rxnInd1) = grpId;
+0161                else
+0162                    %merged before - all rxns with the same group id should be changed
+0163                    groupIds(groupIds == groupIds(rxnInd1)) = grpId;
+0164                end
+0165             end
+0166             if groupIds(rxnInd2) ~= grpId
+0167                if groupIds(rxnInd2) == 0
+0168                    %not merged before, just set the group id
+0169                    groupIds(rxnInd2) = grpId;
+0170                else
+0171                    %merged before - all rxns with the same group id should be changed
+0172                    groupIds(groupIds == groupIds(rxnInd2)) = grpId;
+0173                end
+0174             end
+0175 
+0176             %Iterate again
+0177             mergedSome=true;
+0178         end
+0179     end
+0180 
+0181     %All possible reactions merged
+0182     if mergedSome==false
+0183         break;
+0184     end
+0185 
+0186     %Now delete all reactions that involve no metabolites
+0187     I=find(sum(reducedModel.S~=0,1)==0);
+0188 
+0189     %Remove reactions
+0190     reducedModel=removeReactions(reducedModel,I);
+0191 
+0192     %Remove metabolites
+0193     notInUse=sum(reducedModel.S~=0,2)==0;
+0194     reducedModel=removeMets(reducedModel,notInUse);
+0195 end
+0196     
+0197 function [model1,reversedRxns1] = flipRxn(model1, rxnInd, groupIds1, reversedRxns1)
+0198     model1.S(:,rxnInd) = model1.S(:,rxnInd)*-1;
+0199     %swap the bounds
+0200     ub = model1.ub(rxnInd);
+0201     model1.ub(rxnInd) = -model1.lb(rxnInd);
+0202     model1.lb(rxnInd) = -ub;
+0203     %flip the objective
+0204     model1.c(rxnInd) = -model1.c(rxnInd);
+0205     
+0206     %now take care of the reversedRxns - if this is a group, reverse all of the
+0207     %reactions in the group in the reversedRxns index - they will all be reversed at the
+0208     %same time since they are the same rxn.
+0209     rxnIndices = rxnInd;
+0210     if groupIds1(rxnInd) > 0
+0211         rxnIndices = find(groupIds1 == groupIds1(rxnInd));
+0212     end
+0213     reversedRxns1(rxnIndices) = ~reversedRxns1(rxnIndices);
+0214 end
+0215 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/INIT/prepINITModel.html b/doc/INIT/prepINITModel.html new file mode 100644 index 000000000..5b70f0cd6 --- /dev/null +++ b/doc/INIT/prepINITModel.html @@ -0,0 +1,407 @@ + + + + Description of prepINITModel + + + + + + + + + +
Home > INIT > prepINITModel.m
+ + + +

prepINITModel +

+ +

PURPOSE ^

+
prepINITModel
+ +

SYNOPSIS ^

+
function prepData = prepINITModel(origRefModel, taskStruct, spontRxnNames, convertGenes, customRxnsToIgnore, extComp, skipScaling)
+ +

DESCRIPTION ^

+
 prepINITModel
+
+ The purpose of this function is to run time-consuming calculation steps that are not
+ dependent on the RNA-Seq data.
+
+ origRefModel      The model to use. Expected to be something such as Human-GEM, 
+                   Mouse-GEM, etc.
+ taskStruct        The essential tasks. Can be loaded with for example
+                   taskStruct = parseTaskList('../data/metabolicTasks_Essential.txt');
+ spontRxnNames     The spontaneous rxns. (optional, default {})
+ convertGenes      If true the genes are converted to gene names (from 
+                   ENSEMBL) (optional, default false)
+ customRxnsToIgnore These reactions can be ignored in the ignore mask 
+                   (specifying b7=1) (optional, default = {})
+ extComp           Name of the external compartment, typically 's' or 'e'. This
+                   is used for identifying exch and import rxns (optional, default = 'e')
+ prepData          The resulting prepData structure which is used as input to ftINIT
+ skipScaling       If true the scaling step is not run on the minimal model. The 
+                   scaling is there to remove large differences between the 
+                   stoichiometric coefficients within a reaction, since such
+                   differences creates numerical issues in the ftINIT algorithm 
+                   due to limitations in solver resolution. However,
+                   the current scaling step is also risky and may lead to that
+                   some reactions cannot carry flux, since it changes the stoichiometry
+                   of the reactions with large differences. If you experience problems
+                   where the solution is infeasible, it may be worth trying to turn off
+                   the scaling. Note that it is only the minModel that is scaled,
+                   the scaling will not be present in the final model.
+                   Default: (optional, default = false)
+ 
+ Usage: prepData = prepINITModel(origRefModel, taskStruct, spontRxnNames, convertGenes, customRxnsToIgnore, extComp)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function prepData = prepINITModel(origRefModel, taskStruct, spontRxnNames, convertGenes, customRxnsToIgnore, extComp, skipScaling)
+0002 % prepINITModel
+0003 %
+0004 % The purpose of this function is to run time-consuming calculation steps that are not
+0005 % dependent on the RNA-Seq data.
+0006 %
+0007 % origRefModel      The model to use. Expected to be something such as Human-GEM,
+0008 %                   Mouse-GEM, etc.
+0009 % taskStruct        The essential tasks. Can be loaded with for example
+0010 %                   taskStruct = parseTaskList('../data/metabolicTasks_Essential.txt');
+0011 % spontRxnNames     The spontaneous rxns. (optional, default {})
+0012 % convertGenes      If true the genes are converted to gene names (from
+0013 %                   ENSEMBL) (optional, default false)
+0014 % customRxnsToIgnore These reactions can be ignored in the ignore mask
+0015 %                   (specifying b7=1) (optional, default = {})
+0016 % extComp           Name of the external compartment, typically 's' or 'e'. This
+0017 %                   is used for identifying exch and import rxns (optional, default = 'e')
+0018 % prepData          The resulting prepData structure which is used as input to ftINIT
+0019 % skipScaling       If true the scaling step is not run on the minimal model. The
+0020 %                   scaling is there to remove large differences between the
+0021 %                   stoichiometric coefficients within a reaction, since such
+0022 %                   differences creates numerical issues in the ftINIT algorithm
+0023 %                   due to limitations in solver resolution. However,
+0024 %                   the current scaling step is also risky and may lead to that
+0025 %                   some reactions cannot carry flux, since it changes the stoichiometry
+0026 %                   of the reactions with large differences. If you experience problems
+0027 %                   where the solution is infeasible, it may be worth trying to turn off
+0028 %                   the scaling. Note that it is only the minModel that is scaled,
+0029 %                   the scaling will not be present in the final model.
+0030 %                   Default: (optional, default = false)
+0031 %
+0032 % Usage: prepData = prepINITModel(origRefModel, taskStruct, spontRxnNames, convertGenes, customRxnsToIgnore, extComp)
+0033 
+0034 
+0035 if nargin < 3
+0036     spontRxnNames = {}; 
+0037 end
+0038 
+0039 if nargin < 4
+0040     convertGenes = false; 
+0041 end
+0042 
+0043 if nargin < 5
+0044     customRxnsToIgnore = {}; 
+0045 end
+0046 
+0047 if nargin < 6
+0048     extComp = 'e';
+0049 end
+0050 
+0051 if nargin < 7
+0052     skipScaling = false;
+0053 end
+0054 disp('Step 1: Gene rules')
+0055 [origRefModel.grRules, origRefModel.rxnGeneMat] = standardizeGrRules(origRefModel, true);
+0056 
+0057 if convertGenes %For mouse we might want to translate in the opposite direction - this has to be done before calling this function in that case.
+0058     [origRefModel.grRules, origRefModel.genes, origRefModel.rxnGeneMat] = translateGrRules(origRefModel.grRules, 'Name');
+0059 end
+0060 
+0061 
+0062 % Get list of all dead-end/inacessible/constrained reactions in the model.
+0063 % We don't merge linear dependent reactions here, that will happen later.
+0064 % We also don't remove reversibility here, we don't want that in the final
+0065 % models produced. Therefore, this is done as a separate step.
+0066 % This takes quite some time to run
+0067 disp('Step 2: First simplification')
+0068 [~,deletedDeadEndRxns] = simplifyModel(origRefModel,true,false,true,true,true);
+0069 
+0070 % get reduced model
+0071 cModel = removeReactions(origRefModel,deletedDeadEndRxns,false,true);
+0072 
+0073 
+0074 %Then, run the tasks to find out which reactions are essential. These rxns
+0075 %will be forced to carry flux in the optimization later
+0076 
+0077 % determine reactions essential for tasks - takes ~10 min
+0078 % need to add boundary mets first - but only to a temporary model, we don't
+0079 % want those for further processing
+0080 disp('Step 3: Check tasks (~10 min)')
+0081 if ~isempty(taskStruct)
+0082     bModel = closeModel(cModel);
+0083     [taskReport, essentialRxnMat, ~, essentialFluxes] = checkTasks(bModel,[],true,false,true,taskStruct);
+0084 
+0085     %extract the essential rxns:
+0086     sel = sum(essentialRxnMat,2) > 0;
+0087     selInd = find(sel);
+0088     essentialRxns = bModel.rxns(selInd);%382 rxns for human-GEM
+0089 
+0090     %Find metabolites present in taskStruct. We want to avoid removing
+0091     %these metabolites from the final model (even though they may no longer
+0092     %participate in any reacitons) so that the final model is still able to
+0093     %complete all of the tasks without any errors.
+0094     taskMets = union(vertcat(taskStruct.inputs),vertcat(taskStruct.outputs));
+0095     taskMets = union(taskMets, parseRxnEqu(vertcat(taskStruct.equations)));
+0096     modelMets = strcat(cModel.metNames,'[',cModel.comps(cModel.metComps),']');
+0097     [inModel,metInd] = ismember(taskMets,modelMets);
+0098     essentialMetsForTasks = cModel.mets(metInd(inModel));%118 mets
+0099 
+0100     %Remove tasks that cannot be performed
+0101     taskStruct(taskReport.ok == false) = [];
+0102 
+0103 else
+0104     essentialRxns = {};
+0105     essentialMetsForTasks = {};
+0106     taskReport = {};
+0107 end
+0108 
+0109 
+0110 % remove metabolites separately to avoid removing those needed for tasks
+0111 unusedMets = cModel.mets(all(cModel.S == 0,2));%1248 in Human-GEM
+0112 cModel = removeMets(cModel, setdiff(unusedMets,essentialMetsForTasks));
+0113 
+0114 if ~isempty(taskStruct)
+0115 
+0116     %Here, we decide on a direction in which the essential reactions should be forced.
+0117     essentialRevDir = false(length(essentialRxns),1);
+0118     pp = zeros(length(essentialRxns),1);
+0119     nn = zeros(length(essentialRxns),1);
+0120     for i = 1:length(selInd)
+0121         pos = sum(essentialFluxes(selInd(i),essentialRxnMat(selInd(i),:)) > 0);
+0122         neg = sum(essentialFluxes(selInd(i),essentialRxnMat(selInd(i),:)) < 0);
+0123         essentialRevDir(i) = pos < neg;
+0124         pp(i) = pos;
+0125         nn(i) = neg;
+0126     end
+0127 
+0128     %sum(pp>0 & nn>0) %0, so it is not a big problem that different tasks share essential
+0129     %reactions but in different directions, at least no such cases exist now, so we ignore this for now.
+0130 
+0131     %Now create a minimal model for the MILP - we want to make this as small as we can, but we
+0132     %don't want to use this later when we create the final models - just for the first MILP.
+0133     %We don't want boundary metabolites in here either.
+0134 
+0135     %We do a trick with the essential rxns here:
+0136     %What we want is to get rid of the reversibility of the reactions, because reversible reactions require
+0137     %an integer each in the MILP, and we can also get the case that it may be cheaper to force flux in the wrong direction, which
+0138     %will probably not give the gap-filling of reactions that we want.
+0139     %So, we simply change the reversible reactions to irreversible, and flip their direction if the direction
+0140     %to force flux in is negative. We don't need to do anything else, runINIT will then handle all essential rxns
+0141     %as irreversible (and will not add any integers etc. for them).
+0142 
+0143     minModel1 = cModel;
+0144     %for the essential rxns where we should force flux in the positive direction, just make them irreversible
+0145     %for the negative direction, we do the same, but also flip the direction of the reaction
+0146 
+0147     %first flip the reactions with negative direction
+0148     %constructEquations(minModel1,minModel1.rxns(selInd(essentialRevDir))) %looks good
+0149     minModel1 = reverseRxns(minModel1, minModel1.rxns(selInd(essentialRevDir)));
+0150     %constructEquations(minModel2,minModel2.rxns(selInd(essentialRevDir))) %looks good
+0151 
+0152     %Then make them irreversible
+0153     minModel1.rev(selInd) = 0;
+0154     minModel1.lb(selInd) = 0;
+0155 else
+0156     minModel1 = cModel;
+0157 end
+0158 %Now, remove reversibility on any reactions that can only be run in one direction - that simplifies the problem
+0159 %This takes a long time to run (at least an hour or so).
+0160 %This is an important step, we go from 5533 to 3734 reversible rxns, which reduces the size of the MILP,
+0161 %since irreversible rxns are easier to handle.
+0162 disp('Step 4: Second simplification (~1 hour)')
+0163 minModel2 = simplifyModel(minModel1,false,false,false,false,false,false,true);
+0164 
+0165 disp('Step 5: Final work')
+0166 
+0167 %Now, merge all linear dependent rxns - this reduces the size of the model a lot.
+0168 %Size goes from 11888 rxns to 7922 rxns for human-GEM, so this is an important step
+0169 [minModel3,origRxnIds,groupIds]=mergeLinear(minModel2, {});
+0170 
+0171 %we now need to figure out what happened to the essential rxns in the merge step above.
+0172 %Note that it would be ideal to run checkTasks on the result from mergeLinear, but that doesn't work.
+0173 %The exchange rxns have in many cases been merged with other reactions, making it difficult to run
+0174 %the tasks. So, instead we run checkTasks before, and figure out which merged reactions the
+0175 %essential reactions belong to now
+0176 
+0177 %It may be possible to create a minModel2b, run mergeLinear on that (which is quick), and
+0178 %then run checkTasks on the minimized model. Would be good to check if this gives the
+0179 %same result, I'm not sure. The code would get less complicated.
+0180 
+0181 
+0182 if ~isempty(taskStruct)
+0183 
+0184     %find all potential rxns
+0185     rxnIndOrig = ismember(origRxnIds, essentialRxns);
+0186     ids = unique(groupIds(rxnIndOrig));
+0187     ids = ids(ids > 0);%0 means it has not been merged
+0188     rxnCandidates = unique([essentialRxns;origRxnIds(ismember(groupIds, ids))]);%388, essentialRxns is 382
+0189     newEssentialRxns = minModel3.rxns(ismember(minModel3.rxns,rxnCandidates));%196 in Human-GEM
+0190     %setdiff(newEssentialRxns, essentialRxns)%only 2, that is very few
+0191     %setdiff(essentialRxns, newEssentialRxns)%188, that is very many
+0192     %It is probably the case that many essential reactions are linearly dependent on one another, which makes sense.
+0193 else
+0194     newEssentialRxns = {};
+0195 end
+0196 %What is left now is to remove some rxns from the problem, such as exchange rxns and spontaneous rxns.
+0197 %We set the rxn scores of these to exactly 0, and make sure no other scores are zero.
+0198 %runINIT will then handle this, we do >0 and <0 to get positive and negative scores, the rest
+0199 %are not included in the problem.
+0200 %But, this has to happen in the scoring - we identify the reactions in the origrxns here, and then fix this
+0201 %in the scoring for each sample (the function groupRxnScores handles this and is run for each sample).
+0202 
+0203 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+0204 %identify the reactions to ignore in the minModel2
+0205 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+0206 
+0207 %Identify reactions that should be ignored by tINIT, i.e. tINIT will not remove these regardless of score
+0208 
+0209 
+0210 [~,exchRxnInd] = getExchangeRxns(minModel2);
+0211 toIgnoreExch = false(numel(minModel2.rxns),1);
+0212 toIgnoreExch(exchRxnInd) = true;
+0213 toIgnoreImportRxns = false(numel(minModel2.rxns),1);
+0214 toIgnoreSimpleTransp = false(numel(minModel2.rxns),1);
+0215 toIgnoreAdvTransp = false(numel(minModel2.rxns),1);
+0216 toIgnoreS = false(numel(minModel2.rxns),1);
+0217 
+0218 
+0219 
+0220 %sum(toIgnore) %1500 for Human-GEM
+0221 %find simple transport reactions with no GPRs:
+0222 %We really only skip the reactions with two metabolites
+0223 %where they are the same but different compartments - only skip the transport into the cell for now
+0224 numMets = sum(minModel2.S ~= 0, 1);
+0225 scomp = find(strcmp(minModel2.comps,extComp));
+0226 for i = 1:length(minModel2.rxns)
+0227     %check that it has no GPR and that the rxn has two metabolites
+0228     if strcmp(minModel2.grRules(i),'') && (numMets(i) == 2)
+0229       metsComps = minModel2.metComps(minModel2.S(:,i) ~= 0);
+0230       metNames = minModel2.metNames(minModel2.S(:,i) ~= 0);
+0231       if metsComps(1) ~= metsComps(2) && (metsComps(1) == scomp || metsComps(2) == scomp) %different compartments, one is the extComp
+0232           if strcmp(metNames{1}, metNames{2}) %the same metabolite, it is a transport reaction
+0233               toIgnoreImportRxns(i) = true;
+0234           end
+0235       elseif metsComps(1) ~= metsComps(2) %different compartments, no check for extComp
+0236           if strcmp(metNames{1}, metNames{2}) %the same metabolite, it is a transport reaction
+0237               toIgnoreSimpleTransp(i) = true;
+0238           end
+0239       end
+0240     else %check for advanced
+0241         metsInd = find(minModel2.S(:,i) ~= 0);
+0242         %check that we have an even number of mets that is larger than 2 and that we don't have a GPR
+0243         if rem(length(metsInd),2) == 0 && length(metsInd) > 2 && isempty(minModel2.grRules{i})
+0244             %Now check that we have pairs of metabolites that are transported
+0245             SVals = full(minModel2.S(metsInd,i));
+0246             metNames = minModel2.metNames(metsInd);
+0247             comps = minModel2.metComps(metsInd);
+0248             success = true;
+0249             while ~isempty(metNames)
+0250                 if length(metNames) < 2 %this should not happen
+0251                    error('We should never arrive here!');
+0252                 end
+0253                 metMatch = find(strcmp(metNames(2:length(metNames)),metNames{1})) + 1;
+0254                 if length(metMatch) ~= 1 %we want a match, and only one (if there is some other complex transport rxn, we skip that)
+0255                    success = false;
+0256                    break;
+0257                 end
+0258                 if (SVals(1) + SVals(metMatch)) ~= 0 %the stoichiometry is not right
+0259                    success = false;
+0260                    break;
+0261                 end
+0262                 if comps(1) == comps(metMatch) %they must be in different compartments (maybe this need not to be checked)
+0263                    success = false;
+0264                    break;
+0265                 end
+0266                 %now remove the pair and continue with the next
+0267                 SVals([1;metMatch]) = [];
+0268                 metNames([1;metMatch]) = [];
+0269                 comps([1;metMatch]) = [];
+0270             end
+0271             toIgnoreAdvTransp(i) = success;
+0272         end          
+0273     end
+0274 end
+0275 
+0276 %Spontaneous reactions:
+0277 toIgnoreSpont = ismember(minModel2.rxns, spontRxnNames);%only 10 rxns in human-GEM
+0278 
+0279 %rxns without GPRs in the s compartment (outside the cell)
+0280 sCompInd = find(strcmp(minModel2.comps, extComp));
+0281 for i = 1:length(minModel2.rxns)
+0282     metsInd = find(minModel2.S(:,i) ~= 0);
+0283     %check that it has more than 1 metabolite (not exch rxn) and no GPR
+0284     if length(metsInd) > 1 && isempty(minModel2.grRules{i})
+0285         if  all(minModel2.metComps(metsInd) == sCompInd)
+0286             toIgnoreS(i) = true;
+0287         end
+0288     end
+0289 end
+0290 
+0291 toIgnoreAllWithoutGPRs = cellfun(@isempty,minModel2.grRules);
+0292 
+0293 
+0294 %sum(toIgnore)%in total 2375 rxns in human-GEM
+0295 %sum(toIgnoreAllTransp)%in total 3337 rxns in human-GEM, so 1,000 more
+0296 
+0297 %Now, try to scale the model to become more favorable for the solver.
+0298 %In general, we try to make all fluxes as similar as possible.
+0299 %      There is room for improvement here, this function is pretty simple.
+0300 %      It only rescales reactions, while it would be possible to rescale
+0301 %      metabolites as well (ROS => kROS, albumin => millialbumin, etc., but
+0302 %      scaled freely with a mathematical method). It could potentially open up
+0303 %      for using less strict margins in the MILP, and make it run faster.
+0304 if (skipScaling)
+0305     scaledMinModel = minModel3;
+0306 else
+0307     scaledMinModel = rescaleModelForINIT(minModel3);
+0308     scaledMinModel.ub(scaledMinModel.ub > 0) = 1000;
+0309     scaledMinModel.lb(scaledMinModel.lb < 0) = -1000;
+0310 end
+0311 % create data structure with pre-processing results
+0312 prepData.taskReport = taskReport;
+0313 prepData.essentialRxns = newEssentialRxns; %essential rxns in the minModel
+0314 prepData.taskStruct = taskStruct;
+0315 prepData.refModel = cModel;
+0316 prepData.minModel = scaledMinModel;
+0317 prepData.refModelWithBM = closeModel(cModel); %do this here so we don't have to do this for each sample
+0318 prepData.groupIds = groupIds;
+0319 prepData.essentialMetsForTasks = essentialMetsForTasks;
+0320 
+0321 prepData.toIgnoreExch = toIgnoreExch;
+0322 prepData.toIgnoreImportRxns = toIgnoreImportRxns;
+0323 prepData.toIgnoreSimpleTransp = toIgnoreSimpleTransp;
+0324 prepData.toIgnoreAdvTransp = toIgnoreAdvTransp;
+0325 prepData.toIgnoreSpont = toIgnoreSpont;
+0326 prepData.toIgnoreS = toIgnoreS;
+0327 prepData.toIgnoreCustomRxns = ismember(minModel2.rxns, customRxnsToIgnore);
+0328 prepData.toIgnoreAllWithoutGPRs = toIgnoreAllWithoutGPRs;
+0329 
+0330 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/INIT/removeLowScoreGenes.html b/doc/INIT/removeLowScoreGenes.html new file mode 100644 index 000000000..06ff5320b --- /dev/null +++ b/doc/INIT/removeLowScoreGenes.html @@ -0,0 +1,372 @@ + + + + Description of removeLowScoreGenes + + + + + + + + + +
Home > INIT > removeLowScoreGenes.m
+ + + +

removeLowScoreGenes +

+ +

PURPOSE ^

+
removeLowScoreGenes Remove low-scoring genes from model.
+ +

SYNOPSIS ^

+
function [newModel,remGenes] = removeLowScoreGenes(model,geneScores,isozymeScoring,complexScoring)
+ +

DESCRIPTION ^

+
removeLowScoreGenes  Remove low-scoring genes from model.
+
+   This function removes genes from a model based on their scores, a step
+   used by the tINIT package. The function recognizes and differentiates
+   between isozymes and subunits of an enzyme complex. Genes are removed
+   from each grRule, subject to the following conditions:
+       1) At least one gene must remain associated with the reaction
+       2) Genes involved in a complex (joined by ANDs) are not removed
+
+ Usage:
+
+   [newModel,remGenes] = removeLowScoreGenes(model,geneScores,complexScoring);
+
+ Inputs:
+
+   model           Model structure from which genes are to be removed.
+
+   geneScores      A vector of scores associated with the model genes.
+                   Genes with a positive score will remain in the model,
+                   whereas genes with a negative score will try to be
+                   removed.
+                   
+                   If all genes associated with a reaction have a negative
+                   score, then the least-negative gene will remain; if 
+                   there is a tie, one will be selected at random.
+
+                   If a negative-scoring gene is a subunit in a complex, 
+                   it will not be removed; however, the entire complex may
+                   be removed. See the following example cases:
+
+                    Original: G1 or (G2 and G3 and G4)
+                    Negative: G1, G2
+                         New: G2 and G3 and G4
+
+                    Original: G1 or (G2 and G3) or (G4 and G5)
+                    Negative: G1, G2
+                         New: G4 and G5     [using default complexScoring]
+
+                    Original: (G1 and (G2 or G3) and G4)
+                    Negative: G2
+                         New: (G1 and G3 and G4)
+
+   isozymeScoring  Method used to combine the scores of multiple isozymes;
+                   'min', 'max', 'median', or 'average'. 
+                   (optional, default 'max')
+
+   complexScoring  Method used to combine the scores of enzyme complex
+                   subunits: 'min', 'max', 'median', or 'average'. 
+                   (optional, default 'min')
+
+ Outputs:
+
+   newModel        Model with updated gene, grRules, and rxnGeneMat fields
+                   after attemping to remove negative-score genes.
+
+   remGenes        A list of negative-score genes that were fully removed
+                   from the model. Negative-score genes that were removed
+                   from some grRules but not all will not be included in
+                   this list.
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 function [newModel,remGenes] = removeLowScoreGenes(model,geneScores,isozymeScoring,complexScoring)
+0002 %removeLowScoreGenes  Remove low-scoring genes from model.
+0003 %
+0004 %   This function removes genes from a model based on their scores, a step
+0005 %   used by the tINIT package. The function recognizes and differentiates
+0006 %   between isozymes and subunits of an enzyme complex. Genes are removed
+0007 %   from each grRule, subject to the following conditions:
+0008 %       1) At least one gene must remain associated with the reaction
+0009 %       2) Genes involved in a complex (joined by ANDs) are not removed
+0010 %
+0011 % Usage:
+0012 %
+0013 %   [newModel,remGenes] = removeLowScoreGenes(model,geneScores,complexScoring);
+0014 %
+0015 % Inputs:
+0016 %
+0017 %   model           Model structure from which genes are to be removed.
+0018 %
+0019 %   geneScores      A vector of scores associated with the model genes.
+0020 %                   Genes with a positive score will remain in the model,
+0021 %                   whereas genes with a negative score will try to be
+0022 %                   removed.
+0023 %
+0024 %                   If all genes associated with a reaction have a negative
+0025 %                   score, then the least-negative gene will remain; if
+0026 %                   there is a tie, one will be selected at random.
+0027 %
+0028 %                   If a negative-scoring gene is a subunit in a complex,
+0029 %                   it will not be removed; however, the entire complex may
+0030 %                   be removed. See the following example cases:
+0031 %
+0032 %                    Original: G1 or (G2 and G3 and G4)
+0033 %                    Negative: G1, G2
+0034 %                         New: G2 and G3 and G4
+0035 %
+0036 %                    Original: G1 or (G2 and G3) or (G4 and G5)
+0037 %                    Negative: G1, G2
+0038 %                         New: G4 and G5     [using default complexScoring]
+0039 %
+0040 %                    Original: (G1 and (G2 or G3) and G4)
+0041 %                    Negative: G2
+0042 %                         New: (G1 and G3 and G4)
+0043 %
+0044 %   isozymeScoring  Method used to combine the scores of multiple isozymes;
+0045 %                   'min', 'max', 'median', or 'average'.
+0046 %                   (optional, default 'max')
+0047 %
+0048 %   complexScoring  Method used to combine the scores of enzyme complex
+0049 %                   subunits: 'min', 'max', 'median', or 'average'.
+0050 %                   (optional, default 'min')
+0051 %
+0052 % Outputs:
+0053 %
+0054 %   newModel        Model with updated gene, grRules, and rxnGeneMat fields
+0055 %                   after attemping to remove negative-score genes.
+0056 %
+0057 %   remGenes        A list of negative-score genes that were fully removed
+0058 %                   from the model. Negative-score genes that were removed
+0059 %                   from some grRules but not all will not be included in
+0060 %                   this list.
+0061 %
+0062 
+0063 
+0064 if nargin < 3 || isempty(isozymeScoring)
+0065     isozymeScoring = 'max';
+0066 end
+0067 if nargin < 4
+0068     complexScoring = 'min';
+0069 end
+0070 
+0071 if ~isequal(size(model.genes),size(geneScores))
+0072     error('The dimensions of model genes and geneScores do not match.');
+0073 end
+0074 
+0075 % convert logical operators to symbols
+0076 grRules = model.grRules;
+0077 if any(contains(grRules,{'&','|'}))
+0078     symbolicRules = true;
+0079 else
+0080     symbolicRules = false;
+0081 end
+0082 grRules = regexprep(grRules,' and ',' & ');
+0083 grRules = regexprep(grRules,' or ',' | ');
+0084 
+0085 % get unique list of grRules
+0086 [uRules,~,rule_ind] = unique(grRules);
+0087 
+0088 % iterate through each rule
+0089 newRules = uRules;  %initialize newRules
+0090 for i = 1:numel(uRules)
+0091     if isempty(uRules{i}) || ~contains(uRules{i},'|')
+0092         continue
+0093     elseif contains(uRules{i},'&')
+0094         newRules{i} = processComplexRule(uRules{i},model.genes,geneScores,isozymeScoring,complexScoring);
+0095     else
+0096         newRules{i} = processSimpleRule(uRules{i},model.genes,geneScores,isozymeScoring,complexScoring);
+0097     end
+0098 end
+0099 
+0100 % re-map unique rules to model
+0101 newModel = model;
+0102 newModel.grRules = newRules(rule_ind);
+0103 
+0104 % restore original logical operator formatting if it was changed
+0105 if ~symbolicRules
+0106     newModel.grRules = regexprep(newModel.grRules, ' \| ', ' or ');
+0107     newModel.grRules = regexprep(newModel.grRules, ' & ', ' and ');
+0108 end
+0109 
+0110 % regenerate "genes" and "rxnGeneMat" model fields
+0111 [genes,rxnGeneMat] = getGenesFromGrRules(newModel.grRules);
+0112 
+0113 % determine which of the original genes were removed
+0114 remInd = ~ismember(model.genes,genes);
+0115 remGenes = model.genes(remInd);
+0116 
+0117 % Keep the retained genes in their original order rather than the sorted
+0118 % order returned by getGenesFromGrRules. Gene removal never introduces new
+0119 % genes, so the remaining genes are model.genes(~remInd). Preserving this
+0120 % order ensures the gene-associated fields trimmed below (geneShortNames,
+0121 % proteins, etc.), which are indexed by remInd, stay aligned with genes.
+0122 newModel.genes = model.genes(~remInd);
+0123 [~,reorderInd] = ismember(newModel.genes,genes);
+0124 newModel.rxnGeneMat = rxnGeneMat(:,reorderInd);
+0125 
+0126 if isfield(newModel,'geneShortNames')
+0127     newModel.geneShortNames(remInd) = [];
+0128 end
+0129 if isfield(newModel,'proteins')
+0130     newModel.proteins(remInd) = [];
+0131 end
+0132 if isfield(newModel,'geneMiriams')
+0133     newModel.geneMiriams(remInd) = [];
+0134 end
+0135 if isfield(newModel,'geneFrom')
+0136     newModel.geneFrom(remInd) = [];
+0137 end
+0138 if isfield(newModel,'geneComps')
+0139     newModel.geneComps(remInd) = [];
+0140 end
+0141 
+0142 
+0143 end
+0144 
+0145 
+0146 
+0147 function [updatedRule,rScore] = processSimpleRule(rule,genes,gScores,isozymeScoring,complexScoring)
+0148 % Either score or modify a reaction gene rule containig only ANDs or ORs.
+0149 %
+0150 % If the rule contains an enzyme complex (all ANDs), the complex will be
+0151 % scored based on the score of its subunits. Subunits without a score (NaN)
+0152 % will be excluded from the score calculation.
+0153 %
+0154 % If the rule contains only isozymes (all ORs), the negative-score genes
+0155 % will be removed from the rule. Isozymes without a score (NaN) will not be
+0156 % removed from the rule. The resuling rule will then be scored.
+0157 
+0158 
+0159 % get IDs and indices of genes involved in rule
+0160 ruleGenes = unique(regexp(rule,'[^&|\(\) ]+','match'));
+0161 [~,geneInd] = ismember(ruleGenes,genes);
+0162 
+0163 % rules with one or no genes remain unchanged
+0164 if numel(ruleGenes) < 2
+0165     rScore = gScores(geneInd);
+0166     updatedRule = rule;
+0167     return
+0168 end
+0169 
+0170 if ~contains(rule,'&')  % rule contains isozymes
+0171     
+0172     scoreMethod = isozymeScoring;
+0173     negInd = gScores(geneInd) < 0;  % NaNs will return false here
+0174     if all(negInd)
+0175         % get the least negative gene, adding a small random value to avoid a tie
+0176         [~,maxInd] = max(gScores(geneInd) + rand(size(geneInd))*(1e-8));
+0177         updatedRule = ruleGenes{maxInd};
+0178     elseif sum(~negInd) == 1
+0179         updatedRule = ruleGenes{~negInd};
+0180     else
+0181         updatedRule = strjoin(ruleGenes(~negInd),' | ');
+0182         if startsWith(rule,'(')
+0183             updatedRule = ['(',updatedRule,')'];
+0184         end
+0185     end
+0186     
+0187     % update ruleGenes and their indices
+0188     ruleGenes = unique(regexp(updatedRule,'[^&|\(\) ]+','match'));
+0189     [~,geneInd] = ismember(ruleGenes,genes);
+0190     
+0191 elseif ~contains(rule,'|')  % rule contains enzyme complex
+0192     scoreMethod = complexScoring;
+0193     updatedRule = rule;
+0194 else
+0195     error('This function cannot handle rules with both "OR" and "AND" expressions.');
+0196 end
+0197 
+0198 % score rule
+0199 switch lower(scoreMethod)
+0200     case 'min'
+0201         rScore = min(gScores(geneInd),[],'omitnan');
+0202     case 'max'
+0203         rScore = max(gScores(geneInd),[],'omitnan');
+0204     case 'median'
+0205         rScore = median(gScores(geneInd),'omitnan');
+0206     case 'average'
+0207         rScore = mean(gScores(geneInd),'omitnan');
+0208 end
+0209 
+0210 end
+0211 
+0212 
+0213 
+0214 function updatedRule = processComplexRule(rule,genes,gScores,isozymeScoring,complexScoring)
+0215 % Update reactions containing both AND and OR expressions.
+0216 %
+0217 % Negative-score genes will be removed if they are isozymic, whereas they
+0218 % will not be removed if they are part of an enzyme complex. However, if
+0219 % the enzyme complex has a negative score, the entire complex will be
+0220 % removed, as long as it is not the only remaining element in the rule.
+0221 
+0222 
+0223 % Specify phrases to search for in the grRule. These phrases will find
+0224 % genes grouped by all ANDs (first phrase) or all ORs (second phrase).
+0225 search_phrases = {'\([^&|\(\) ]+( & [^&|\(\) ]+)+\)', '\([^&|\(\) ]+( \| [^&|\(\) ]+)+\)'};
+0226 
+0227 % initialize some variables
+0228 subsets = {};  % subsets are groups of genes grouped by all ANDs or all ORs
+0229 c = 1;  % counter to keep track of the group (subset) number
+0230 r_orig = rule;  % record original rule to determine when it stops changing
+0231 for k = 1:100  % iterate some arbitrarily high number of times
+0232     for j = 1:length(search_phrases)
+0233         new_subset = regexp(rule,search_phrases{j},'match')';  % extract subsets
+0234         if ~isempty(new_subset)
+0235             subsets = [subsets; new_subset];  % append to list of subsets
+0236             subset_nums = arrayfun(@num2str,(c:length(subsets))','UniformOutput',false);  % get group numbers to be assigned to the new subsets, and convert to strings
+0237             rule = regexprep(rule,search_phrases{j},strcat('#',subset_nums,'#'),'once');  % replace the subsets in the expression with their group numbers (enclosed by "#"s)
+0238             c = c + length(new_subset);
+0239         end
+0240     end
+0241     if isequal(rule,r_orig)
+0242         break;  % stop iterating when rule stops changing
+0243     else
+0244         r_orig = rule;
+0245     end
+0246 end
+0247 subsets{end+1} = rule;  % add final state of rule as the last subset
+0248 
+0249 % score and update each subset, and append to gene list and gene scores
+0250 for i = 1:numel(subsets)
+0251     [subsets{i},subset_score] = processSimpleRule(subsets{i},genes,gScores,isozymeScoring,complexScoring);
+0252     gScores = [gScores; subset_score];
+0253     genes = [genes; {strcat('#',num2str(i),'#')}];
+0254 end
+0255 
+0256 % reconstruct the rule from its updated subsets
+0257 updatedRule = subsets{end};
+0258 for i = c-1:-1:1
+0259     updatedRule = regexprep(updatedRule,strcat('#',num2str(i),'#'),subsets{i});
+0260 end
+0261 
+0262 end
+0263 
+0264 
+0265
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/INIT/rescaleModelForINIT.html b/doc/INIT/rescaleModelForINIT.html new file mode 100644 index 000000000..fab29af6b --- /dev/null +++ b/doc/INIT/rescaleModelForINIT.html @@ -0,0 +1,129 @@ + + + + Description of rescaleModelForINIT + + + + + + + + + +
Home > INIT > rescaleModelForINIT.m
+ + + +

rescaleModelForINIT +

+ +

PURPOSE ^

+
rescaleModelForINIT
+ +

SYNOPSIS ^

+
function model=rescaleModelForINIT(model, maxStoichDiff)
+ +

DESCRIPTION ^

+
 rescaleModelForINIT
+
+ The idea with this function is to rescale the MILP problem in ftINIT to avoid large differences
+ in flux magnitudes between reactions. Such differences cause among other things
+ difficulties regarding tolerances for integer variables.
+ For now it just scales down all reactions with high stoichiometric coefficients
+ There is room for improvement here - the best would be to convert mets such as albumin
+ to instead represent 1/100 albumin - that would create much less extreme coefficients.
+ This type of improvement is known as scaling in the literature around LPs and MILPs.
+
+ model         the model to be modified (input and output)
+ maxStoichVal  all reactions with stoichiometric coefficent higher than this 
+               will be scaled down. (optional, default 250)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function model=rescaleModelForINIT(model, maxStoichDiff)
+0002 % rescaleModelForINIT
+0003 %
+0004 % The idea with this function is to rescale the MILP problem in ftINIT to avoid large differences
+0005 % in flux magnitudes between reactions. Such differences cause among other things
+0006 % difficulties regarding tolerances for integer variables.
+0007 % For now it just scales down all reactions with high stoichiometric coefficients
+0008 % There is room for improvement here - the best would be to convert mets such as albumin
+0009 % to instead represent 1/100 albumin - that would create much less extreme coefficients.
+0010 % This type of improvement is known as scaling in the literature around LPs and MILPs.
+0011 %
+0012 % model         the model to be modified (input and output)
+0013 % maxStoichVal  all reactions with stoichiometric coefficent higher than this
+0014 %               will be scaled down. (optional, default 250)
+0015 
+0016 if (nargin < 2)
+0017     maxStoichDiff = 25;
+0018 end
+0019 
+0020 %Define maxMinRatio to be the ratio between the largest and smallest
+0021 %stoichiometric coefficients in each reaction.
+0022 %Scale all rxns with maxMinRatio > maxStoichDiff - just set all coeffs that are
+0023 %larger than maxStoichDiff*minVal to that value, and center the mean coeff to 1 for all rxns.
+0024 SAbs = abs(model.S);
+0025 for i = 1:numel(model.rxns)
+0026     tmp = SAbs(:,i);
+0027     tmp = tmp(tmp ~= 0);
+0028     mn = min(tmp);
+0029     %modify matrix
+0030     sign = ones(numel(model.mets),1);
+0031     sign(model.S(:,i) < 0) = -1;
+0032     sel = SAbs(:,i) > maxStoichDiff*mn;
+0033     model.S(sel,i) = sign(sel) .* maxStoichDiff*mn;
+0034 end
+0035 %center around 1
+0036 boolMat = model.S ~= 0;
+0037 absMat = abs(model.S);
+0038 rxnScales = sum(boolMat,1)./sum(absMat,1);
+0039 
+0040 model.S = model.S .* rxnScales;
+0041 
+0042 %{
+0043 if (nargin < 2)
+0044     maxStoichVal = 250;
+0045 end
+0046 
+0047 
+0048 %find all reactions containing high stoichiometry coefficients
+0049 maxCoeffs = max(model.S, [], 1);
+0050 rxnsToCheck = maxCoeffs > maxStoichVal;
+0051 
+0052 %for debugging:
+0053 %constructEquations(model, model.rxns(rxnsToCheck))
+0054 
+0055 rxnsToCheckInd = find(rxnsToCheck);
+0056 
+0057 %We just scale all reactions so they don't have a coefficient > maxStoichVal for now
+0058 
+0059 %do this with a loop, doesn't really matter
+0060 for rxnInd = rxnsToCheckInd
+0061     %find the lowest index which is not a pointless metabolite, such as H+, H2O etc.
+0062     rxnS = model.S(:,rxnInd);
+0063     %metInd = find(rxnS ~= 0);
+0064     
+0065     largestCoeff = max(abs(rxnS));
+0066     scaleFactor = maxStoichVal/largestCoeff;
+0067     model.S(:,rxnInd) = model.S(:,rxnInd) .* scaleFactor;
+0068 end
+0069 %}
+0070 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/INIT/reverseRxns.html b/doc/INIT/reverseRxns.html new file mode 100644 index 000000000..abca5f469 --- /dev/null +++ b/doc/INIT/reverseRxns.html @@ -0,0 +1,68 @@ + + + + Description of reverseRxns + + + + + + + + + +
Home > INIT > reverseRxns.m
+ + + +

reverseRxns +

+ +

PURPOSE ^

+
reverseRxns
+ +

SYNOPSIS ^

+
function model=reverseRxns(model, rxns)
+ +

DESCRIPTION ^

+
 reverseRxns
+ Reverses reactions
+ model     the model to change (input/output)
+ rxns      the rxns to reverse
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function model=reverseRxns(model, rxns)
+0002 % reverseRxns
+0003 % Reverses reactions
+0004 % model     the model to change (input/output)
+0005 % rxns      the rxns to reverse
+0006 
+0007 rxnInd = find(ismember(model.rxns,rxns));
+0008 
+0009 %reverse the reactions
+0010 model.S(:,rxnInd) = model.S(:,rxnInd)*-1;
+0011 %swap the bounds
+0012 ub = model.ub(rxnInd);
+0013 model.ub(rxnInd) = -model.lb(rxnInd);
+0014 model.lb(rxnInd) = -ub;
+0015 %flip the objective
+0016 model.c(rxnInd) = -model.c(rxnInd);
+0017 
+0018 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/INIT/runINIT.html b/doc/INIT/runINIT.html new file mode 100644 index 000000000..15cbb20d1 --- /dev/null +++ b/doc/INIT/runINIT.html @@ -0,0 +1,445 @@ + + + + Description of runINIT + + + + + + + + + +
Home > INIT > runINIT.m
+ + + +

runINIT +

+ +

PURPOSE ^

+
runINIT
+ +

SYNOPSIS ^

+
function [outModel, deletedRxns, metProduction, fValue]=runINIT(model,rxnScores,presentMets,essentialRxns,prodWeight,allowExcretion,noRevLoops,params)
+ +

DESCRIPTION ^

+
 runINIT
+    Generates a model using the INIT algorithm, based on proteomics and/or
+   transcriptomics and/or metabolomics and/or metabolic tasks. This is the 
+   original implementation, which is now replaced with ftINIT.
+
+   model           a reference model structure
+   rxnScores       a vector of scores for the reactions in the model.
+                   Positive scores are reactions to keep and negative
+                   scores are reactions to exclude (optional, default all 0.0)
+   presentMets     cell array with unique metabolite names that the model
+                   should produce (optional, default [])
+   essentialRxns   cell array of reactions that are essential and that
+                   have to be in the resulting model. This is normally
+                   used when fitting a model to task (see fitTasks) (optional,
+                   default [])
+   prodWeight      a score that determines the value of having
+                   net-production of metabolites. This is a way of having
+                   a more functional network as it provides a reason for
+                   including bad reactions for connectivity reasons. This
+                   score is for each metabolite, and the sum of these weights
+                   and the scores for the reactions is what is optimized
+                   (optional, default 0.5)
+   allowExcretion  true if excretion of all metabolites should be allowed.
+                   This results in fewer reactions being considered
+                   dead-ends, but all reactions in the resulting model may
+                   not be able to carry flux. If this is "false" then the
+                   equality constraints are taken from model.b. If the
+                   input model lacks exchange reactions then this should
+                   probably be "true", or a large proportion of the model
+                   would be excluded for connectivity reasons
+                   (optional, default false)
+   noRevLoops      true if reversible reactions should be constrained to
+                   only carry flux in one direction. This prevents
+                   reversible reactions from being wrongly assigned as
+                   connected (the forward and backward reactions can form a
+                   loop and therefore appear connected), but it makes the
+                   problem significantly more computationally intensive to
+                   solve (two more integer constraints per reversible reaction)
+                   (optional, default false)
+   params          parameter structure for use by optimizeProb
+
+   outModel        the resulting model structure
+   deletedRxns     reactions which were deleted by the algorithm
+   metProduction   array that indicates which of the
+                   metabolites in presentMets that could be
+                   produced
+                   -2: metabolite name not found in model
+                   -1: metabolite found, but it could not be produced
+                   1: metabolite could be produced
+   fValue          objective value (sum of (the negative of)
+                   reaction scores for the included reactions and
+                   prodWeight*number of produced metabolites)
+
+   This function is the actual implementation of the algorithm. See
+   getINITModel for a higher-level function for model reconstruction. See
+   PLoS Comput Biol. 2012;8(5):e1002518 for details regarding the
+   implementation.
+
+ Usage: [outModel deletedRxns metProduction fValue]=runINIT(model,...
+           rxnScores,presentMets,essentialRxns,prodWeight,allowExcretion,...
+           noRevLoops,params)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function [outModel, deletedRxns, metProduction, fValue]=runINIT(model,rxnScores,presentMets,essentialRxns,prodWeight,allowExcretion,noRevLoops,params)
+0002 % runINIT
+0003 %    Generates a model using the INIT algorithm, based on proteomics and/or
+0004 %   transcriptomics and/or metabolomics and/or metabolic tasks. This is the
+0005 %   original implementation, which is now replaced with ftINIT.
+0006 %
+0007 %   model           a reference model structure
+0008 %   rxnScores       a vector of scores for the reactions in the model.
+0009 %                   Positive scores are reactions to keep and negative
+0010 %                   scores are reactions to exclude (optional, default all 0.0)
+0011 %   presentMets     cell array with unique metabolite names that the model
+0012 %                   should produce (optional, default [])
+0013 %   essentialRxns   cell array of reactions that are essential and that
+0014 %                   have to be in the resulting model. This is normally
+0015 %                   used when fitting a model to task (see fitTasks) (optional,
+0016 %                   default [])
+0017 %   prodWeight      a score that determines the value of having
+0018 %                   net-production of metabolites. This is a way of having
+0019 %                   a more functional network as it provides a reason for
+0020 %                   including bad reactions for connectivity reasons. This
+0021 %                   score is for each metabolite, and the sum of these weights
+0022 %                   and the scores for the reactions is what is optimized
+0023 %                   (optional, default 0.5)
+0024 %   allowExcretion  true if excretion of all metabolites should be allowed.
+0025 %                   This results in fewer reactions being considered
+0026 %                   dead-ends, but all reactions in the resulting model may
+0027 %                   not be able to carry flux. If this is "false" then the
+0028 %                   equality constraints are taken from model.b. If the
+0029 %                   input model lacks exchange reactions then this should
+0030 %                   probably be "true", or a large proportion of the model
+0031 %                   would be excluded for connectivity reasons
+0032 %                   (optional, default false)
+0033 %   noRevLoops      true if reversible reactions should be constrained to
+0034 %                   only carry flux in one direction. This prevents
+0035 %                   reversible reactions from being wrongly assigned as
+0036 %                   connected (the forward and backward reactions can form a
+0037 %                   loop and therefore appear connected), but it makes the
+0038 %                   problem significantly more computationally intensive to
+0039 %                   solve (two more integer constraints per reversible reaction)
+0040 %                   (optional, default false)
+0041 %   params          parameter structure for use by optimizeProb
+0042 %
+0043 %   outModel        the resulting model structure
+0044 %   deletedRxns     reactions which were deleted by the algorithm
+0045 %   metProduction   array that indicates which of the
+0046 %                   metabolites in presentMets that could be
+0047 %                   produced
+0048 %                   -2: metabolite name not found in model
+0049 %                   -1: metabolite found, but it could not be produced
+0050 %                   1: metabolite could be produced
+0051 %   fValue          objective value (sum of (the negative of)
+0052 %                   reaction scores for the included reactions and
+0053 %                   prodWeight*number of produced metabolites)
+0054 %
+0055 %   This function is the actual implementation of the algorithm. See
+0056 %   getINITModel for a higher-level function for model reconstruction. See
+0057 %   PLoS Comput Biol. 2012;8(5):e1002518 for details regarding the
+0058 %   implementation.
+0059 %
+0060 % Usage: [outModel deletedRxns metProduction fValue]=runINIT(model,...
+0061 %           rxnScores,presentMets,essentialRxns,prodWeight,allowExcretion,...
+0062 %           noRevLoops,params)
+0063 
+0064 if nargin<2
+0065     rxnScores=zeros(numel(model.rxns),1);
+0066 end
+0067 if isempty(rxnScores)
+0068     rxnScores=zeros(numel(model.rxns),1);
+0069 end
+0070 if nargin<3 || isempty(presentMets)
+0071     presentMets={};
+0072 else
+0073     presentMets=convertCharArray(presentMets);
+0074 end
+0075 if nargin<4 || isempty(essentialRxns)
+0076     essentialRxns={};
+0077 else
+0078     essentialRxns=convertCharArray(essentialRxns);
+0079 end
+0080 if nargin<5 || isempty(prodWeight)
+0081     prodWeight=0.5;
+0082 end
+0083 if nargin<6
+0084     allowExcretion=false;
+0085 end
+0086 if nargin<7
+0087     noRevLoops=false;
+0088 end
+0089 if nargin<8
+0090     params=[];
+0091 end
+0092 
+0093 if numel(presentMets)~=numel(unique(presentMets))
+0094     EM='Duplicate metabolite names in presentMets';
+0095     dispEM(EM);
+0096 end
+0097 
+0098 %Default is that the metabolites cannot be produced
+0099 if ~isempty(presentMets)
+0100     metProduction=ones(numel(presentMets),1)*-2;
+0101     presentMets=upper(presentMets);
+0102     pmIndexes=find(ismember(presentMets,upper(model.metNames)));
+0103     metProduction(pmIndexes)=-1; %Then set that they are at least found
+0104 else
+0105     metProduction=[];
+0106     pmIndexes=[];
+0107 end
+0108 
+0109 %The model should be in the reversible format and all relevant exchange
+0110 %reactions should be open
+0111 if isfield(model,'unconstrained')
+0112     EM='Exchange metabolites are still present in the model. Use simplifyModel if this is not intended';
+0113     dispEM(EM,false);
+0114 end
+0115 
+0116 %The irreversible reactions that are essential must have a flux and are
+0117 %therefore not optimized for using MILP, which reduces the problem size.
+0118 %However, reversible reactions must have a flux in one direction, so they
+0119 %have to stay in the problem. The essentiality constraint on reversible
+0120 %reactions is implemented in the same manner as for reversible reactions
+0121 %when noRevLoops==true, but with the additional constraint that C ub=-1.
+0122 %This forces one of the directions to be active.
+0123 revRxns=find(model.rev~=0);
+0124 essentialReversible=find(ismember(model.rxns(revRxns),essentialRxns));
+0125 essentialRxns=intersect(essentialRxns,model.rxns(model.rev==0));
+0126 
+0127 %Convert the model to irreversible
+0128 irrevModel=convertToIrrev(model);
+0129 rxnScores=[rxnScores;rxnScores(model.rev==1)];
+0130 %These are used if noRevLoops is true
+0131 if noRevLoops==true
+0132     forwardIndexes=find(model.rev~=0);
+0133     backwardIndexes=(numel(model.rxns)+1:numel(irrevModel.rxns))';
+0134 else
+0135     %Then they should only be used for essential reversible reactions
+0136     forwardIndexes=revRxns(essentialReversible);
+0137     backwardIndexes=essentialReversible+numel(model.rxns);
+0138 end
+0139 
+0140 %Get the indexes of the essential reactions and remove them from the
+0141 %scoring vector
+0142 essentialIndex=find(ismember(irrevModel.rxns,essentialRxns));
+0143 rxnScores(essentialIndex)=[];
+0144 
+0145 %Go through each of the presentMets (if they exist) and modify the S matrix
+0146 %so that each reaction which produces any of them also produces a
+0147 %corresponding fake metabolite and the opposite in the reverse direction.
+0148 
+0149 %This is to deal with the fact that there is no compartment info regarding
+0150 %the presentMets. This modifies the irrevModel structure, but that is fine
+0151 %since it's the model structure that is returned.
+0152 if any(pmIndexes)
+0153     irrevModel.metNames=upper(irrevModel.metNames);
+0154     metsToAdd.mets=strcat({'FAKEFORPM'},num2str(pmIndexes));
+0155     metsToAdd.metNames=metsToAdd.mets;
+0156     metsToAdd.compartments=irrevModel.comps{1};
+0157     
+0158     %There is no constraints on the metabolites yet, since maybe not all of
+0159     %them could be produced
+0160     irrevModel=addMets(irrevModel,metsToAdd);
+0161 end
+0162 
+0163 %Modify the matrix
+0164 for i=1:numel(pmIndexes)
+0165     %Get the matching mets
+0166     I=ismember(irrevModel.metNames,presentMets(pmIndexes(i)));
+0167     
+0168     %Find the reactions where any of them are used.
+0169     [~, K, L]=find(irrevModel.S(I,:));
+0170     
+0171     %This ugly loop is to avoid problems if a metabolite occurs several
+0172     %times in one reaction
+0173     KK=unique(K);
+0174     LL=zeros(numel(KK),1);
+0175     for j=1:numel(KK)
+0176         LL(j)=sum(L(K==KK(j)));
+0177     end
+0178     irrevModel.S(numel(irrevModel.mets)-numel(pmIndexes)+i,KK)=LL;
+0179 end
+0180 
+0181 %Some nice to have numbers
+0182 nMets=numel(irrevModel.mets);
+0183 nRxns=numel(irrevModel.rxns);
+0184 nEssential=numel(essentialIndex);
+0185 nNonEssential=nRxns-nEssential;
+0186 nonEssentialIndex=setdiff(1:nRxns,essentialIndex);
+0187 S=irrevModel.S;
+0188 
+0189 %Add so that each non-essential reaction produces one unit of a fake
+0190 %metabolite
+0191 temp=sparse(1:nRxns,1:nRxns,1);
+0192 temp(essentialIndex,:)=[];
+0193 S=[S;temp];
+0194 
+0195 %Add another set of reactions (will be binary) which also produce these
+0196 %fake metabolites, but with a stoichiometry of 1000
+0197 temp=sparse(1:nNonEssential,1:nNonEssential,1000);
+0198 temp=[sparse(nMets,nNonEssential);temp];
+0199 S=[S temp];
+0200 
+0201 %Add reactions for net-production of (real) metabolites
+0202 if prodWeight~=0
+0203     temp=[speye(nMets-numel(pmIndexes))*-1;sparse(nNonEssential+numel(pmIndexes),nMets-numel(pmIndexes))];
+0204     S=[S temp];
+0205     %To keep the number of reactions added like this
+0206     nNetProd=nMets-numel(pmIndexes);
+0207 else
+0208     nNetProd=0;
+0209 end
+0210 
+0211 %Add constraints so that reversible reactions can only be used in one
+0212 %direction. This is done by adding the fake metabolites A, B, C for each
+0213 %reversible reaction in the following manner
+0214 % forward: A + .. => ... backwards: B + ... => ... int1: C => 1000 A int2:
+0215 % C => 1000 B A ub=999.9 B ub=999.9 C lb=-1 int1 and int2 are binary
+0216 if any(forwardIndexes)
+0217     nRevBounds=numel(forwardIndexes);
+0218     
+0219     %Add the A metabolites for the forward reactions and the B metabolites
+0220     %for the reverse reactions
+0221     I=speye(numel(irrevModel.rxns))*-1;
+0222     temp=[I(forwardIndexes,:);I(backwardIndexes,:)];
+0223     
+0224     %Padding
+0225     temp=[temp sparse(size(temp,1),size(S,2)-numel(irrevModel.rxns))];
+0226     
+0227     %Add the int1 & int2 reactions that produce A and B
+0228     temp=[temp speye(nRevBounds*2)*1000];
+0229     
+0230     %And add that they also consume C
+0231     temp=[temp;[sparse(nRevBounds,size(S,2)) speye(nRevBounds)*-1 speye(nRevBounds)*-1]];
+0232     
+0233     %Add the new reactions and metabolites
+0234     S=[S sparse(size(S,1),nRevBounds*2)];
+0235     S=[S;temp];
+0236 else
+0237     nRevBounds=0;
+0238 end
+0239 
+0240 %Add so that the essential reactions must have a small flux and that the
+0241 %binary ones (and net-production reactions) may have zero flux. The integer
+0242 %reactions for reversible reactions have [0 1]
+0243 prob.blx=[irrevModel.lb;zeros(nNonEssential+nNetProd+nRevBounds*2,1)];
+0244 prob.blx(essentialIndex)=max(0.1,prob.blx(essentialIndex));
+0245 
+0246 %Add so that the binary ones and net-production reactions can have at the
+0247 %most flux 1.0
+0248 prob.bux=[irrevModel.ub;ones(nNonEssential+nNetProd+nRevBounds*2,1)];
+0249 
+0250 %Add that the fake metabolites must be produced in a small amount and that
+0251 %the A and B metabolites for reversible reactions can be [0 999.9] and C
+0252 %metabolites [-1 0]
+0253 prob.blc=[irrevModel.b(:,1);ones(nNonEssential,1);zeros(nRevBounds*2,1);ones(nRevBounds,1)*-1];
+0254 
+0255 %Add that normal metabolites can be freely excreted if
+0256 %allowExcretion==true, and that the fake ones can be excreted 1000 units at
+0257 %most. C metabolites for essential reversible reactions should have an
+0258 %upper bound of -1. If noRevLoops is false, then add this constraint for
+0259 %all the reactions instead.
+0260 if noRevLoops==true
+0261     revUB=zeros(nRevBounds,1);
+0262     revUB(essentialReversible)=-1;
+0263 else
+0264     revUB=ones(nRevBounds,1)*-1;
+0265 end
+0266 if allowExcretion==true
+0267     metUB=inf(nMets,1);
+0268 else
+0269     metUB=irrevModel.b(:,min(size(irrevModel.b,2),2));
+0270 end
+0271 prob.buc=[metUB;ones(nNonEssential,1)*1000;ones(nRevBounds*2,1)*999.9;revUB];
+0272 
+0273 %Add objective coefficients for the binary reactions. The negative is used
+0274 %since we're minimizing. The negative is taken for the prodWeight as well,
+0275 %in order to be consistent with the syntax that positive scores are good
+0276 prob.c=[zeros(nRxns,1);rxnScores;ones(nNetProd,1)*prodWeight*-1;zeros(nRevBounds*2,1)];
+0277 prob.a=S;
+0278 
+0279 % adapt problem structure for cobra-style solver
+0280 prob.c=[prob.c;zeros(size(prob.a,1),1)];
+0281 prob.A=[prob.a -speye(size(prob.a,1))];
+0282 prob.b=zeros(size(prob.a,1), 1);
+0283 prob.ub=[prob.bux; prob.buc];
+0284 prob.osense=1;
+0285 prob.csense=char(zeros(1,size(prob.a,1)));
+0286 prob.csense(:)='E';
+0287 
+0288 %We still don't know which of the presentMets that can be produced. Go
+0289 %through them, force production, and see if the problem can be solved
+0290 for i=1:numel(pmIndexes)
+0291     prob.blc(numel(irrevModel.mets)-numel(pmIndexes)+i)=1;
+0292     prob.lb=[prob.blx; prob.blc];
+0293     res=optimizeProb(prob,params);
+0294     isFeasible=checkSolution(res);
+0295     if ~isFeasible
+0296         %Reset the constraint again
+0297         prob.blc(numel(irrevModel.mets)-numel(pmIndexes)+i)=0;
+0298     else
+0299         %Metabolite produced
+0300         metProduction(pmIndexes(i))=1;
+0301     end
+0302 end
+0303 prob.lb=[prob.blx; prob.blc];
+0304 
+0305 %Add that the binary reactions may only take integer values.
+0306 prob.vartype = repmat('C', 1, size(prob.A, 2));
+0307 allInt=[(nRxns+1):(nRxns+nNonEssential) size(S,2)-nRevBounds*2+1:size(S,2)];
+0308 prob.vartype(allInt) = 'B';
+0309 
+0310 % solve problem
+0311 res=optimizeProb(prob,params);
+0312 
+0313 %Problem should not be infeasible, but it is possible that the time limit
+0314 %was reached before finding any solutions.
+0315 if ~checkSolution(res)
+0316     if strcmp(res.origStat, 'TIME_LIMIT')
+0317         EM='Time limit reached without finding a solution. Try increasing the TimeLimit parameter.';
+0318     else
+0319         EM='The problem is infeasible';
+0320     end
+0321     dispEM(EM);
+0322 end
+0323 
+0324 fValue=res.obj;
+0325 
+0326 %Get all reactions used in the irreversible model
+0327 usedRxns=(nonEssentialIndex(res.full(nRxns+1:nRxns+nNonEssential)<0.1))';
+0328 
+0329 %Map to reversible model IDs
+0330 usedRxns=[usedRxns(usedRxns<=numel(model.rxns));revRxns(usedRxns(usedRxns>numel(model.rxns))-numel(model.rxns))];
+0331 
+0332 %Then get the ones that are not used in either direction or is essential
+0333 I=true(numel(model.rxns),1);
+0334 I(usedRxns)=false;
+0335 I(essentialIndex)=false;
+0336 deletedRxns=model.rxns(I);
+0337 outModel=removeReactions(model,I,true,true);
+0338 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/INIT/scoreComplexModel.html b/doc/INIT/scoreComplexModel.html new file mode 100644 index 000000000..51ace0e59 --- /dev/null +++ b/doc/INIT/scoreComplexModel.html @@ -0,0 +1,482 @@ + + + + Description of scoreComplexModel + + + + + + + + + +
Home > INIT > scoreComplexModel.m
+ + + +

scoreComplexModel +

+ +

PURPOSE ^

+
scoreComplexModel
+ +

SYNOPSIS ^

+
function [rxnScores, geneScores, hpaScores, arrayScores] = scoreComplexModel(model,hpaData,arrayData,tissue,celltype,noGeneScore,isozymeScoring,complexScoring,multipleCellScoring,hpaLevelScores)
+ +

DESCRIPTION ^

+
 scoreComplexModel
+   Scores the reactions and genes in a model containing complex gene rules
+   based on expression data from HPA and/or gene arrays.
+
+   It is highly recommended that the model grRules are "cleaned" and
+   verified by the "cleanModelGeneRules" function prior to scoring the
+   model with scoreComplexModel.
+
+   model               a model structure
+   hpaData             HPA data structure from parseHPA (optional if arrayData is
+                       supplied, default [])
+   arrayData           gene expression data structure (optional if hpaData is
+                       supplied, default [])
+       genes           cell array with the unique gene names
+       tissues         cell array with the tissue names. The list may not be
+                       unique, as there can be multiple cell types per tissue
+       celltypes       cell array with the cell type names for each tissue
+       levels          GENESxTISSUES array with the expression level for
+                       each gene in each tissue/celltype. NaN should be
+                       used when no measurement was performed
+       threshold       a single value or a vector of gene expression 
+                       thresholds, above which genes are considered to be
+                       "expressed". (optional, by default, the mean expression
+                       levels of each gene across all tissues in arrayData
+                       will be used as the threshold values)
+   tissue              tissue to score for. Should exist in either
+                       hpaData.tissues or arrayData.tissues
+   celltype            cell type to score for. Should exist in either
+                       hpaData.celltypes or arrayData.celltypes for this
+                       tissue (optional, default is to use the max values
+                       among all the cell types for the tissue. Use [] if
+                       you want to supply more arguments)
+   noGeneScore         score for reactions without genes (optional, default -2)
+   isozymeScoring      determines how scores are calculated for reactions
+                       with multiple genes joined by "OR" expression(s)
+                       ('min', 'max', 'median', 'average')
+                       (optional, default 'max')
+   complexScoring      determines how scores are calculated for reactions
+                       with multiple genes joined by "AND" expression(s)
+                       ('min', 'max', 'median', 'average')
+                       (optional, default 'min')
+   multipleCellScoring determines how scores are calculated when several
+                       cell types are used ('max' or 'average')
+                       (optional, default 'max')
+   hpaLevelScores      structure with numerical scores for the expression
+                       level categories from HPA. The structure should have a
+                       "names" and a "scores" field (optional, see code for
+                       default scores)
+
+   rxnScores       scores for each of the reactions in model
+   geneScores      scores for each of the genes in model. Genes which are
+                   not in the dataset(s) have -Inf as scores
+   hpaScores       scores for each of the genes in model if only taking hpaData
+                   into account. Genes which are not in the dataset(s)
+                   have -Inf as scores
+   arrayScores     scores for each of the genes in model if only taking arrayData
+                   into account. Genes which are not in the dataset(s)
+                   have -Inf as scores
+
+ Usage: [rxnScores, geneScores, hpaScores, arrayScores]=scoreComplexModel(...
+               model,hpaData,arrayData,tissue,celltype,noGeneScore,isozymeScoring,
+               complexScoring,multipleCellScoring,hpaLevelScores)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 function [rxnScores, geneScores, hpaScores, arrayScores] = scoreComplexModel(model,hpaData,arrayData,tissue,celltype,noGeneScore,isozymeScoring,complexScoring,multipleCellScoring,hpaLevelScores)
+0002 % scoreComplexModel
+0003 %   Scores the reactions and genes in a model containing complex gene rules
+0004 %   based on expression data from HPA and/or gene arrays.
+0005 %
+0006 %   It is highly recommended that the model grRules are "cleaned" and
+0007 %   verified by the "cleanModelGeneRules" function prior to scoring the
+0008 %   model with scoreComplexModel.
+0009 %
+0010 %   model               a model structure
+0011 %   hpaData             HPA data structure from parseHPA (optional if arrayData is
+0012 %                       supplied, default [])
+0013 %   arrayData           gene expression data structure (optional if hpaData is
+0014 %                       supplied, default [])
+0015 %       genes           cell array with the unique gene names
+0016 %       tissues         cell array with the tissue names. The list may not be
+0017 %                       unique, as there can be multiple cell types per tissue
+0018 %       celltypes       cell array with the cell type names for each tissue
+0019 %       levels          GENESxTISSUES array with the expression level for
+0020 %                       each gene in each tissue/celltype. NaN should be
+0021 %                       used when no measurement was performed
+0022 %       threshold       a single value or a vector of gene expression
+0023 %                       thresholds, above which genes are considered to be
+0024 %                       "expressed". (optional, by default, the mean expression
+0025 %                       levels of each gene across all tissues in arrayData
+0026 %                       will be used as the threshold values)
+0027 %   tissue              tissue to score for. Should exist in either
+0028 %                       hpaData.tissues or arrayData.tissues
+0029 %   celltype            cell type to score for. Should exist in either
+0030 %                       hpaData.celltypes or arrayData.celltypes for this
+0031 %                       tissue (optional, default is to use the max values
+0032 %                       among all the cell types for the tissue. Use [] if
+0033 %                       you want to supply more arguments)
+0034 %   noGeneScore         score for reactions without genes (optional, default -2)
+0035 %   isozymeScoring      determines how scores are calculated for reactions
+0036 %                       with multiple genes joined by "OR" expression(s)
+0037 %                       ('min', 'max', 'median', 'average')
+0038 %                       (optional, default 'max')
+0039 %   complexScoring      determines how scores are calculated for reactions
+0040 %                       with multiple genes joined by "AND" expression(s)
+0041 %                       ('min', 'max', 'median', 'average')
+0042 %                       (optional, default 'min')
+0043 %   multipleCellScoring determines how scores are calculated when several
+0044 %                       cell types are used ('max' or 'average')
+0045 %                       (optional, default 'max')
+0046 %   hpaLevelScores      structure with numerical scores for the expression
+0047 %                       level categories from HPA. The structure should have a
+0048 %                       "names" and a "scores" field (optional, see code for
+0049 %                       default scores)
+0050 %
+0051 %   rxnScores       scores for each of the reactions in model
+0052 %   geneScores      scores for each of the genes in model. Genes which are
+0053 %                   not in the dataset(s) have -Inf as scores
+0054 %   hpaScores       scores for each of the genes in model if only taking hpaData
+0055 %                   into account. Genes which are not in the dataset(s)
+0056 %                   have -Inf as scores
+0057 %   arrayScores     scores for each of the genes in model if only taking arrayData
+0058 %                   into account. Genes which are not in the dataset(s)
+0059 %                   have -Inf as scores
+0060 %
+0061 % Usage: [rxnScores, geneScores, hpaScores, arrayScores]=scoreComplexModel(...
+0062 %               model,hpaData,arrayData,tissue,celltype,noGeneScore,isozymeScoring,
+0063 %               complexScoring,multipleCellScoring,hpaLevelScores)
+0064 %
+0065 
+0066 
+0067 if nargin < 5
+0068     celltype = [];
+0069 end
+0070 if nargin < 6 || isempty(noGeneScore)
+0071     noGeneScore = -2;
+0072 end
+0073 if nargin < 7 || isempty(isozymeScoring)
+0074     isozymeScoring = 'max';
+0075 end
+0076 if nargin < 8 || isempty(complexScoring)
+0077     complexScoring = 'min';
+0078 end
+0079 if nargin < 9 || isempty(multipleCellScoring)
+0080     multipleCellScoring = 'max';
+0081 end
+0082 if nargin < 10
+0083     % The first four are for APE, the other ones for staining
+0084     hpaLevelScores.names = {'High' 'Medium' 'Low' 'None' 'Strong' 'Moderate' 'Weak' 'Negative' 'Not detected'};
+0085     hpaLevelScores.scores = [20 15 10 -8 20 15 10 -8 -8];
+0086 end
+0087 
+0088 if isempty(hpaData) && isempty(arrayData)
+0089     EM = 'Must supply hpaData, arrayData or both';
+0090     dispEM(EM);
+0091 end
+0092 if ~ismember(lower(isozymeScoring),{'min','max','median','average'})
+0093     EM = 'Valid options for isozymeScoring are "min", "max", "median", or "average"';
+0094     dispEM(EM);
+0095 end
+0096 if ~ismember(lower(complexScoring),{'min','max','median','average'})
+0097     EM = 'Valid options for complexScoring are "min", "max", "median", or "average"';
+0098     dispEM(EM);
+0099 end
+0100 if ~ismember(lower(multipleCellScoring),{'max','average'})
+0101     EM = 'Valid options for multipleCellScoring are "max" or "average"';
+0102     dispEM(EM);
+0103 end
+0104 
+0105 
+0106 % Throw an error if array data for only one tissue is supplied without
+0107 % specifying threshold values
+0108 if ~isempty(arrayData)
+0109     if numel(unique(arrayData.tissues)) < 2
+0110         if ~isfield(arrayData,'threshold') || isempty(arrayData.threshold)
+0111             EM = 'arrayData must contain measurements for at least two celltypes/tissues since the score is calculated based on the expression level compared to the overall average';
+0112             dispEM(EM);
+0113         end
+0114     end
+0115 end
+0116 
+0117 % Process arrayData.threshold if necessary
+0118 if isfield(arrayData,'threshold') && (numel(arrayData.threshold) == 1)
+0119     % if only a single gene threshold value is provided, then just
+0120     % duplicate this value for all genes.
+0121     arrayData.threshold = arrayData.threshold*ones(size(arrayData.genes));
+0122 end
+0123 
+0124 % This is so the code can ignore which combination of input data is used
+0125 if isempty(arrayData)
+0126     arrayData.genes={};
+0127     arrayData.tissues={};
+0128     arrayData.celltypes={};
+0129     arrayData.levels=[];
+0130     arrayData.threshold=[];
+0131 end
+0132 if isempty(hpaData)
+0133     hpaData.genes={};
+0134     hpaData.tissues={};
+0135     hpaData.celltypes={};
+0136     hpaData.levels={};
+0137     hpaData.types={};
+0138     hpaData.reliabilities={};
+0139     hpaData.gene2Level=[];
+0140     hpaData.gene2Type=[];
+0141     hpaData.gene2Reliability=[];
+0142 end
+0143 
+0144 % Check that the tissue exists
+0145 if ~ismember(upper(tissue),upper(hpaData.tissues)) && ~ismember(upper(tissue),upper(arrayData.tissues))
+0146     EM = 'The tissue name does not match';
+0147     dispEM(EM);
+0148 end
+0149 if any(celltype)
+0150     % Check that both data types has cell type defined if that is to be used
+0151     if ~isfield(hpaData,'celltypes') || ~isfield(arrayData,'celltypes')
+0152         EM = 'Both hpaData and arrayData must contain cell type information if cell type is to be used';
+0153         dispEM(EM);
+0154     end
+0155     if ~ismember(upper(celltype),upper(hpaData.celltypes)) && ~ismember(upper(celltype),upper(arrayData.celltypes))
+0156         EM = 'The cell type name does not match';
+0157         dispEM(EM);
+0158     end
+0159 end
+0160 
+0161 % Some preprocessing of the structures to increase efficiency
+0162 % Remove all tissues that are not the correct one
+0163 J = ~strcmpi(hpaData.tissues,tissue);
+0164 
+0165 %If cell type is supplied, then only keep that cell type
+0166 if any(celltype)
+0167     J = J | ~strcmpi(hpaData.celltypes,celltype);
+0168 end
+0169 
+0170 hpaData.tissues(J)=[];
+0171 if isfield(hpaData,'celltypes')
+0172     hpaData.celltypes(J)=[];
+0173 end
+0174 if isfield(hpaData,'gene2Level')
+0175     hpaData.gene2Level(:,J)=[];
+0176 end
+0177 if isfield(hpaData,'gene2Type')
+0178     hpaData.gene2Type(:,J)=[];
+0179 end
+0180 if isfield(hpaData,'gene2Reliability')
+0181     hpaData.gene2Reliability(:,J)=[];
+0182 end
+0183 
+0184 % Remove all genes from the structures that are not in model or that aren't
+0185 % measured in the tissue
+0186 if ~isempty(hpaData.genes) % This should not be necessary, but the summation is a 0x1 matrix and the other is []
+0187     I = ~ismember(hpaData.genes,model.genes) | sum(hpaData.gene2Level,2) == 0;
+0188 else
+0189     I = [];
+0190 end
+0191 hpaData.genes(I) = [];
+0192 if isfield(hpaData,'gene2Level')
+0193     hpaData.gene2Level(I,:) = [];
+0194 end
+0195 if isfield(hpaData,'gene2Type')
+0196     hpaData.gene2Type(I,:) = [];
+0197 end
+0198 if isfield(hpaData,'gene2Reliability')
+0199     hpaData.gene2Reliability(I,:) = [];
+0200 end
+0201 
+0202 I = strcmpi(arrayData.tissues,tissue);
+0203 % If cell type is supplied, then only keep that cell type
+0204 if any(celltype)
+0205     I = I & strcmpi(arrayData.celltypes,celltype);
+0206 end
+0207 
+0208 % Remove all genes from the structures that are not in model or that aren't
+0209 % measured in the tissue
+0210 J = ~ismember(arrayData.genes,model.genes) | all(isnan(arrayData.levels(:,I)),2);
+0211 arrayData.genes(J) = [];
+0212 arrayData.levels(J,:) = [];
+0213 if isfield(arrayData,'threshold')
+0214     arrayData.threshold(J) = [];
+0215 end
+0216 
+0217 % Calculate the scores for the arrayData. These scores are calculated for
+0218 % each genes from its fold change between the tissue/celltype(s) in question
+0219 % and all other celltypes, or the threshold if supplied. This is a lower
+0220 % quality data than protein abundance, since gene abundance is an indirect
+0221 % estimate of protein level. These scores are therefore only used for genes
+0222 % for which there is no HPA data available. The fold changes are transformed
+0223 % as min(5*log(x),10) for x > 1 and max(5*log(x),-5) for x < 1 in order to
+0224 % have negative scores for lower expressed genes and to scale the scores
+0225 % to have somewhat lower weights than the HPA scores
+0226 tempArrayLevels = arrayData.levels;
+0227 tempArrayLevels(isnan(tempArrayLevels)) = 0;
+0228 if isfield(arrayData,'threshold') && ~isempty(arrayData.threshold)
+0229     % if provided, the user-supplied expression threshold value(s) will be
+0230     % used as the "average" expression level to which each gene is compared
+0231     average = arrayData.threshold;
+0232 else
+0233     average = sum(tempArrayLevels,2)./sum(~isnan(arrayData.levels),2);
+0234 end
+0235 if strcmpi(multipleCellScoring,'max')
+0236     current = max(tempArrayLevels(:,I),[],2);
+0237 else
+0238     current = sum(tempArrayLevels(:,I),2)./sum(~isnan(arrayData.levels(:,I)),2);
+0239 end
+0240 if ~isempty(current)
+0241     aScores = 5*log(current./average);
+0242 else
+0243     aScores = [];
+0244 end
+0245 aScores(aScores > 0) = min(aScores(aScores > 0),10);
+0246 aScores(aScores < 0) = max(aScores(aScores < 0),-5);
+0247 aScores(isnan(aScores)) = -5;  % NaNs occur when gene expression is zero across all tissues
+0248 
+0249 % Map the HPA levels to scores
+0250 [I, J] = ismember(upper(hpaData.levels),upper(hpaLevelScores.names));
+0251 if ~all(I)
+0252     EM = 'There are expression level categories that do not match to hpaLevelScores';
+0253     dispEM(EM);
+0254 end
+0255 [K, L, M] = find(hpaData.gene2Level);
+0256 scores = hpaLevelScores.scores(J);
+0257 if strcmpi(multipleCellScoring,'max')
+0258     hScores = max(sparse(K,L,scores(M),numel(hpaData.genes),numel(hpaData.tissues)),[],2);
+0259 else
+0260     hScores = mean(sparse(K,L,scores(M),numel(hpaData.genes),numel(hpaData.tissues)),2);
+0261 end
+0262 
+0263 % Assign gene scores, prioritizing HPA (protein) data over arrayData (RNA)
+0264 geneScores = nan(numel(model.genes),1);
+0265 hpaScores = -Inf(numel(model.genes),1);
+0266 arrayScores = -Inf(numel(model.genes),1);
+0267 
+0268 [I, J] = ismember(model.genes,arrayData.genes);
+0269 geneScores(I) = aScores(J(I));
+0270 arrayScores(I) = aScores(J(I));
+0271 
+0272 [I, J] = ismember(model.genes,hpaData.genes);
+0273 geneScores(I) = hScores(J(I));
+0274 hpaScores(I) = hScores(J(I));
+0275 
+0276 
+0277 % To speed things up, only need to score each unique grRule once
+0278 [uRules,~,rule_ind] = unique(model.grRules);
+0279 uScores = nan(size(uRules));
+0280 
+0281 % convert logic operators to symbols
+0282 uRules = regexprep(uRules,' and ',' & ');
+0283 uRules = regexprep(uRules,' or ',' | ');
+0284 
+0285 % score based on presence/combination of & and | operators
+0286 for i = 1:numel(uRules)
+0287     if isempty(uRules{i})
+0288         uScores(i) = noGeneScore;
+0289     elseif contains(uRules{i},'&') && contains(uRules{i},'|')
+0290         uScores(i) = scoreComplexRule(uRules{i},model.genes,geneScores,isozymeScoring,complexScoring);
+0291     else
+0292         uScores(i) = scoreSimpleRule(uRules{i},model.genes,geneScores,isozymeScoring,complexScoring);
+0293     end
+0294 end
+0295 
+0296 % NaN reaction scores should be changed to the no-gene score
+0297 uScores(isnan(uScores)) = noGeneScore;
+0298 
+0299 % re-map unique rule scores to model
+0300 rxnScores = uScores(rule_ind);
+0301 
+0302 end
+0303 
+0304 
+0305 
+0306 function rScore = scoreSimpleRule(rule,genes,gScores,isozymeScoring,complexScoring)
+0307 %Score reactions with simple gene rules (those with all ANDs or all ORs).
+0308 
+0309 if ~contains(rule,'&')
+0310     scoreMethod = isozymeScoring;
+0311 elseif ~contains(rule,'|')
+0312     scoreMethod = complexScoring;
+0313 else
+0314     error('This function cannot handle complex gene rules.');
+0315 end
+0316 ruleGenes = unique(regexp(rule,'[^&|\(\) ]+','match'));
+0317 [~,geneInd] = ismember(ruleGenes,genes);
+0318 switch lower(scoreMethod)
+0319     case 'min'
+0320         rScore = min(gScores(geneInd),[],'omitnan');
+0321     case 'max'
+0322         rScore = max(gScores(geneInd),[],'omitnan');
+0323     case 'median'
+0324         rScore = median(gScores(geneInd),'omitnan');
+0325     case 'average'
+0326         rScore = mean(gScores(geneInd),'omitnan');
+0327 end
+0328 
+0329 end
+0330 
+0331 
+0332 
+0333 function rScore = scoreComplexRule(rule,genes,gScores,isozymeScoring,complexScoring)
+0334 %Score reactions with complex gene rules (those with both ANDs or ORs).
+0335 
+0336 % Specify phrases to search for in the grRule. These phrases will find
+0337 % genes grouped by all ANDs (first phrase) or all ORs (second phrase).
+0338 search_phrases = {'\([^&|\(\) ]+( & [^&|\(\) ]+)+\)', '\([^&|\(\) ]+( \| [^&|\(\) ]+)+\)'};
+0339 
+0340 % initialize some variables
+0341 subsets = {};  % subsets are groups of genes grouped by all ANDs or all ORs
+0342 c = 1;  % counter to keep track of the group (subset) number
+0343 r_orig = rule;  % record original rule to determine when it stops changing
+0344 for k = 1:100  % iterate some arbitrarily high number of times
+0345     for j = 1:length(search_phrases)
+0346         new_subset = regexp(rule,search_phrases{j},'match')';  % extract subsets
+0347         if ~isempty(new_subset)
+0348             subsets = [subsets; new_subset];  % append to list of subsets
+0349             subset_nums = arrayfun(@num2str,(c:length(subsets))','UniformOutput',false);  % get group numbers to be assigned to the new subsets, and convert to strings
+0350             rule = regexprep(rule,search_phrases{j},strcat('#',subset_nums,'#'),'once');  % replace the subsets in the expression with their group numbers (enclosed by "#"s)
+0351             c = c + length(new_subset);
+0352         end
+0353     end
+0354     if isequal(rule,r_orig)
+0355         break;  % stop iterating when rule stops changing
+0356     else
+0357         r_orig = rule;
+0358     end
+0359 end
+0360 subsets{end+1} = rule;  % add final state of rule as the last subset
+0361 
+0362 % score each subset and append to gene list and gene scores
+0363 for i = 1:numel(subsets)
+0364     gScores = [gScores; scoreSimpleRule(subsets{i},genes,gScores,isozymeScoring,complexScoring)];
+0365     genes = [genes; {strcat('#',num2str(i),'#')}];
+0366 end
+0367 
+0368 % the final subset score is the overall reaction score
+0369 rScore = gScores(end);
+0370 
+0371 end
+0372
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/alpha.png b/doc/alpha.png new file mode 100644 index 0000000000000000000000000000000000000000..c73de7b05000443a0842f2e915d30dc5efec0dd1 GIT binary patch literal 273 zcmV+s0q*{ZP)z zQ4WJJ2!`q6(c~&{CcFyX%{{O*3+<>*r)K@)L#;sgtx%hY2zp`w01>%5jgw&J!A6Ov z{oxj&d7k&j`4Qtd0>I2H(i=Rwz9Tqxf(W|?ki|=ctL(aA|es#WFKbc?zg4C=hd_}m12PXzTKJB+iB?u XpQ?QQ=I-(g00000NkvXXu0mjf#?^X; literal 0 HcmV?d00001 diff --git a/doc/c++.png b/doc/c++.png new file mode 100644 index 0000000000000000000000000000000000000000..24f56e6293df813f7699555d0fdd0224a33bdac9 GIT binary patch literal 327 zcmeAS@N?(olHy`uVBq!ia0vp^0YJ>p!2~4#tiFE(NUrMq>1fP(BLp1!W^mpLQ_Wwp7rPrm~SUGa2r45^s&cKTi3W&@s7VZD}9S!LiPTl|j(*)-gYW;;XAZ?5N!pnK5hG z+s}VG5+xWO6mIF=yOWvujML^HlXZ+Yu?Qyj=7(iWd!%tXIGN|}`LH!?g3;OMg0piY zXCLcLf98Km#%@Dm=Gw_oB65#C&Ig=Xv$e7}bMZ3wpl2`Gw(%Wrdp_NvM0oStJBj<- zw>I9sUd+GU{%T3g&-nYj{hnNcohMx1C8q6LzjX6wt1Wi%t17>Iemh??{C9K})9DTU VtbG#CZUOzr;OXk;vd$@?2>_TKh~WSL literal 0 HcmV?d00001 diff --git a/doc/c.png b/doc/c.png new file mode 100644 index 0000000000000000000000000000000000000000..c39fbf0e25ee296c5da082458363c45d945e55ac GIT binary patch literal 252 zcmVqm`?`neZy@-MWWPW6I1ran`JUPt^Pp2nEy;5sZWf01@dO#z`=%5EER@AM$q-T7II}~u7He5MzB*^2($9;r8$^sTRx!mG z*Y={Rp11gKlvQkAY5N${nZR6`uQXd6Q{e@Bh2dQhbZ(t1?070Ye8{5GRQ*|k);Is- zyZYFOBO(zQWDhg*y_Wu+*U+*r-a`3&yE1OHzojSttaK8#KYM}z0000 + + + Description of FSEOF + + + + + + + + + +
Home > core > FSEOF.m
+ + + +

FSEOF +

+ +

PURPOSE ^

+
FSEOF
+ +

SYNOPSIS ^

+
function targets=FSEOF(model,biomassRxn,targetRxn,iterations,coefficient,outputFile)
+ +

DESCRIPTION ^

+
 FSEOF
+   Implements the Flux Scanning based on Enforced Objective Flux algorithm.
+
+ Input:
+   model           a model structure
+   biomassRxn      string with reaction ID of the biomass formation or
+                   growth reaction
+   targetRxn       string with reaction ID of target reaction
+   iterations      numeric indicating number of iterations (optional,
+                   default 10)
+   coefficient     numeric indicating ratio of optimal target reaction
+                   flux, must be less than 1 (optional, default 0.9)
+   outputFile      string with output filename (optional, default prints
+                   to command window)
+
+ Output:
+   targets         structure with information for identified targets
+       logical     logical array indicating whether a model reaction was
+                   identified as target by FSEOF
+       slope       numeric array with FSEOF slopes for target reactions
+
+ This function writes an tab-delimited file or prints to command window.
+ If an output has been specified (targets), it will also generate a
+ structure indicating for each model reaction whether it is identified by
+ FSEOF as a target and the slope of the reaction when switching from
+ biomass formation to product formation.
+
+ Usage: targets = FSEOF(model, biomassRxn, targetRxn, iterations,...
+                   coefficient, outputFile)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function targets=FSEOF(model,biomassRxn,targetRxn,iterations,coefficient,outputFile)
+0002 % FSEOF
+0003 %   Implements the Flux Scanning based on Enforced Objective Flux algorithm.
+0004 %
+0005 % Input:
+0006 %   model           a model structure
+0007 %   biomassRxn      string with reaction ID of the biomass formation or
+0008 %                   growth reaction
+0009 %   targetRxn       string with reaction ID of target reaction
+0010 %   iterations      numeric indicating number of iterations (optional,
+0011 %                   default 10)
+0012 %   coefficient     numeric indicating ratio of optimal target reaction
+0013 %                   flux, must be less than 1 (optional, default 0.9)
+0014 %   outputFile      string with output filename (optional, default prints
+0015 %                   to command window)
+0016 %
+0017 % Output:
+0018 %   targets         structure with information for identified targets
+0019 %       logical     logical array indicating whether a model reaction was
+0020 %                   identified as target by FSEOF
+0021 %       slope       numeric array with FSEOF slopes for target reactions
+0022 %
+0023 % This function writes an tab-delimited file or prints to command window.
+0024 % If an output has been specified (targets), it will also generate a
+0025 % structure indicating for each model reaction whether it is identified by
+0026 % FSEOF as a target and the slope of the reaction when switching from
+0027 % biomass formation to product formation.
+0028 %
+0029 % Usage: targets = FSEOF(model, biomassRxn, targetRxn, iterations,...
+0030 %                   coefficient, outputFile)
+0031 
+0032 biomassRxn=char(biomassRxn);
+0033 targetRxn=char(targetRxn);
+0034 
+0035 if nargin<4
+0036     iterations=10;
+0037     coefficient=0.9;
+0038 end
+0039 
+0040 if nargin <5
+0041     coefficient=0.9;
+0042 end
+0043 
+0044 if nargin == 6
+0045     output=1;
+0046 else
+0047     output=0;
+0048 end
+0049 
+0050 %Find out the maximum theoretical yield of target reaction
+0051 model=setParam(model,'obj',targetRxn,1);
+0052 sol=solveLP(model,1);
+0053 targetMax=sol.f*coefficient;   % 90 percent of the theoretical yield
+0054 
+0055 model=setParam(model,'obj',biomassRxn,1);
+0056 
+0057 fseof.results=zeros(length(model.rxns),iterations);
+0058 fseof.target=zeros(length(model.rxns),1);
+0059 rxnDirection=zeros(length(model.rxns),1);
+0060 
+0061 %Enforce objective flux iteratively
+0062 for i=1:iterations
+0063     n=i*targetMax/iterations;
+0064     model=setParam(model,'lb',targetRxn,n);
+0065     
+0066     sol=solveLP(model,1);
+0067     
+0068     fseof.results(:,i)=sol.x;
+0069     
+0070     %Loop through all fluxes and identify the ones that increased upon the
+0071     %enforced objective flux
+0072     for j=1:length(fseof.results)
+0073         if fseof.results(j,1) > 0   %Check the positive fluxes
+0074             
+0075             if i == 1   %The initial round
+0076                 rxnDirection(j,1)=1;
+0077                 fseof.target(j,1)=1;
+0078             else
+0079                 
+0080                 if (fseof.results(j,i) > fseof.results(j,i-1)) & fseof.target(j,1)
+0081                     fseof.target(j,1)=1;
+0082                 else
+0083                     fseof.target(j,1)=0;
+0084                 end
+0085             end
+0086             
+0087         elseif fseof.results(j,1) < 0 %Check the negative fluxes
+0088             
+0089             if i == 1   %The initial round
+0090                 rxnDirection(j,1)=-1;
+0091                 fseof.target(j,1)=1;
+0092             else
+0093                 if (fseof.results(j,i) < fseof.results(j,i-1)) & fseof.target(j,1)
+0094                     fseof.target(j,1)=1;
+0095                 else
+0096                     fseof.target(j,1)=0;
+0097                 end
+0098             end
+0099             
+0100         end
+0101         
+0102     end
+0103 end
+0104 
+0105 %Generating output
+0106 formatSpec='%s\t%s\t%s\t%s\t%s\t%s\t%s\n';
+0107 if output == 1    %Output to a file
+0108     outputFile=char(outputFile);
+0109     fid=fopen(outputFile,'w');
+0110     fprintf(fid,formatSpec,'Slope','rowID','Enzyme ID','Enzyme Name','Subsystems','Direction','Gr Rule');
+0111 else              %Output to screen
+0112     fprintf(formatSpec,'Slope','rowID','Enzyme ID','Enzyme Name','Subsystems','Direction','Gr Rule');
+0113 end
+0114 
+0115 for num=1:length(fseof.target)
+0116     if fseof.target(num,1) == 1
+0117         A0=num2str(abs(fseof.results(num,iterations)-fseof.results(num,1))/abs(targetMax-targetMax/iterations)); %Slope calculation
+0118         A1=num2str(num);                                  %row ID
+0119         A2=char(model.rxns(num));                         %enzyme ID
+0120         A3=char(model.rxnNames(num));                     %enzyme Name
+0121         if isfield(model,'subSystems') && ~isempty(model.subSystems{num});
+0122             if ~any(cellfun(@(x) iscell(x), model.subSystems));
+0123                 subSys = cellfun(@(x) {x}, model.subSystems, 'uni', 0);
+0124             else
+0125                 subSys = model.subSystems;
+0126             end
+0127             A4=char(strjoin(subSys{num},';'));                   %Subsystems
+0128         else
+0129             A4='';
+0130         end
+0131         A5=num2str(model.rev(num)*rxnDirection(num,1));   %reaction Dirction
+0132         A6=char(model.grRules(num));                      %Gr Rule
+0133         if output == 1    %Output to a file
+0134             fprintf(fid,formatSpec,A0,A1,A2,A3,A4,A5,A6);
+0135         else              %Output screen
+0136             fprintf(formatSpec,A0,A1,A2,A3,A4,A5,A6);
+0137         end
+0138     end
+0139 end
+0140 
+0141 if output == 1    %Output to a file
+0142     fclose(fid);
+0143 end
+0144 
+0145 if nargout == 1
+0146     targets.logical=logical(fseof.target);
+0147     targets.slope=abs(fseof.results(:,iterations)-fseof.results(:,1))/abs(targetMax-targetMax/iterations); %Slope calculation
+0148 end
+0149 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/addExchangeRxns.html b/doc/core/addExchangeRxns.html new file mode 100644 index 000000000..c1bdf99fa --- /dev/null +++ b/doc/core/addExchangeRxns.html @@ -0,0 +1,166 @@ + + + + Description of addExchangeRxns + + + + + + + + + +
Home > core > addExchangeRxns.m
+ + + +

addExchangeRxns +

+ +

PURPOSE ^

+
addExchangeRxns
+ +

SYNOPSIS ^

+
function [model, addedRxns]=addExchangeRxns(model,reactionType,mets)
+ +

DESCRIPTION ^

+
 addExchangeRxns
+   Adds exchange reactions for some metabolites
+
+   model           a model structure
+   reactionType    the type of reactions to add
+                   'in'    input reactions
+                   'out'   output reactions
+                   'both'  reversible input/output reactions. Positive
+                   direction corresponds to output
+   mets            either a cell array of metabolite IDs, a logical vector
+                   with the same number of elements as metabolites in the model,
+                   or a vector of indexes to add for (optional, default model.mets)
+
+   model           updated model structure
+   addedRxns       ids of the added reactions
+
+   This is a faster version than addRxns when adding exchange reactions.
+   New reactions are named "metName exchange (OUT/IN/BOTH)" while reaction
+   ids are formatted as "EXC_OUT/IN/BOTH_METID".
+
+ Usage: [model, addedRxns]=addExchangeRxns(model,reactionType,mets)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function [model, addedRxns]=addExchangeRxns(model,reactionType,mets)
+0002 % addExchangeRxns
+0003 %   Adds exchange reactions for some metabolites
+0004 %
+0005 %   model           a model structure
+0006 %   reactionType    the type of reactions to add
+0007 %                   'in'    input reactions
+0008 %                   'out'   output reactions
+0009 %                   'both'  reversible input/output reactions. Positive
+0010 %                   direction corresponds to output
+0011 %   mets            either a cell array of metabolite IDs, a logical vector
+0012 %                   with the same number of elements as metabolites in the model,
+0013 %                   or a vector of indexes to add for (optional, default model.mets)
+0014 %
+0015 %   model           updated model structure
+0016 %   addedRxns       ids of the added reactions
+0017 %
+0018 %   This is a faster version than addRxns when adding exchange reactions.
+0019 %   New reactions are named "metName exchange (OUT/IN/BOTH)" while reaction
+0020 %   ids are formatted as "EXC_OUT/IN/BOTH_METID".
+0021 %
+0022 % Usage: [model, addedRxns]=addExchangeRxns(model,reactionType,mets)
+0023 
+0024 if nargin<3
+0025     mets=model.mets;
+0026 elseif ~islogical(mets) && ~isnumeric(mets)
+0027     mets=convertCharArray(mets);
+0028 end
+0029 J=getIndexes(model,mets,'mets',false);
+0030 mets=model.mets(J);
+0031 
+0032 reactionType=char(upper(reactionType));
+0033 
+0034 %Production is positive for OUT and BOTH
+0035 if strcmp(reactionType,'IN')
+0036     I=speye(numel(model.mets));
+0037 else
+0038     I=speye(numel(model.mets))*-1;
+0039 end
+0040 I=I(:,J);
+0041 
+0042 %Add an I matrix which corresponds to production of all metabolites
+0043 model.S=[model.S I];
+0044 if strcmp(reactionType,'BOTH')
+0045     model.lb=[model.lb;ones(numel(J),1)*-1000];
+0046     model.rev=[model.rev;ones(numel(J),1)];
+0047 else
+0048     model.lb=[model.lb;zeros(numel(J),1)];
+0049     model.rev=[model.rev;zeros(numel(J),1)];
+0050 end
+0051 model.ub=[model.ub;ones(numel(J),1)*1000];
+0052 model.c=[model.c;zeros(numel(J),1)];
+0053 
+0054 filler=cell(numel(J),1);
+0055 filler(:)={''};
+0056 addedRxns=strcat('EXC_',reactionType,'_',mets);
+0057 addedRxnNames=strcat(model.metNames(J),' exchange (',reactionType,')');
+0058 model.rxns=[model.rxns;addedRxns];
+0059 model.rxnNames=[model.rxnNames;addedRxnNames];
+0060 
+0061 if isfield(model,'eccodes')
+0062     model.eccodes=[model.eccodes;filler];
+0063 end
+0064 if isfield(model,'subSystems')
+0065     fillerSub = filler;
+0066     if any(cellfun(@(x) iscell(x), model.subSystems))
+0067         fillerSub(:)={{''}};
+0068     end
+0069     model.subSystems=[model.subSystems;fillerSub];
+0070 end
+0071 if isfield(model,'grRules')
+0072     model.grRules=[model.grRules;filler];
+0073 end
+0074 if isfield(model,'rxnFrom')
+0075     model.rxnFrom=[model.rxnFrom;filler];
+0076 end
+0077 if isfield(model,'rxnMiriams')
+0078     model.rxnMiriams=[model.rxnMiriams;filler];
+0079 end
+0080 if isfield(model,'rxnGeneMat')
+0081     model.rxnGeneMat=[model.rxnGeneMat;sparse(numel(J),numel(model.genes))];
+0082 end
+0083 if isfield(model,'rxnComps')
+0084     model.rxnComps=[model.rxnComps;ones(numel(J),1)];
+0085     fprintf('NOTE: The exchange reactions are assigned to the first compartment\n');
+0086 end
+0087 if isfield(model,'rxnNotes')
+0088     model.rxnNotes=[model.rxnNotes;filler];
+0089 end
+0090 if isfield(model,'rxnReferences')
+0091     model.rxnReferences=[model.rxnReferences;filler];
+0092 end
+0093 if isfield(model,'rxnConfidenceScores')
+0094     model.rxnConfidenceScores=[model.rxnConfidenceScores;NaN(numel(J),1)];
+0095 end
+0096 if isfield(model,'rxnDeltaG')
+0097     model.rxnDeltaG=[model.rxnDeltaG;NaN(numel(J),1)];
+0098 end
+0099 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/addGenesRaven.html b/doc/core/addGenesRaven.html new file mode 100644 index 000000000..39d26818d --- /dev/null +++ b/doc/core/addGenesRaven.html @@ -0,0 +1,221 @@ + + + + Description of addGenesRaven + + + + + + + + + +
Home > core > addGenesRaven.m
+ + + +

addGenesRaven +

+ +

PURPOSE ^

+
addGenesRaven
+ +

SYNOPSIS ^

+
function newModel=addGenesRaven(model,genesToAdd)
+ +

DESCRIPTION ^

+
 addGenesRaven
+   Adds genes to a model
+
+   model        a model structure
+   genesToAdd   the genes genesToAdd can have the following fields:
+                genes          cell array with unique strings that
+                               identifies each gene. Only character which are
+                               allowed in SBML ids are allowed (mainly a-z,
+                               0-9 and '_'). However, there is no check
+                               for this performed, as it only matters if
+                               the model should be exported to SBML
+                geneShortNames cell array of gene abbreviations (optional,
+                               default '')
+                geneMiriams    cell array with MIRIAM structures (optional,
+                               default [])
+                proteins   cell array of protein names associated to
+                               each gene (optional, default '')
+
+   newModel     an updated model structure
+
+   NOTE: This function does not make extensive checks about MIRIAM formats,
+   forbidden characters or such.
+
+ Usage: newModel=addGenesRaven(model,genesToAdd)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function newModel=addGenesRaven(model,genesToAdd)
+0002 % addGenesRaven
+0003 %   Adds genes to a model
+0004 %
+0005 %   model        a model structure
+0006 %   genesToAdd   the genes genesToAdd can have the following fields:
+0007 %                genes          cell array with unique strings that
+0008 %                               identifies each gene. Only character which are
+0009 %                               allowed in SBML ids are allowed (mainly a-z,
+0010 %                               0-9 and '_'). However, there is no check
+0011 %                               for this performed, as it only matters if
+0012 %                               the model should be exported to SBML
+0013 %                geneShortNames cell array of gene abbreviations (optional,
+0014 %                               default '')
+0015 %                geneMiriams    cell array with MIRIAM structures (optional,
+0016 %                               default [])
+0017 %                proteins   cell array of protein names associated to
+0018 %                               each gene (optional, default '')
+0019 %
+0020 %   newModel     an updated model structure
+0021 %
+0022 %   NOTE: This function does not make extensive checks about MIRIAM formats,
+0023 %   forbidden characters or such.
+0024 %
+0025 % Usage: newModel=addGenesRaven(model,genesToAdd)
+0026 
+0027 newModel=model;
+0028 
+0029 if isempty(genesToAdd)
+0030     return;
+0031 end
+0032 
+0033 %Check some stuff regarding the required fields
+0034 if ~isfield(genesToAdd,'genes')
+0035     EM='genes is a required field in genesToAdd';
+0036     dispEM(EM);
+0037 else
+0038     genesToAdd.genes=convertCharArray(genesToAdd.genes);
+0039 end
+0040 
+0041 %Number of genes
+0042 nGenes=numel(genesToAdd.genes);
+0043 nOldGenes=numel(model.genes);
+0044 filler=cell(nGenes,1);
+0045 filler(:)={''};
+0046 largeFiller=cell(nOldGenes,1);
+0047 largeFiller(:)={''};
+0048 
+0049 %Check that no gene ids are already present in the model
+0050 I=ismember(genesToAdd.genes,model.genes);
+0051 if all(I)
+0052     warning('All genes in genesToAdd.genes are already present in model.genes');
+0053     return
+0054 elseif any(I)
+0055     existingGenes=strjoin(genesToAdd.genes(I), ', ');
+0056     warning(['The following genes are already present in model.genes and will therefore not be added: ', existingGenes])
+0057     genesToAdd.genes(I)=[];
+0058     if isfield(genesToAdd,'geneShortNames')
+0059         genesToAdd.geneShortNames(I)=[];
+0060     end
+0061     if isfield(genesToAdd,'proteins')
+0062         genesToAdd.proteins(I)=[];
+0063     end
+0064     if isfield(genesToAdd,'geneMiriams')
+0065         genesToAdd.geneMiriams(I)=[];
+0066     end
+0067 else
+0068     newModel.genes=[newModel.genes;genesToAdd.genes(:)];
+0069 end
+0070 
+0071 %Some more checks and if they pass then add each field to the structure
+0072 if isfield(genesToAdd,'geneShortNames')
+0073     genesToAdd.geneShortNames=convertCharArray(genesToAdd.geneShortNames);
+0074     if numel(genesToAdd.geneShortNames)~=nGenes
+0075         EM='genesToAdd.geneShortNames must have the same number of elements as genesToAdd.genes';
+0076         dispEM(EM);
+0077     end
+0078     %Add empty field if it doesn't exist
+0079     if ~isfield(newModel,'geneShortNames')
+0080         newModel.geneShortNames=largeFiller;
+0081     end
+0082     newModel.geneShortNames=[newModel.geneShortNames;genesToAdd.geneShortNames(:)];
+0083 else
+0084     %Add empty strings if structure is in model
+0085     if isfield(newModel,'geneShortNames')
+0086         newModel.geneShortNames=[newModel.geneShortNames;filler];
+0087     end
+0088 end
+0089 if isfield(genesToAdd,'proteins')
+0090     genesToAdd.proteins=convertCharArray(genesToAdd.proteins);
+0091     if numel(genesToAdd.proteins)~=nGenes
+0092         EM='genesToAdd.proteins must have the same number of elements as genesToAdd.genes';
+0093         dispEM(EM);
+0094     end
+0095     %Add empty field if it doesn't exist
+0096     if ~isfield(newModel,'proteins')
+0097         newModel.proteins=largeFiller;
+0098     end
+0099     newModel.proteins=[newModel.proteins;genesToAdd.proteins(:)];
+0100 else
+0101     %Add empty strings if structure is in model
+0102     if isfield(newModel,'proteins')
+0103         newModel.proteins=[newModel.proteins;filler];
+0104     end
+0105 end
+0106 
+0107 
+0108 %Don't check the type of geneMiriams
+0109 if isfield(genesToAdd,'geneMiriams')
+0110     if numel(genesToAdd.geneMiriams)~=nGenes
+0111         EM='genesToAdd.geneMiriams must have the same number of elements as genesToAdd.genes';
+0112         dispEM(EM);
+0113     end
+0114     %Add empty field if it doesn't exist
+0115     if ~isfield(newModel,'geneMiriams')
+0116         newModel.geneMiriams=cell(nOldGenes,1);
+0117     end
+0118     newModel.geneMiriams=[newModel.geneMiriams;genesToAdd.geneMiriams(:)];
+0119 else
+0120     if isfield(newModel,'geneMiriams')
+0121         newModel.geneMiriams=[newModel.geneMiriams;cell(nGenes,1)];
+0122     end
+0123 end
+0124 
+0125 if isfield(genesToAdd,'geneComps')
+0126     if numel(genesToAdd.geneComps)~=nGenes
+0127         EM='genesToAdd.geneComps must have the same number of elements as genesToAdd.genes';
+0128         dispEM(EM);
+0129     end
+0130     %Add empty field if it doesn't exist
+0131     if ~isfield(newModel,'geneComps')
+0132         newModel.geneComps=ones(nOldGenes,1);
+0133         EM='Adding genes with compartment information to a model without such information. All existing genes will be assigned to the first compartment';
+0134         dispEM(EM,false);
+0135     end
+0136     newModel.geneComps=[newModel.geneComps;genesToAdd.geneComps(:)];
+0137 else
+0138     if isfield(newModel,'geneComps')
+0139         newModel.geneComps=[newModel.geneComps;ones(nGenes,1)];
+0140         fprintf('NOTE: The added genes will be assigned to the first compartment\n');
+0141     end
+0142 end
+0143 
+0144 if isfield(newModel,'geneFrom')
+0145     newModel.geneFrom=[newModel.geneFrom;filler];
+0146 end
+0147 
+0148 if isfield(newModel,'rxnGeneMat')
+0149     newModel.rxnGeneMat=[newModel.rxnGeneMat,zeros(length(newModel.rxns),nGenes)];
+0150 end
+0151 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/addMets.html b/doc/core/addMets.html new file mode 100644 index 000000000..2681ccee4 --- /dev/null +++ b/doc/core/addMets.html @@ -0,0 +1,472 @@ + + + + Description of addMets + + + + + + + + + +
Home > core > addMets.m
+ + + +

addMets +

+ +

PURPOSE ^

+
addMets
+ +

SYNOPSIS ^

+
function newModel=addMets(model,metsToAdd,copyInfo,prefix)
+ +

DESCRIPTION ^

+
 addMets
+   Adds metabolites to a model
+
+ Input:
+   model       a model structure
+   metsToAdd   the metabolite structure can have the following fields:
+       mets            cell array with unique strings that identifies each
+                       metabolite (optional, default IDs of new
+                       metabolites are numbered with the prefix defined
+                       below)
+       metNames        cell array with the names of each metabolite
+       compartments    cell array with the compartment of each
+                       metabolite. Should match model.comps. If this is a
+                       string rather than a cell array it is assumed that
+                       all mets are in that compartment
+       b               Nx1 or Nx2 matrix with equality constraints for
+                       each metabolite (optional, default 0)
+       unconstrained   vector describing if each metabolite is an exchange
+                       metabolite (1) or not (0) (optional, default 0)
+       inchis          cell array with InChI strings (optional, default '')
+       metSmiles       cell array with SMILES strings (optional, default '')
+       metFormulas     cell array with the formulas  (optional, default '')
+       metMiriams      cell array with MIRIAM structures (optional, default [])
+       metCharges      metabolite charge (optional, default NaN)
+       metDeltaG       Gibbs free energy of formation at biochemical
+                       standard condition in kJ/mole (optional, default NaN)
+       metNotes        cell array with metabolite notes as strings
+                       (optional, default '')
+   copyInfo    when adding metabolites to a compartment where it
+               previously did not exist, the function will copy any
+               available annotation from the metabolite in another
+               compartment (optional, default true)
+   prefix      when metsToAdd.mets is not specified, new metabolite IDs
+               are generated with the prefix specified here. If IDs with
+               the prefix are already used in the model then the
+               numbering will start from the highest existing integer+1
+               (optional, default 'm_')
+
+ Output:
+   newModel     an updated model structure
+
+ This function does not make extensive checks about MIRIAM formats,
+ forbidden characters or such.
+
+ If multiple metabolites are added at once, the metMiriams cell array
+ should be defined as (example with ChEBI and KEGG):
+
+ metsToAdd.metMiriams{1} = struct('name',{{'chebi';'kegg.compound'}},...
+     'value',{{'CHEBI:18072';'C11821'}});
+ metsToAdd.metMiriams{2} = struct('name',{{'chebi';'kegg.compound'}},...
+     'value',{{'CHEBI:31132';'C12248'}});
+
+ Usage: newModel = addMets(model, metsToAdd, copyInfo, prefix)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function newModel=addMets(model,metsToAdd,copyInfo,prefix)
+0002 % addMets
+0003 %   Adds metabolites to a model
+0004 %
+0005 % Input:
+0006 %   model       a model structure
+0007 %   metsToAdd   the metabolite structure can have the following fields:
+0008 %       mets            cell array with unique strings that identifies each
+0009 %                       metabolite (optional, default IDs of new
+0010 %                       metabolites are numbered with the prefix defined
+0011 %                       below)
+0012 %       metNames        cell array with the names of each metabolite
+0013 %       compartments    cell array with the compartment of each
+0014 %                       metabolite. Should match model.comps. If this is a
+0015 %                       string rather than a cell array it is assumed that
+0016 %                       all mets are in that compartment
+0017 %       b               Nx1 or Nx2 matrix with equality constraints for
+0018 %                       each metabolite (optional, default 0)
+0019 %       unconstrained   vector describing if each metabolite is an exchange
+0020 %                       metabolite (1) or not (0) (optional, default 0)
+0021 %       inchis          cell array with InChI strings (optional, default '')
+0022 %       metSmiles       cell array with SMILES strings (optional, default '')
+0023 %       metFormulas     cell array with the formulas  (optional, default '')
+0024 %       metMiriams      cell array with MIRIAM structures (optional, default [])
+0025 %       metCharges      metabolite charge (optional, default NaN)
+0026 %       metDeltaG       Gibbs free energy of formation at biochemical
+0027 %                       standard condition in kJ/mole (optional, default NaN)
+0028 %       metNotes        cell array with metabolite notes as strings
+0029 %                       (optional, default '')
+0030 %   copyInfo    when adding metabolites to a compartment where it
+0031 %               previously did not exist, the function will copy any
+0032 %               available annotation from the metabolite in another
+0033 %               compartment (optional, default true)
+0034 %   prefix      when metsToAdd.mets is not specified, new metabolite IDs
+0035 %               are generated with the prefix specified here. If IDs with
+0036 %               the prefix are already used in the model then the
+0037 %               numbering will start from the highest existing integer+1
+0038 %               (optional, default 'm_')
+0039 %
+0040 % Output:
+0041 %   newModel     an updated model structure
+0042 %
+0043 % This function does not make extensive checks about MIRIAM formats,
+0044 % forbidden characters or such.
+0045 %
+0046 % If multiple metabolites are added at once, the metMiriams cell array
+0047 % should be defined as (example with ChEBI and KEGG):
+0048 %
+0049 % metsToAdd.metMiriams{1} = struct('name',{{'chebi';'kegg.compound'}},...
+0050 %     'value',{{'CHEBI:18072';'C11821'}});
+0051 % metsToAdd.metMiriams{2} = struct('name',{{'chebi';'kegg.compound'}},...
+0052 %     'value',{{'CHEBI:31132';'C12248'}});
+0053 %
+0054 % Usage: newModel = addMets(model, metsToAdd, copyInfo, prefix)
+0055 
+0056 if nargin<3
+0057     copyInfo=true;
+0058 end
+0059 if nargin<4
+0060     prefix='m_';
+0061 else
+0062     prefix=char(prefix);
+0063 end
+0064 
+0065 newModel=model;
+0066 
+0067 if isempty(metsToAdd)
+0068     return;
+0069 end
+0070 
+0071 %Check some stuff regarding the required fields
+0072 if ~isfield(metsToAdd,'mets')
+0073     metsToAdd.metNames=convertCharArray(metsToAdd.metNames);
+0074     metsToAdd.mets=generateNewIds(newModel,'mets',prefix,numel(metsToAdd.metNames));
+0075 else
+0076     metsToAdd.mets=convertCharArray(metsToAdd.mets);
+0077 end
+0078 if ~isfield(metsToAdd,'metNames')
+0079     metsToAdd.metNames=metsToAdd.mets;
+0080 else
+0081     metsToAdd.metNames=convertCharArray(metsToAdd.metNames);
+0082 end
+0083 if ~isfield(metsToAdd,'compartments')
+0084     EM='compartments is a required field in metsToAdd';
+0085     dispEM(EM);
+0086 else
+0087     metsToAdd.compartments=convertCharArray(metsToAdd.compartments);
+0088     %If only one compartment is given, assume it is for all metabolites
+0089     if numel(metsToAdd.compartments)==1 && numel(metsToAdd.mets)>1
+0090         temp=cell(numel(metsToAdd.mets),1);
+0091         temp(:)=metsToAdd.compartments;
+0092         metsToAdd.compartments=temp;
+0093     end
+0094 end
+0095 
+0096 %Number of metabolites
+0097 nMets=numel(metsToAdd.mets);
+0098 nOldMets=numel(model.mets);
+0099 filler=cell(nMets,1);
+0100 filler(:)={''};
+0101 largeFiller=cell(nOldMets,1);
+0102 largeFiller(:)={''};
+0103 
+0104 %Check that no metabolite ids are already present in the model
+0105 I=ismember(metsToAdd.mets,model.mets);
+0106 if any(I)
+0107     error('One or more elements in metsToAdd.mets are already present in model.mets: %s',...
+0108         strjoin(metsToAdd.mets(I),', '));
+0109 else
+0110     newModel.mets=[newModel.mets;metsToAdd.mets(:)];
+0111 end
+0112 
+0113 %Check that all the compartments could be found
+0114 [I, compMap]=ismember(metsToAdd.compartments,model.comps);
+0115 if ~all(I)
+0116     EM='metsToAdd.compartments must match model.comps';
+0117     dispEM(EM);
+0118 end
+0119 
+0120 %Check that the metabolite names aren't present in the same compartment.
+0121 %Not the neatest way maybe..
+0122 t1=strcat(metsToAdd.metNames(:),'***',metsToAdd.compartments(:));
+0123 t2=strcat(model.metNames,'***',model.comps(model.metComps));
+0124 if any(ismember(t1,t2))
+0125     EM='One or more elements in metsToAdd.metNames already exist in the same compartments as the one it is being added to';
+0126     dispEM(EM);
+0127 end
+0128 
+0129 %Some more checks and if they pass then add each field to the structure
+0130 if numel(metsToAdd.metNames)~=nMets
+0131     EM='metsToAdd.metNames must have the same number of elements as metsToAdd.mets';
+0132     dispEM(EM);
+0133 else
+0134     newModel.metNames=[newModel.metNames;metsToAdd.metNames(:)];
+0135 end
+0136 
+0137 if numel(compMap)~=nMets
+0138     EM='metsToAdd.compartments must have the same number of elements as metsToAdd.mets';
+0139     dispEM(EM);
+0140 else
+0141     newModel.metComps=[newModel.metComps;compMap(:)];
+0142 end
+0143 
+0144 if isfield(metsToAdd,'b')
+0145     if size(metsToAdd.b,1)~=nMets
+0146         EM='metsToAdd.b must have the same number of elements as metsToAdd.mets';
+0147         dispEM(EM);
+0148     else
+0149         %Add empty field if it doesn't exist
+0150         if ~isfield(newModel,'b')
+0151             newModel.b=zeros(nOldMets,1);
+0152         end
+0153         
+0154         %If the original is only one vector
+0155         if size(metsToAdd.b,2)>size(newModel.b,2)
+0156             newModel.b=[newModel.b newModel.b];
+0157         end
+0158         %Add the new ones
+0159         newModel.b=[newModel.b;metsToAdd.b];
+0160     end
+0161 else
+0162     if isfield(newModel,'b')
+0163         %Add the default
+0164         newModel.b=[newModel.b;zeros(nMets,size(newModel.b,2))];
+0165     end
+0166 end
+0167 
+0168 if isfield(metsToAdd,'unconstrained')
+0169     if numel(metsToAdd.unconstrained)~=nMets
+0170         EM='metsToAdd.unconstrained must have the same number of elements as metsToAdd.mets';
+0171         dispEM(EM);
+0172     else
+0173         %Add empty field if it doesn't exist
+0174         if ~isfield(newModel,'unconstrained')
+0175             newModel.unconstrained=zeros(nOldMets,1);
+0176         end
+0177         
+0178         %Add the new ones
+0179         newModel.unconstrained=[newModel.unconstrained;metsToAdd.unconstrained(:)];
+0180     end
+0181 else
+0182     if isfield(newModel,'unconstrained')
+0183         %Add the default
+0184         newModel.unconstrained=[newModel.unconstrained;zeros(nMets,1)];
+0185     end
+0186 end
+0187 
+0188 if isfield(metsToAdd,'inchis')
+0189     metsToAdd.inchis=convertCharArray(metsToAdd.inchis);
+0190     if numel(metsToAdd.inchis)~=nMets
+0191         EM='metsToAdd.inchis must have the same number of elements as metsToAdd.mets';
+0192         dispEM(EM);
+0193     end
+0194     %Add empty field if it doesn't exist
+0195     if ~isfield(newModel,'inchis')
+0196         newModel.inchis=largeFiller;
+0197     end
+0198     newModel.inchis=[newModel.inchis;metsToAdd.inchis(:)];
+0199 else
+0200     %Add empty strings if structure is in model
+0201     if isfield(newModel,'inchis')
+0202         newModel.inchis=[newModel.inchis;filler];
+0203     end
+0204 end
+0205 
+0206 
+0207 if isfield(metsToAdd,'metSmiles')
+0208     metsToAdd.metSmiles=convertCharArray(metsToAdd.metSmiles);
+0209     if numel(metsToAdd.metSmiles)~=nMets
+0210         EM='metsToAdd.metSmiles must have the same number of elements as metsToAdd.mets';
+0211         dispEM(EM);
+0212     end
+0213     %Add empty field if it doesn't exist
+0214     if ~isfield(newModel,'metSmiles')
+0215         newModel.metSmiles=largeFiller;
+0216     end
+0217     newModel.metSmiles=[newModel.metSmiles;metsToAdd.metSmiles(:)];
+0218 else
+0219     %Add empty strings if structure is in model
+0220     if isfield(newModel,'metSmiles')
+0221         newModel.metSmiles=[newModel.metSmiles;filler];
+0222     end
+0223 end
+0224 
+0225 if isfield(metsToAdd,'metFormulas')
+0226     metsToAdd.metFormulas=convertCharArray(metsToAdd.metFormulas);
+0227     if numel(metsToAdd.metFormulas)~=nMets
+0228         EM='metsToAdd.metFormulas must have the same number of elements as metsToAdd.mets';
+0229         dispEM(EM);
+0230     end
+0231     %Add empty field if it doesn't exist
+0232     if ~isfield(newModel,'metFormulas')
+0233         newModel.metFormulas=largeFiller;
+0234     end
+0235     newModel.metFormulas=[newModel.metFormulas;metsToAdd.metFormulas(:)];
+0236 else
+0237     %Add default
+0238     if isfield(newModel,'metFormulas')
+0239         newModel.metFormulas=[newModel.metFormulas;filler];
+0240     end
+0241 end
+0242 
+0243 if isfield(metsToAdd,'metCharges')
+0244     if numel(metsToAdd.metCharges)~=nMets
+0245         EM='metsToAdd.metCharges must have the same number of elements as metsToAdd.mets';
+0246         dispEM(EM);
+0247     end
+0248     if ~isnumeric(metsToAdd.metCharges)
+0249         EM='metsToAdd.metCharges must be of type "double"';
+0250         dispEM(EM);
+0251     end
+0252     if ~isfield(newModel,'metCharges')
+0253         newModel.metCharges=NaN(numel(largeFiller),1);
+0254     end
+0255     newModel.metCharges=[newModel.metCharges;metsToAdd.metCharges(:)];
+0256 else
+0257     %Add default
+0258     if isfield(newModel,'metCharges')
+0259         newModel.metCharges=[newModel.metCharges;NaN(numel(filler),1)];
+0260     end
+0261 end
+0262 
+0263 if isfield(metsToAdd,'metDeltaG')
+0264     if numel(metsToAdd.metDeltaG)~=nMets
+0265         EM='metsToAdd.metDeltaG must have the same number of elements as metsToAdd.mets';
+0266         dispEM(EM);
+0267     end
+0268     if ~isnumeric(metsToAdd.metDeltaG)
+0269         EM='metsToAdd.metDeltaG must be of type "double"';
+0270         dispEM(EM);
+0271     end
+0272     if ~isfield(newModel,'metDeltaG')
+0273         newModel.metDeltaG=NaN(numel(largeFiller),1);
+0274     end
+0275     newModel.metDeltaG=[newModel.metDeltaG;metsToAdd.metDeltaG(:)];
+0276 else
+0277     %Add default
+0278     if isfield(newModel,'metDeltaG')
+0279         newModel.metDeltaG=[newModel.metDeltaG;NaN(numel(filler),1)];
+0280     end
+0281 end
+0282 
+0283 
+0284 if isfield(metsToAdd,'metNotes')
+0285     metsToAdd.metNotes=convertCharArray(metsToAdd.metNotes);
+0286     if numel(metsToAdd.metNotes)==1 && numel(metsToAdd.mets)>1
+0287         temp=cell(numel(metsToAdd.mets),1);
+0288         temp(:)=metsToAdd.metNotes;
+0289         metsToAdd.metNotes=temp;
+0290     end
+0291     if numel(metsToAdd.metNotes)~=nMets
+0292         EM='metsToAdd.metNotes must have the same number of elements as metsToAdd.mets';
+0293         dispEM(EM);
+0294     end
+0295     %Add empty field if it doesn't exist
+0296     if ~isfield(newModel,'metNotes')
+0297         newModel.metNotes=largeFiller;
+0298     end
+0299     newModel.metNotes=[newModel.metNotes;metsToAdd.metNotes(:)];
+0300 else
+0301     %Add empty strings if structure is in model
+0302     if isfield(newModel,'metNotes')
+0303         newModel.metNotes=[newModel.metNotes;filler];
+0304     end
+0305 end
+0306 
+0307 %Don't check the type of metMiriams
+0308 if isfield(metsToAdd,'metMiriams')
+0309     if numel(metsToAdd.metMiriams)==1 && numel(metsToAdd.mets)>1
+0310         temp=cell(numel(metsToAdd.mets),1);
+0311         temp(:)={metsToAdd.metMiriams};
+0312         metsToAdd.metMiriams=temp;
+0313     end
+0314     if numel(metsToAdd.metMiriams)~=nMets
+0315         EM='metsToAdd.metMiriams must have the same number of elements as metsToAdd.mets';
+0316         dispEM(EM);
+0317     end
+0318     %Add empty field if it doesn't exist
+0319     if ~isfield(newModel,'metMiriams')
+0320         newModel.metMiriams=cell(nOldMets,1);
+0321     end
+0322     newModel.metMiriams=[newModel.metMiriams;metsToAdd.metMiriams(:)];
+0323 else
+0324     if isfield(newModel,'metMiriams')
+0325         newModel.metMiriams=[newModel.metMiriams;cell(nMets,1)];
+0326     end
+0327 end
+0328 
+0329 if isfield(newModel,'metFrom')
+0330     newModel.metFrom=[newModel.metFrom;filler];
+0331 end
+0332 
+0333 %Expand the S matrix
+0334 newModel.S=[newModel.S;sparse(nMets,size(newModel.S,2))];
+0335 
+0336 if copyInfo==true
+0337     [I, J]=ismember(metsToAdd.metNames,model.metNames);
+0338     J=J(I);
+0339     %I is the indexes of the new metabolites for which a metabolite with
+0340     %the same name existed
+0341     I=find(I)+nOldMets;
+0342     %Go through each of the added mets and copy annotation if it doesn't
+0343     %exist
+0344     for i=1:numel(I)
+0345         if isfield(newModel,'inchis')
+0346             if isempty(newModel.inchis{I(i)})
+0347                 newModel.inchis(I(i))=newModel.inchis(J(i));
+0348             end
+0349         end
+0350         if isfield(newModel,'metSmiles')
+0351             if isempty(newModel.metSmiles{I(i)})
+0352                 newModel.metSmiles(I(i))=newModel.metSmiles(J(i));
+0353             end
+0354         end        
+0355         if isfield(newModel,'metFormulas')
+0356             if isempty(newModel.metFormulas{I(i)})
+0357                 newModel.metFormulas(I(i))=newModel.metFormulas(J(i));
+0358             end
+0359         end
+0360         if isfield(newModel,'metMiriams')
+0361             if isempty(newModel.metMiriams{I(i)})
+0362                 newModel.metMiriams(I(i))=newModel.metMiriams(J(i));
+0363             end
+0364         end
+0365         if isfield(newModel,'metCharges')
+0366             newModel.metCharges(I(i))=newModel.metCharges(J(i));
+0367         end
+0368         if isfield(newModel,'metDeltaG')
+0369             newModel.metDeltaG(I(i))=newModel.metDeltaG(J(i));
+0370         end
+0371     end
+0372 end
+0373 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/addRxns.html b/doc/core/addRxns.html new file mode 100644 index 000000000..5a26576f6 --- /dev/null +++ b/doc/core/addRxns.html @@ -0,0 +1,846 @@ + + + + Description of addRxns + + + + + + + + + +
Home > core > addRxns.m
+ + + +

addRxns +

+ +

PURPOSE ^

+
addRxns
+ +

SYNOPSIS ^

+
function newModel=addRxns(model,rxnsToAdd,eqnType,compartment,allowNewMets,allowNewGenes)
+ +

DESCRIPTION ^

+
 addRxns
+   Adds reactions to a model
+
+ Input:
+   model            a model structure
+   rxnsToAdd        the reaction structure can have the following fields:
+       rxns                cell array with unique strings that identifies
+                           each reaction
+       equations           cell array with equation strings. Decimal
+                           coefficients are expressed as "1.2".
+                           Reversibility is indicated by "<=>" or "=>"
+       mets                (alternative to equations) cell array with the
+                           metabolites involved in each reaction as nested
+                           arrays. E.g.: {{'met1','met2'},{'met1','met3','met4'}}
+                           In the case of one single reaction added, it
+                           can be a string array: {'met1','met2'}
+       stoichCoeffs        (alternative to equations) cell array with the
+                           corresponding stoichiometries as nested vectors
+                           E.g.: {[-1,+2],[-1,-1,+1]}. In the case of one
+                           single reaction added, it can be a vector: [-1,+2]
+       rxnNames            cell array with the names of each reaction
+                           (optional, default '')
+       lb                  vector with the lower bounds (optional, default
+                           model.annotations.defaultLB or -inf for
+                           reversible reactions and 0 for irreversible
+                           when "equations" is used. When "mets" and
+                           "stoichCoeffs" are ,used it defaults for all
+                           to model.annotations.defaultLB or -inf)
+       ub                  vector with the upper bounds (optional, default
+                           model.annotations.defaultUB or inf)
+       c                   vector with the objective function coefficients
+                           (optional, default 0)
+       eccodes             cell array with the EC-numbers for each
+                           reactions. Delimit several EC-numbers with ";"
+                           (optional, default '')
+       subSystems          cell array with the subsystems for each
+                           reaction (optional, default '')
+       grRules             cell array with the gene-reaction relationship
+                           for each reaction. E.g. "(A and B) or (C)"
+                           means that the reaction could be catalyzed by a
+                           complex between A & B or by C on its own. All
+                           the genes have to be present in model.genes.
+                           Add genes with addGenesRaven before calling
+                           this function if needed (optional, default '')
+       rxnMiriams          cell array with Miriam structures (optional,
+                           default [])
+       rxnComps            cell array with compartments (as in
+                           model.comps) (optional, default {})
+       rxnNotes            cell array with reaction notes (optional,
+                           default '')
+       rxnDeltaG           Gibbs free energy at biochemical standard
+                           condition in kJ/mole (optional, default NaN)
+       rxnReferences       cell array with reaction references (optional,
+                           default '')
+       rxnConfidenceScores vector with reaction confidence scores
+                           (optional, default NaN)
+   eqnType          double describing how the equation string should be
+                    interpreted
+                    1 - The metabolites are matched to model.mets. New
+                        metabolites (if allowed) are added to
+                        "compartment" (default)
+                    2 - The metabolites are matched to model.metNames and
+                        all metabolites are assigned to "compartment". Any
+                        new metabolites that are added will be assigned
+                        IDs "m1", "m2"... If IDs on the same form are
+                        already used in the model then the numbering will
+                        start from the highest used integer+1
+                    3 - The metabolites are written as
+                        "metNames[comps]". Only compartments in
+                        model.comps are allowed. Any
+                        new metabolites that are added will be assigned
+                        IDs "m1", "m2"... If IDs on the same form are
+                        already used in the model then the numbering will
+                        start from the highest used integer+1
+   compartment      a string with the compartment the metabolites should
+                    be placed in when using eqnType=2. Must match
+                    model.comps (optional when eqnType=1 or eqnType=3)
+   allowNewMets     true if the function is allowed to add new
+                    metabolites. Can also be a string, which will be used
+                    as prefix for the new metabolite IDs. It is highly
+                    recommended to first add any new metabolites with
+                    addMets rather than automatically through this
+                    function. addMets supports more annotation of
+                    metabolites, allows for the use of exchange
+                    metabolites, and using it reduces the risk of parsing
+                    errors (optional, default false)
+   allowNewGenes    true if the functions is allowed to add new genes
+                    (optional, default false)
+
+ Output:
+   newModel         an updated model structure
+
+   This function does not make extensive checks about formatting of
+   gene-reaction rules.
+
+   When adding metabolites to a compartment where they previously do not
+   the function will copy any available information from the metabolite in
+   another compartment.
+
+ Usage: newModel = addRxns(model, rxnsToAdd, eqnType, compartment,...
+                       allowNewMets, allowNewGenes)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function newModel=addRxns(model,rxnsToAdd,eqnType,compartment,allowNewMets,allowNewGenes)
+0002 % addRxns
+0003 %   Adds reactions to a model
+0004 %
+0005 % Input:
+0006 %   model            a model structure
+0007 %   rxnsToAdd        the reaction structure can have the following fields:
+0008 %       rxns                cell array with unique strings that identifies
+0009 %                           each reaction
+0010 %       equations           cell array with equation strings. Decimal
+0011 %                           coefficients are expressed as "1.2".
+0012 %                           Reversibility is indicated by "<=>" or "=>"
+0013 %       mets                (alternative to equations) cell array with the
+0014 %                           metabolites involved in each reaction as nested
+0015 %                           arrays. E.g.: {{'met1','met2'},{'met1','met3','met4'}}
+0016 %                           In the case of one single reaction added, it
+0017 %                           can be a string array: {'met1','met2'}
+0018 %       stoichCoeffs        (alternative to equations) cell array with the
+0019 %                           corresponding stoichiometries as nested vectors
+0020 %                           E.g.: {[-1,+2],[-1,-1,+1]}. In the case of one
+0021 %                           single reaction added, it can be a vector: [-1,+2]
+0022 %       rxnNames            cell array with the names of each reaction
+0023 %                           (optional, default '')
+0024 %       lb                  vector with the lower bounds (optional, default
+0025 %                           model.annotations.defaultLB or -inf for
+0026 %                           reversible reactions and 0 for irreversible
+0027 %                           when "equations" is used. When "mets" and
+0028 %                           "stoichCoeffs" are ,used it defaults for all
+0029 %                           to model.annotations.defaultLB or -inf)
+0030 %       ub                  vector with the upper bounds (optional, default
+0031 %                           model.annotations.defaultUB or inf)
+0032 %       c                   vector with the objective function coefficients
+0033 %                           (optional, default 0)
+0034 %       eccodes             cell array with the EC-numbers for each
+0035 %                           reactions. Delimit several EC-numbers with ";"
+0036 %                           (optional, default '')
+0037 %       subSystems          cell array with the subsystems for each
+0038 %                           reaction (optional, default '')
+0039 %       grRules             cell array with the gene-reaction relationship
+0040 %                           for each reaction. E.g. "(A and B) or (C)"
+0041 %                           means that the reaction could be catalyzed by a
+0042 %                           complex between A & B or by C on its own. All
+0043 %                           the genes have to be present in model.genes.
+0044 %                           Add genes with addGenesRaven before calling
+0045 %                           this function if needed (optional, default '')
+0046 %       rxnMiriams          cell array with Miriam structures (optional,
+0047 %                           default [])
+0048 %       rxnComps            cell array with compartments (as in
+0049 %                           model.comps) (optional, default {})
+0050 %       rxnNotes            cell array with reaction notes (optional,
+0051 %                           default '')
+0052 %       rxnDeltaG           Gibbs free energy at biochemical standard
+0053 %                           condition in kJ/mole (optional, default NaN)
+0054 %       rxnReferences       cell array with reaction references (optional,
+0055 %                           default '')
+0056 %       rxnConfidenceScores vector with reaction confidence scores
+0057 %                           (optional, default NaN)
+0058 %   eqnType          double describing how the equation string should be
+0059 %                    interpreted
+0060 %                    1 - The metabolites are matched to model.mets. New
+0061 %                        metabolites (if allowed) are added to
+0062 %                        "compartment" (default)
+0063 %                    2 - The metabolites are matched to model.metNames and
+0064 %                        all metabolites are assigned to "compartment". Any
+0065 %                        new metabolites that are added will be assigned
+0066 %                        IDs "m1", "m2"... If IDs on the same form are
+0067 %                        already used in the model then the numbering will
+0068 %                        start from the highest used integer+1
+0069 %                    3 - The metabolites are written as
+0070 %                        "metNames[comps]". Only compartments in
+0071 %                        model.comps are allowed. Any
+0072 %                        new metabolites that are added will be assigned
+0073 %                        IDs "m1", "m2"... If IDs on the same form are
+0074 %                        already used in the model then the numbering will
+0075 %                        start from the highest used integer+1
+0076 %   compartment      a string with the compartment the metabolites should
+0077 %                    be placed in when using eqnType=2. Must match
+0078 %                    model.comps (optional when eqnType=1 or eqnType=3)
+0079 %   allowNewMets     true if the function is allowed to add new
+0080 %                    metabolites. Can also be a string, which will be used
+0081 %                    as prefix for the new metabolite IDs. It is highly
+0082 %                    recommended to first add any new metabolites with
+0083 %                    addMets rather than automatically through this
+0084 %                    function. addMets supports more annotation of
+0085 %                    metabolites, allows for the use of exchange
+0086 %                    metabolites, and using it reduces the risk of parsing
+0087 %                    errors (optional, default false)
+0088 %   allowNewGenes    true if the functions is allowed to add new genes
+0089 %                    (optional, default false)
+0090 %
+0091 % Output:
+0092 %   newModel         an updated model structure
+0093 %
+0094 %   This function does not make extensive checks about formatting of
+0095 %   gene-reaction rules.
+0096 %
+0097 %   When adding metabolites to a compartment where they previously do not
+0098 %   the function will copy any available information from the metabolite in
+0099 %   another compartment.
+0100 %
+0101 % Usage: newModel = addRxns(model, rxnsToAdd, eqnType, compartment,...
+0102 %                       allowNewMets, allowNewGenes)
+0103 
+0104 if nargin<3
+0105     eqnType=1;
+0106 elseif ~isnumeric(eqnType)
+0107     EM='eqnType must be numeric';
+0108     dispEM(EM);
+0109 elseif ~ismember(eqnType,[1 2 3])
+0110     EM='eqnType must be 1, 2, or 3';
+0111     dispEM(EM);
+0112 end    
+0113 
+0114 if nargin<4
+0115     compartment=[];
+0116 else
+0117     compartment=char(compartment);
+0118 end
+0119 if nargin<5
+0120     allowNewMets=false;
+0121 elseif ~islogical(allowNewMets)
+0122     allowNewMets=char(allowNewMets);
+0123 end
+0124 if nargin<6
+0125     allowNewGenes=false;
+0126 end
+0127 
+0128 if allowNewGenes & isfield(rxnsToAdd,'grRules')
+0129     genesToAdd.genes = strjoin(convertCharArray(rxnsToAdd.grRules));
+0130     genesToAdd.genes = regexp(genesToAdd.genes,' |)|(|and|or','split'); % Remove all grRule punctuation
+0131     genesToAdd.genes = genesToAdd.genes(~cellfun(@isempty,genesToAdd.genes));  % Remove spaces and empty genes
+0132     genesToAdd.genes = setdiff(unique(genesToAdd.genes),model.genes); % Only keep new genes
+0133     if isfield(model,'geneComps')
+0134         genesToAdd.geneComps(1:numel(genesToAdd.genes)) = repmat(11,numel(genesToAdd.genes),1);
+0135     end
+0136     if ~isempty(genesToAdd.genes)
+0137         fprintf('\nNew genes added to the model:\n')
+0138         fprintf([strjoin(genesToAdd.genes,'\n') '\n'])
+0139         newModel=addGenesRaven(model,genesToAdd);
+0140     else
+0141         newModel=model;
+0142     end
+0143 else
+0144     newModel=model;
+0145 end
+0146 
+0147 %If no reactions should be added
+0148 if isempty(rxnsToAdd)
+0149     return;
+0150 end
+0151 
+0152 if eqnType==2 || (eqnType==1 && allowNewMets==true)
+0153     compartment=char(compartment);
+0154     if ~ismember(compartment,model.comps)
+0155         EM='compartment must match one of the compartments in model.comps';
+0156         dispEM(EM);
+0157     end
+0158 end
+0159 
+0160 if ~isfield(rxnsToAdd,'rxns')
+0161     EM='rxns is a required field in rxnsToAdd';
+0162     dispEM(EM);
+0163 else
+0164     rxnsToAdd.rxns=convertCharArray(rxnsToAdd.rxns);
+0165     %To fit with some later printing
+0166     rxnsToAdd.rxns=rxnsToAdd.rxns(:);
+0167 end
+0168 if ~(isfield(rxnsToAdd,'equations') || (isfield(rxnsToAdd,'mets') && isfield(rxnsToAdd,'stoichCoeffs')))
+0169     EM='Either "equations" or "mets"+"stoichCoeffs" are required fields in rxnsToAdd';
+0170     dispEM(EM);
+0171 end
+0172 
+0173 if any(ismember(rxnsToAdd.rxns,model.rxns))
+0174     EM='One or more reaction id was already present in the model. Use changeRxns or remove the existing reactions before adding new ones';
+0175     dispEM(EM);
+0176 end
+0177 
+0178 %Normal case: equations provided
+0179 if isfield(rxnsToAdd,'equations')
+0180     rxnsToAdd.equations=convertCharArray(rxnsToAdd.equations);
+0181 
+0182     %Alternative case: mets+stoichiometry provided
+0183 else
+0184     %In the case of 1 rxn added (array of strings + vector), transform to
+0185     %cells of length=1:
+0186     if iscellstr(rxnsToAdd.mets)
+0187         rxnsToAdd.mets={rxnsToAdd.mets};
+0188     end
+0189     if isnumeric(rxnsToAdd.stoichCoeffs)
+0190         rxnsToAdd.stoichCoeffs = {rxnsToAdd.stoichCoeffs};
+0191     end
+0192     %Now both rxnsToAdd.mets and rxnsToAdd.stoichCoeffs should be cell
+0193     %arrays & of the same size:
+0194     if ~iscell(rxnsToAdd.mets) || ~iscell(rxnsToAdd.stoichCoeffs)
+0195         EM='rxnsToAdd.mets & rxnsToAdd.stoichCoeffs must be cell arrays';
+0196         dispEM(EM);
+0197     elseif length(rxnsToAdd.stoichCoeffs) ~= length(rxnsToAdd.mets)
+0198         EM = 'rxnsToAdd.stoichCoeffs must have the same number of elements as rxnsToAdd.mets';
+0199         dispEM(EM);
+0200     end
+0201     %In this case we need lb to decide if the reaction is reversible or not:
+0202     if ~isfield(rxnsToAdd,'lb')
+0203         %Fill with standard if it doesn't exist
+0204         rxnsToAdd.lb=-inf(size(rxnsToAdd.mets));
+0205     elseif ~isnumeric(rxnsToAdd.lb)
+0206         EM = 'rxnsToAdd.lb must be a vector';
+0207         dispEM(EM);
+0208     elseif length(rxnsToAdd.lb) ~= length(rxnsToAdd.mets)
+0209         EM = 'rxnsToAdd.lb must have the same number of elements as rxnsToAdd.mets';
+0210         dispEM(EM);
+0211     end
+0212     %Now we construct equations, to comply with the rest of the script:
+0213     rxnsToAdd.equations = cell(size(rxnsToAdd.mets));
+0214     for i = 1:length(rxnsToAdd.mets)
+0215         mets         = rxnsToAdd.mets{i};
+0216         stoichCoeffs = rxnsToAdd.stoichCoeffs{i};
+0217         if isfield(rxnsToAdd,'ub')
+0218             isrev        = rxnsToAdd.lb(i) < 0 && rxnsToAdd.ub(i) > 0;
+0219         else
+0220             isrev        = rxnsToAdd.lb(i) < 0;
+0221         end
+0222         rxnsToAdd.equations{i} = buildEquation(mets,stoichCoeffs,isrev);
+0223     end
+0224 end
+0225 
+0226 nRxns=numel(rxnsToAdd.rxns);
+0227 nOldRxns=numel(model.rxns);
+0228 filler=cell(nRxns,1);
+0229 filler(:)={''};
+0230 cellfiller=cell(nRxns,1);
+0231 cellfiller(:)={{''}};
+0232 largeFiller=cell(nOldRxns,1);
+0233 largeFiller(:)={''};
+0234 largeCellFiller=cell(nOldRxns,1);
+0235 largeCellFiller(:)={{''}};
+0236 
+0237 %***Add everything to the model except for the equations.
+0238 if numel(rxnsToAdd.equations)~=nRxns
+0239     EM='rxnsToAdd.equations must have the same number of elements as rxnsToAdd.rxns';
+0240     dispEM(EM);
+0241 end
+0242 
+0243 %Parse the equations. This is done at this early stage since I need the
+0244 %reversibility info
+0245 [S, mets, badRxns, reversible]=constructS(rxnsToAdd.equations);
+0246 EM='The following equations have one or more metabolites both as substrate and product. Only the net equations will be added:';
+0247 dispEM(EM,false,rxnsToAdd.rxns(badRxns));
+0248 
+0249 newModel.rev=[newModel.rev;reversible];
+0250 newModel.rxns=[newModel.rxns;rxnsToAdd.rxns(:)];
+0251 
+0252 if isfield(rxnsToAdd,'rxnNames')
+0253     rxnsToAdd.rxnNames=convertCharArray(rxnsToAdd.rxnNames);
+0254     if numel(rxnsToAdd.rxnNames)~=nRxns
+0255         EM='rxnsToAdd.rxnNames must have the same number of elements as rxnsToAdd.rxns';
+0256         dispEM(EM);
+0257     end
+0258     %Fill with standard if it doesn't exist
+0259     if ~isfield(newModel,'rxnNames')
+0260         newModel.rxnNames=largeFiller;
+0261     end
+0262     newModel.rxnNames=[newModel.rxnNames;rxnsToAdd.rxnNames(:)];
+0263 else
+0264     %Fill with standard if it doesn't exist
+0265     if isfield(newModel,'rxnNames')
+0266         newModel.rxnNames=[newModel.rxnNames;filler];
+0267     end
+0268 end
+0269 
+0270 if isfield(newModel,'annotation') & isfield(newModel.annotation,'defaultLB')
+0271     newLb=newModel.annotation.defaultLB;
+0272 else
+0273     newLb=-inf;
+0274 end
+0275 
+0276 if isfield(rxnsToAdd,'lb')
+0277     if numel(rxnsToAdd.lb)~=nRxns
+0278         EM='rxnsToAdd.lb must have the same number of elements as rxnsToAdd.rxns';
+0279         dispEM(EM);
+0280     end
+0281     %Fill with standard if it doesn't exist
+0282     if ~isfield(newModel,'lb')
+0283         newModel.lb=zeros(nOldRxns,1);
+0284         newModel.lb(newModel.rev~=0)=newLb;
+0285     end
+0286     newModel.lb=[newModel.lb;rxnsToAdd.lb(:)];
+0287 else
+0288     %Fill with standard if it doesn't exist
+0289     if isfield(newModel,'lb')
+0290         I=zeros(nRxns,1);
+0291         I(reversible~=0)=newLb;
+0292         newModel.lb=[newModel.lb;I];
+0293     end
+0294 end
+0295 
+0296 if isfield(newModel,'annotation') & isfield(newModel.annotation,'defaultUB')
+0297     newUb=newModel.annotation.defaultUB;
+0298 else
+0299     newUb=inf;
+0300 end
+0301 
+0302 if isfield(rxnsToAdd,'ub')
+0303     if numel(rxnsToAdd.ub)~=nRxns
+0304         EM='rxnsToAdd.ub must have the same number of elements as rxnsToAdd.rxns';
+0305         dispEM(EM);
+0306     end
+0307     %Fill with standard if it doesn't exist
+0308     if ~isfield(newModel,'ub')
+0309         newModel.ub=repmat(newUb,nOldRxns,1);
+0310     end
+0311     newModel.ub=[newModel.ub;rxnsToAdd.ub(:)];
+0312 else
+0313     %Fill with standard if it doesn't exist
+0314     if isfield(newModel,'ub')
+0315         newModel.ub=[newModel.ub;repmat(newUb,nRxns,1)];
+0316     end
+0317 end
+0318 
+0319 if isfield(rxnsToAdd,'c')
+0320     if numel(rxnsToAdd.c)~=nRxns
+0321         EM='rxnsToAdd.c must have the same number of elements as rxnsToAdd.rxns';
+0322         dispEM(EM);
+0323     end
+0324     %Fill with standard if it doesn't exist
+0325     if ~isfield(newModel,'c')
+0326         newModel.c=zeros(nOldRxns,1);
+0327     end
+0328     newModel.c=[newModel.c;rxnsToAdd.c(:)];
+0329 else
+0330     %Fill with standard if it doesn't exist
+0331     if isfield(newModel,'c')
+0332         newModel.c=[newModel.c;zeros(nRxns,1)];
+0333     end
+0334 end
+0335 
+0336 if isfield(rxnsToAdd,'eccodes')
+0337     rxnsToAdd.eccodes=convertCharArray(rxnsToAdd.eccodes);
+0338     if numel(rxnsToAdd.eccodes)~=nRxns
+0339         EM='rxnsToAdd.eccodes must have the same number of elements as rxnsToAdd.rxns';
+0340         dispEM(EM);
+0341     end
+0342     %Fill with standard if it doesn't exist
+0343     if ~isfield(newModel,'eccodes')
+0344         newModel.eccodes=largeFiller;
+0345     end
+0346     newModel.eccodes=[newModel.eccodes;rxnsToAdd.eccodes(:)];
+0347 else
+0348     %Fill with standard if it doesn't exist
+0349     if isfield(newModel,'eccodes')
+0350         newModel.eccodes=[newModel.eccodes;filler];
+0351     end
+0352 end
+0353 
+0354 if isfield(rxnsToAdd,'subSystems')
+0355     % Has to be cell array
+0356     if ischar(rxnsToAdd.subSystems)
+0357         rxnsToAdd.subSystems = {rxnsToAdd.subSystems};
+0358     end
+0359     % If all nested cells are 1x1, then unnest
+0360     if all(cellfun(@(x) iscell(x) && isscalar(x), rxnsToAdd.subSystems))
+0361         rxnsToAdd.subSystems = transpose([rxnsToAdd.subSystems{:}]);
+0362     end
+0363     % Cell array should now be as simple as possible. Check if it is nested
+0364     subSysRxnsNested = any(cellfun(@(x) iscell(x), rxnsToAdd.subSystems));
+0365     if isfield(newModel,'subSystems')
+0366         subSysModelNested = any(cellfun(@(x) iscell(x), newModel.subSystems));
+0367     else
+0368         subSysModelNested = subSysRxnsNested;
+0369         if subSysRxnsNested
+0370             newModel.subSystems=largeCellFiller;
+0371         else
+0372             newModel.subSystems=largeFiller;
+0373         end
+0374     end
+0375     if subSysRxnsNested && ~subSysModelNested
+0376         % Make all existing subSystems nested
+0377         newModel.subSystems = cellfun(@(x) {x}, newModel.subSystems, 'uni', 0);
+0378     elseif ~subSysRxnsNested && subSysModelNested
+0379         rxnsToAdd.subSystems = cellfun(@(x) {x}, rxnsToAdd.subSystems, 'uni', 0);
+0380     end
+0381     if numel(rxnsToAdd.subSystems)~=nRxns
+0382         EM='rxnsToAdd.subSystems must have the same number of elements as rxnsToAdd.rxns';
+0383         dispEM(EM);
+0384     end
+0385     newModel.subSystems=[newModel.subSystems;rxnsToAdd.subSystems(:)];
+0386 else
+0387     %Fill with standard if it does not exist
+0388     if isfield(newModel,'subSystems')
+0389         if any(cellfun(@(x) iscell(x), newModel.subSystems))
+0390             newModel.subSystems=[newModel.subSystems;cellfiller];
+0391         else
+0392             newModel.subSystems=[newModel.subSystems;filler];
+0393         end
+0394     end
+0395 end
+0396 if isfield(rxnsToAdd,'rxnMiriams')
+0397     if numel(rxnsToAdd.rxnMiriams)~=nRxns
+0398         EM='rxnsToAdd.rxnMiriams must have the same number of elements as rxnsToAdd.rxns';
+0399         dispEM(EM);
+0400     end
+0401     %Fill with standard if it doesn't exist
+0402     if ~isfield(newModel,'rxnMiriams')
+0403         newModel.rxnMiriams=cell(nOldRxns,1);
+0404     end
+0405     newModel.rxnMiriams=[newModel.rxnMiriams;rxnsToAdd.rxnMiriams(:)];
+0406 else
+0407     %Fill with standard if it doesn't exist
+0408     if isfield(newModel,'rxnMiriams')
+0409         newModel.rxnMiriams=[newModel.rxnMiriams;cell(nRxns,1)];
+0410     end
+0411 end
+0412 if isfield(rxnsToAdd,'rxnComps')
+0413     if numel(rxnsToAdd.rxnComps)~=nRxns
+0414         EM='rxnsToAdd.rxnComps must have the same number of elements as rxnsToAdd.rxns';
+0415         dispEM(EM);
+0416     end
+0417     %Fill with standard if it doesn't exist
+0418     if ~isfield(newModel,'rxnComps')
+0419         newModel.rxnComps=ones(nOldRxns,1);
+0420         EM='Adding reactions with compartment information to a model without such information. All existing reactions will be assigned to the first compartment';
+0421         dispEM(EM,false);
+0422     end
+0423     newModel.rxnComps=[newModel.rxnComps;rxnsToAdd.rxnComps(:)];
+0424 else
+0425     %Fill with standard if it doesn't exist
+0426     if isfield(newModel,'rxnComps')
+0427         newModel.rxnComps=[newModel.rxnComps;ones(nRxns,1)];
+0428         %fprintf('NOTE: The added reactions will be assigned to the first
+0429         %compartment\n');
+0430     end
+0431 end
+0432 if isfield(rxnsToAdd,'grRules')
+0433     rxnsToAdd.grRules=convertCharArray(rxnsToAdd.grRules);
+0434     if numel(rxnsToAdd.grRules)~=nRxns
+0435         EM='rxnsToAdd.grRules must have the same number of elements as rxnsToAdd.rxns';
+0436         dispEM(EM);
+0437     end
+0438     %Fill with standard if it doesn't exist
+0439     if ~isfield(newModel,'grRules')
+0440         newModel.grRules=largeFiller;
+0441     end
+0442     newModel.grRules=[newModel.grRules;rxnsToAdd.grRules(:)];
+0443 else
+0444     %Fill with standard if it doesn't exist
+0445     if isfield(newModel,'grRules')
+0446         newModel.grRules=[newModel.grRules;filler];
+0447     end
+0448 end
+0449 
+0450 if isfield(rxnsToAdd,'rxnFrom')
+0451     rxnsToAdd.rxnFrom=convertCharArray(rxnsToAdd.rxnFrom);
+0452     if numel(rxnsToAdd.rxnFrom)~=nRxns
+0453         EM='rxnsToAdd.rxnFrom must have the same number of elements as rxnsToAdd.rxns';
+0454         dispEM(EM);
+0455     end
+0456     %Fill with standard if it doesn't exist
+0457     if ~isfield(newModel,'rxnFrom')
+0458         newModel.rxnFrom=largeFiller;
+0459     end
+0460     newModel.rxnFrom=[newModel.rxnFrom;rxnsToAdd.rxnFrom(:)];
+0461 else
+0462     %Fill with standard if it doesn't exist
+0463     if isfield(newModel,'rxnFrom')
+0464         newModel.rxnFrom=[newModel.rxnFrom;filler];
+0465     end
+0466 end
+0467 
+0468 if isfield(rxnsToAdd,'rxnNotes')
+0469     rxnsToAdd.rxnNotes=convertCharArray(rxnsToAdd.rxnNotes);
+0470     if numel(rxnsToAdd.rxnNotes)~=nRxns
+0471         EM='rxnsToAdd.rxnNotes must have the same number of elements as rxnsToAdd.rxns';
+0472         dispEM(EM);
+0473     end
+0474     %Fill with standard if it doesn't exist
+0475     if ~isfield(newModel,'rxnNotes')
+0476         newModel.rxnNotes=largeFiller;
+0477     end
+0478     newModel.rxnNotes=[newModel.rxnNotes;rxnsToAdd.rxnNotes(:)];
+0479 else
+0480     %Fill with standard if it doesn't exist
+0481     if isfield(newModel,'rxnNotes')
+0482         newModel.rxnNotes=[newModel.rxnNotes;filler];
+0483     end
+0484 end
+0485 
+0486 if isfield(rxnsToAdd,'rxnReferences')
+0487     rxnsToAdd.rxnReferences=convertCharArray(rxnsToAdd.rxnReferences);
+0488     if numel(rxnsToAdd.rxnReferences)~=nRxns
+0489         EM='rxnsToAdd.rxnReferences must have the same number of elements as rxnsToAdd.rxns';
+0490         dispEM(EM);
+0491     end
+0492     %Fill with standard if it doesn't exist
+0493     if ~isfield(newModel,'rxnReferences')
+0494         newModel.rxnReferences=largeFiller;
+0495     end
+0496     newModel.rxnReferences=[newModel.rxnReferences;rxnsToAdd.rxnReferences(:)];
+0497 else
+0498     %Fill with standard if it doesn't exist
+0499     if isfield(newModel,'rxnReferences')
+0500         newModel.rxnReferences=[newModel.rxnReferences;filler];
+0501     end
+0502 end
+0503 
+0504 if isfield(rxnsToAdd,'pwys')
+0505     rxnsToAdd.pwys=convertCharArray(rxnsToAdd.pwys);
+0506     if numel(rxnsToAdd.pwys)~=nRxns
+0507         EM='rxnsToAdd.pwys must have the same number of elements as rxnsToAdd.rxns';
+0508         dispEM(EM);
+0509     end
+0510     %Fill with standard if it doesn't exist
+0511     if ~isfield(newModel,'pwys')
+0512         newModel.pwys=largeFiller;
+0513     end
+0514     newModel.pwys=[newModel.pwys;rxnsToAdd.pwys(:)];
+0515 else
+0516     %Fill with standard if it doesn't exist
+0517     if isfield(newModel,'pwys')
+0518         newModel.pwys=[newModel.pwys;filler];
+0519     end
+0520 end
+0521 
+0522 if isfield(rxnsToAdd,'rxnConfidenceScores')
+0523     if numel(rxnsToAdd.rxnConfidenceScores)~=nRxns
+0524         EM='rxnsToAdd.rxnConfidenceScores must have the same number of elements as rxnsToAdd.rxns';
+0525         dispEM(EM);
+0526     end
+0527     %Fill with standard if it doesn't exist
+0528     if ~isfield(newModel,'rxnConfidenceScores')
+0529         newModel.rxnConfidenceScores=NaN(nOldRxns,1);
+0530     end
+0531     newModel.rxnConfidenceScores=[newModel.rxnConfidenceScores;rxnsToAdd.rxnConfidenceScores(:)];
+0532 else
+0533     %Fill with standard if it doesn't exist
+0534     if isfield(newModel,'rxnConfidenceScores')
+0535         newModel.rxnConfidenceScores=[newModel.rxnConfidenceScores;NaN(nRxns,1)];
+0536     end
+0537 end
+0538 
+0539 if isfield(rxnsToAdd,'rxnDeltaG')
+0540     if numel(rxnsToAdd.rxnDeltaG)~=nRxns
+0541         EM='rxnsToAdd.rxnDeltaG must have the same number of elements as rxnsToAdd.rxns';
+0542         dispEM(EM);
+0543     end
+0544     %Fill with standard if it doesn't exist
+0545     if ~isfield(newModel,'rxnDeltaG')
+0546         newModel.rxnDeltaG=NaN(nOldRxns,1);
+0547     end
+0548     newModel.rxnDeltaG=[newModel.rxnDeltaG;rxnsToAdd.rxnDeltaG(:)];
+0549 else
+0550     %Fill with standard if it doesn't exist
+0551     if isfield(newModel,'rxnDeltaG')
+0552         newModel.rxnDeltaG=[newModel.rxnDeltaG;NaN(nRxns,1)];
+0553     end
+0554 end
+0555 
+0556 
+0557 %***Start parsing the equations and adding the info to the S matrix The
+0558 %mets are matched to model.mets
+0559 if eqnType==1
+0560     [I, J]=ismember(mets,model.mets);
+0561     if ~all(I)
+0562         if allowNewMets==true || ischar(allowNewMets)
+0563             %Add the new mets
+0564             metsToAdd.mets=mets(~I);
+0565             metsToAdd.metNames=metsToAdd.mets;
+0566             metsToAdd.compartments=compartment;
+0567             if ischar(allowNewMets)
+0568                 newModel=addMets(newModel,metsToAdd,true,allowNewMets);
+0569             else
+0570                 newModel=addMets(newModel,metsToAdd,true);
+0571             end
+0572         else
+0573             EM='One or more equations contain metabolites that are not in model.mets. Set allowNewMets to true to allow this function to add metabolites or use addMets to add them before calling this function. Are you sure that eqnType=1?';
+0574             dispEM(EM);
+0575         end
+0576     end
+0577     %Calculate the indexes of the metabolites and add the info
+0578     metIndexes=J;
+0579     metIndexes(~I)=numel(newModel.mets)-sum(~I)+1:numel(newModel.mets);
+0580 end
+0581 
+0582 %Do some stuff that is the same for eqnType=2 and eqnType=3
+0583 if eqnType==2 || eqnType==3
+0584     %For later..
+0585     t2=strcat(model.metNames,'***',model.comps(model.metComps));
+0586 end
+0587 
+0588 %The mets are matched to model.metNames and assigned to "compartment"
+0589 if eqnType==2
+0590     %%Check that the metabolite names aren't present in the same
+0591     %%compartment.
+0592     %Not the neatest way maybe..
+0593     t1=strcat(mets,'***',compartment);
+0594     [I, J]=ismember(t1,t2);
+0595     
+0596     if ~all(I)
+0597         if allowNewMets==true || ischar(allowNewMets)
+0598             %Add the new mets
+0599             metsToAdd.metNames=mets(~I);
+0600             metsToAdd.compartments=compartment;
+0601             if ischar(allowNewMets)
+0602                 newModel=addMets(newModel,metsToAdd,true,allowNewMets);
+0603             else
+0604                 newModel=addMets(newModel,metsToAdd,true);
+0605             end
+0606         else
+0607             EM='One or more equations contain metabolites that are not in model.mets. Set allowNewMets to true to allow this function to add metabolites or use addMets to add them before calling this function';
+0608             dispEM(EM);
+0609         end
+0610     end
+0611     
+0612     %Calculate the indexes of the metabolites
+0613     metIndexes=J;
+0614     metIndexes(~I)=numel(newModel.mets)-sum(~I)+1:numel(newModel.mets);
+0615 end
+0616 
+0617 %The equations are on the form metNames[compName]
+0618 if eqnType==3
+0619     %Parse the metabolite names
+0620     metNames=cell(numel(mets),1);
+0621     compartments=metNames;
+0622     for i=1:numel(mets)
+0623         starts=max(strfind(mets{i},'['));
+0624         ends=max(strfind(mets{i},']'));
+0625         
+0626         %Check that the formatting is correct
+0627         if isempty(starts) || isempty(ends) || ends<numel(mets{i})
+0628             EM=['The metabolite ' mets{i} ' is not correctly formatted for eqnType=3'];
+0629             dispEM(EM);
+0630         end
+0631         
+0632         %Check that the compartment is correct
+0633         compartments{i}=mets{i}(starts+1:ends-1);
+0634         I=ismember(compartments(i),newModel.comps);
+0635         if ~I
+0636             EM=['The metabolite ' mets{i} ' has a compartment that is not in model.comps'];
+0637             dispEM(EM);
+0638         end
+0639         metNames{i}=mets{i}(1:starts-1);
+0640     end
+0641     
+0642     %Check if the metabolite exists already
+0643     t1=strcat(metNames,'***',compartments);
+0644     [I, J]=ismember(t1,t2);
+0645     
+0646     if ~all(I)
+0647         if allowNewMets==true | ischar(allowNewMets)
+0648             %Add the new mets
+0649             metsToAdd.metNames=metNames(~I);
+0650             metsToAdd.compartments=compartments(~I);
+0651             if ischar(allowNewMets)
+0652                 newModel=addMets(newModel,metsToAdd,true,allowNewMets);
+0653             else
+0654                 newModel=addMets(newModel,metsToAdd,true);
+0655             end
+0656         else
+0657             EM='One or more equations contain metabolites that are not in model.metNames. Set allowNewMets to true to allow this function to add metabolites or use addMets to add them before calling this function';
+0658             dispEM(EM);
+0659         end
+0660     end
+0661     
+0662     %Calculate the indexes of the metabolites
+0663     metIndexes=J;
+0664     metIndexes(~I)=numel(newModel.mets)-sum(~I)+1:numel(newModel.mets);
+0665 end
+0666 
+0667 %Add the info to the stoichiometric matrix
+0668 newModel.S=[newModel.S sparse(size(newModel.S,1),nRxns)];
+0669 
+0670 for i=1:nRxns
+0671     newModel.S(metIndexes,nOldRxns+i)=S(:,i);
+0672     %Parse the grRules and check whether all genes in grRules appear in
+0673     %genes
+0674     if isfield(newModel,'grRules')
+0675         rule=newModel.grRules{nOldRxns+i};
+0676         rule=strrep(rule,'(','');
+0677         rule=strrep(rule,')','');
+0678         rule=strrep(rule,' or ',' ');
+0679         rule=strrep(rule,' and ',' ');
+0680         genes=regexp(rule,' ','split');
+0681         [I, J]=ismember(genes,newModel.genes);
+0682         if ~all(I) && any(rule)
+0683             EM=['Not all genes for reaction ' rxnsToAdd.rxns{i} ' were found in model.genes. If needed, add genes with addGenesRaven before calling this function, or set the ''allowNewGenes'' flag to true'];
+0684             dispEM(EM);
+0685         end
+0686     end
+0687 end
+0688 
+0689 %Make temporary minimal model structure with only new rxns, to parse to
+0690 %standardizeGrRules
+0691 newRxnsModel.genes=newModel.genes;
+0692 newRxnsModel.grRules=newModel.grRules(length(model.rxns)+1:end);
+0693 newRxnsModel.rxns=newModel.rxns(length(model.rxns)+1:end);
+0694 
+0695 %Fix grRules and reconstruct rxnGeneMat
+0696 [grRules,rxnGeneMat] = standardizeGrRules(newRxnsModel,true);
+0697 newModel.rxnGeneMat = [newModel.rxnGeneMat; rxnGeneMat];
+0698 newModel.grRules = [newModel.grRules(1:nOldRxns); grRules];
+0699 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/addRxnsGenesMets.html b/doc/core/addRxnsGenesMets.html new file mode 100644 index 000000000..0ab9c27ba --- /dev/null +++ b/doc/core/addRxnsGenesMets.html @@ -0,0 +1,274 @@ + + + + Description of addRxnsGenesMets + + + + + + + + + +
Home > core > addRxnsGenesMets.m
+ + + +

addRxnsGenesMets +

+ +

PURPOSE ^

+
addRxnsGenesMets
+ +

SYNOPSIS ^

+
function model=addRxnsGenesMets(model,sourceModel,rxns,addGene,rxnNote,confidence)
+ +

DESCRIPTION ^

+
 addRxnsGenesMets
+   Copies reactions from a source model to a new model, including
+   (new) metabolites and genes
+
+   model           draft model where reactions should be copied to
+   sourceModel     model where reactions and metabolites are sourced from
+   rxns            cell array with reaction IDs (from source model). Can also
+                   be string if only one reaction is added
+   addGene         three options:
+                   false   no genes are annotated to the new reactions
+                   true    grRules ared copied from the sourceModel and
+                           new genes are added when required
+                   string or cell array
+                           new grRules are specified as string or cell
+                           array, and any new genes are added when
+                           required
+                   (optional, default false)
+   rxnNote         cell array with strings explaining why reactions were copied
+                   to the model, to be included as newModel.rxnNotes. Can also
+                   be string if same rxnNotes should be added for each new
+                   reaction, or only one reaction is to be added (optional, default
+                   'Added via addRxnsAndMets()')
+   confidence      integer specifying confidence score for all reactions.
+                   4:  biochemical data: direct evidence from enzymes
+                       assays
+                   3:  genetic data: knockout/-in or overexpression
+                       analysis
+                   2:  physiological data: indirect evidence, e.g.
+                       secretion products or defined medium requirement
+                       sequence data: genome annotation
+                   1:  modeling data: required for functional model,
+                       hypothetical reaction
+                   0:  no evidence
+                   following doi:10.1038/nprot.2009.203 (optional, default 0)
+
+   newModel        an updated model structure
+
+     This function only works if the draft model and source model follow
+    the same metabolite and compartment naming convention. Metabolites are
+    only matched by metaboliteName[compartment]. Useful if one wants to copy
+    additional reactions from source to draft after getModelFromHomology was
+    used involving the same models.
+
+ Usage: newModel=addRxnsGenesMets(model,sourceModel,rxns,addGene,rxnNote,confidence)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function model=addRxnsGenesMets(model,sourceModel,rxns,addGene,rxnNote,confidence)
+0002 % addRxnsGenesMets
+0003 %   Copies reactions from a source model to a new model, including
+0004 %   (new) metabolites and genes
+0005 %
+0006 %   model           draft model where reactions should be copied to
+0007 %   sourceModel     model where reactions and metabolites are sourced from
+0008 %   rxns            cell array with reaction IDs (from source model). Can also
+0009 %                   be string if only one reaction is added
+0010 %   addGene         three options:
+0011 %                   false   no genes are annotated to the new reactions
+0012 %                   true    grRules ared copied from the sourceModel and
+0013 %                           new genes are added when required
+0014 %                   string or cell array
+0015 %                           new grRules are specified as string or cell
+0016 %                           array, and any new genes are added when
+0017 %                           required
+0018 %                   (optional, default false)
+0019 %   rxnNote         cell array with strings explaining why reactions were copied
+0020 %                   to the model, to be included as newModel.rxnNotes. Can also
+0021 %                   be string if same rxnNotes should be added for each new
+0022 %                   reaction, or only one reaction is to be added (optional, default
+0023 %                   'Added via addRxnsAndMets()')
+0024 %   confidence      integer specifying confidence score for all reactions.
+0025 %                   4:  biochemical data: direct evidence from enzymes
+0026 %                       assays
+0027 %                   3:  genetic data: knockout/-in or overexpression
+0028 %                       analysis
+0029 %                   2:  physiological data: indirect evidence, e.g.
+0030 %                       secretion products or defined medium requirement
+0031 %                       sequence data: genome annotation
+0032 %                   1:  modeling data: required for functional model,
+0033 %                       hypothetical reaction
+0034 %                   0:  no evidence
+0035 %                   following doi:10.1038/nprot.2009.203 (optional, default 0)
+0036 %
+0037 %   newModel        an updated model structure
+0038 %
+0039 %     This function only works if the draft model and source model follow
+0040 %    the same metabolite and compartment naming convention. Metabolites are
+0041 %    only matched by metaboliteName[compartment]. Useful if one wants to copy
+0042 %    additional reactions from source to draft after getModelFromHomology was
+0043 %    used involving the same models.
+0044 %
+0045 % Usage: newModel=addRxnsGenesMets(model,sourceModel,rxns,addGene,rxnNote,confidence)
+0046 
+0047 if nargin<6
+0048     confidence=0;
+0049 end
+0050 rxns=convertCharArray(rxns);
+0051 if nargin<5
+0052     rxnNote={'Added via addRxnsGenesMets()'};
+0053 else
+0054     rxnNote=convertCharArray(rxnNote);
+0055 end
+0056 if numel(rxnNote)==1 && numel(rxns)>1
+0057     rxnNoteArray=cell(1,numel(rxns));
+0058     rxnNoteArray(:)=rxnNote;
+0059     rxnNote=rxnNoteArray;
+0060 end
+0061 if nargin<4
+0062     addGene=false;
+0063 end
+0064 
+0065 % Obtain indexes of reactions in source model
+0066 [notNewRxn,oldRxn]=ismember(rxns,model.rxns);
+0067 rxns=rxns(~notNewRxn);
+0068 if isempty(rxns)
+0069     error('All reactions are already in the model.');
+0070 elseif ~isempty(notNewRxn)
+0071     fprintf('The following reactions were already present in the model and will not be added:\n')
+0072     fprintf([strjoin(model.rxns(oldRxn(find(oldRxn))),'\n') '\n'])
+0073 end
+0074 
+0075 [~, rxnIdx]=ismember(rxns,sourceModel.rxns); % Get rxnIDs
+0076 if any(rxnIdx==0)
+0077     dispEM('The following reaction IDs could not be found in the source model:',true,...
+0078         rxns(rxnIdx==0));
+0079 end
+0080 
+0081 % Add new metabolites
+0082 metIdx=find(any(sourceModel.S(:,rxnIdx),2)); % Get metabolite IDs
+0083 % Many of the metabolites in are already in the draft model, so only add
+0084 % the new metabolites
+0085 
+0086 % Match by metNames[metComps]. First make these structures for each model.
+0087 metCompsN =cellstr(num2str(model.metComps));
+0088 map=containers.Map(cellstr(num2str(transpose([1:length(model.comps)]))),model.comps);
+0089 metCompsN = map.values(metCompsN);
+0090 metCompsN = strcat(model.metNames,'[',metCompsN,']');
+0091 
+0092 sourcemetCompsN=cellstr(num2str(sourceModel.metComps));
+0093 map=containers.Map(cellstr(num2str(transpose([1:length(sourceModel.comps)]))),sourceModel.comps);
+0094 sourcemetCompsN = map.values(sourcemetCompsN);
+0095 sourcemetCompsN=strcat(sourceModel.metNames,'[',sourcemetCompsN,']');
+0096 
+0097 newMetCompsN=sourcemetCompsN(metIdx);
+0098 notNewMet=newMetCompsN(ismember(newMetCompsN,metCompsN));
+0099 
+0100 if ~isempty(notNewMet)
+0101     fprintf('\nThe following metabolites were already present in the model and will not be added:\n')
+0102     fprintf([strjoin(transpose(notNewMet),'\n') '\n'])
+0103 end
+0104 
+0105 metIdx=metIdx(~ismember(sourcemetCompsN(metIdx),metCompsN));
+0106 
+0107 if ~isempty(metIdx)
+0108     fprintf('\nThe following metabolites will be added to the model:\n')
+0109     fprintf([strjoin(transpose(sourcemetCompsN(metIdx)),'\n') '\n'])
+0110     
+0111     if isfield(sourceModel,'mets')
+0112         metsToAdd.mets=sourceModel.mets(metIdx);
+0113     end
+0114     if isfield(sourceModel,'metNames')
+0115         metsToAdd.metNames=sourceModel.metNames(metIdx);
+0116     end
+0117     if isfield(sourceModel,'metFormulas')
+0118         metsToAdd.metFormulas=sourceModel.metFormulas(metIdx);
+0119     end
+0120     if isfield(sourceModel,'metCharges')
+0121         metsToAdd.metCharges=sourceModel.metCharges(metIdx);
+0122     end
+0123     if isfield(sourceModel,'metMiriams')
+0124         metsToAdd.metMiriams=sourceModel.metMiriams(metIdx);
+0125     end
+0126     if isfield(sourceModel,'metNotes')
+0127         metsToAdd.metNotes=sourceModel.metNotes(metIdx);
+0128     end
+0129     if isfield(sourceModel,'inchis')
+0130         metsToAdd.inchis=sourceModel.inchis(metIdx);
+0131     end
+0132     if isfield(sourceModel,'metSmiles')
+0133         metsToAdd.metSmiles=sourceModel.metSmiles(metIdx);
+0134     end
+0135     if isfield(sourceModel,'metDeltaG')
+0136         metsToAdd.metDeltaG=sourceModel.metDeltaG(metIdx);
+0137     end
+0138     
+0139     metsToAdd.compartments=strtrim(cellstr(num2str(sourceModel.metComps(metIdx)))); % Convert from compartment string to compartment number
+0140     [~,idx]=ismember(metsToAdd.compartments,strsplit(num2str(1:length(sourceModel.comps)))); % Match compartment number to compartment abbreviation
+0141     metsToAdd.compartments=sourceModel.comps(idx); % Fill in compartment abbreviations
+0142     
+0143     model=addMets(model,metsToAdd);
+0144 end
+0145 fprintf('\nNumber of metabolites added to the model:\n')
+0146 fprintf([num2str(numel(metIdx)),'\n'])
+0147 
+0148 % Add new genes
+0149 if ~islogical(addGene) | addGene ~= false
+0150     if ischar(addGene)
+0151         rxnToAdd.grRules={addGene};
+0152     elseif iscell(addGene)
+0153         rxnToAdd.grRules=addGene(~notNewRxn); 
+0154     else
+0155         rxnToAdd.grRules=sourceModel.grRules(rxnIdx); % Get the relevant grRules
+0156     end
+0157 end
+0158 % Add new reactions
+0159 rxnToAdd.equations=constructEquations(sourceModel,rxnIdx);
+0160 rxnToAdd.rxnNames=sourceModel.rxnNames(rxnIdx);
+0161 rxnToAdd.rxns=sourceModel.rxns(rxnIdx);
+0162 rxnToAdd.lb=sourceModel.lb(rxnIdx);
+0163 rxnToAdd.ub=sourceModel.ub(rxnIdx);
+0164 rxnToAdd.rxnNotes(:)=rxnNote(~notNewRxn);
+0165 rxnToAdd.rxnConfidenceScores=NaN(1,numel(rxnToAdd.rxns));
+0166 if ~isnumeric(confidence)
+0167     EM='confidence score must be numeric';
+0168     dispEM(EM, true);
+0169 end
+0170 rxnToAdd.rxnConfidenceScores(:)=confidence;
+0171 if isfield(sourceModel,'rxnDeltaG')
+0172     rxnToAdd.rxnDeltaG=sourceModel.rxnDeltaG(rxnIdx);
+0173 end
+0174 if isfield(sourceModel,'subSystems')
+0175     rxnToAdd.subSystems=sourceModel.subSystems(rxnIdx);
+0176 end
+0177 if isfield(sourceModel,'eccodes')
+0178     rxnToAdd.eccodes=sourceModel.eccodes(rxnIdx);
+0179 end
+0180 model=addRxns(model,rxnToAdd,3,'',false,true);
+0181 
+0182 fprintf('\nNumber of reactions added to the model:\n')
+0183 fprintf([num2str(numel(rxnIdx)),'\n'])
+0184 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/addTransport.html b/doc/core/addTransport.html new file mode 100644 index 000000000..21b58cbe2 --- /dev/null +++ b/doc/core/addTransport.html @@ -0,0 +1,250 @@ + + + + Description of addTransport + + + + + + + + + +
Home > core > addTransport.m
+ + + +

addTransport +

+ +

PURPOSE ^

+
addTransport
+ +

SYNOPSIS ^

+
function [model, addedRxns]=addTransport(model,fromComp,toComps,metNames,isRev,onlyToExisting,prefix)
+ +

DESCRIPTION ^

+
 addTransport
+   Adds transport reactions between compartments
+
+   model           a model structure
+   fromComp        the id of the compartment to transport from (should
+                   match model.comps)
+   toComps         a cell array of compartment names to transport to (should
+                   match model.comps)
+   metNames        the metabolite names to add transport for (optional, all
+                   metabolites in fromComp)
+   isRev           true if the transport reactions should be reversible
+                   (optional, default true)
+   onlyToExisting  true if transport of a metabolite should only be added
+                   if it already exists in toComp. If false, then new metabolites
+                   are added with addMets first (optional, default true)
+   prefix          string specifying prefix to reaction IDs (optional, default
+                   'tr_')
+
+   This is a faster version than addRxns when adding transport reactions.
+   New reaction names are formatted as "metaboliteName, fromComp-toComp", 
+   while new reaction IDs are sequentially counted with a tr_ prefix:
+   e.g. tr_0001, tr_0002, etc.
+
+ Usage: [model, addedRxns]=addTransport(model,fromComp,toComps,metNames,...
+           isRev,onlyToExisting,prefix)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function [model, addedRxns]=addTransport(model,fromComp,toComps,metNames,isRev,onlyToExisting,prefix)
+0002 % addTransport
+0003 %   Adds transport reactions between compartments
+0004 %
+0005 %   model           a model structure
+0006 %   fromComp        the id of the compartment to transport from (should
+0007 %                   match model.comps)
+0008 %   toComps         a cell array of compartment names to transport to (should
+0009 %                   match model.comps)
+0010 %   metNames        the metabolite names to add transport for (optional, all
+0011 %                   metabolites in fromComp)
+0012 %   isRev           true if the transport reactions should be reversible
+0013 %                   (optional, default true)
+0014 %   onlyToExisting  true if transport of a metabolite should only be added
+0015 %                   if it already exists in toComp. If false, then new metabolites
+0016 %                   are added with addMets first (optional, default true)
+0017 %   prefix          string specifying prefix to reaction IDs (optional, default
+0018 %                   'tr_')
+0019 %
+0020 %   This is a faster version than addRxns when adding transport reactions.
+0021 %   New reaction names are formatted as "metaboliteName, fromComp-toComp",
+0022 %   while new reaction IDs are sequentially counted with a tr_ prefix:
+0023 %   e.g. tr_0001, tr_0002, etc.
+0024 %
+0025 % Usage: [model, addedRxns]=addTransport(model,fromComp,toComps,metNames,...
+0026 %           isRev,onlyToExisting,prefix)
+0027 
+0028 fromComp=char(fromComp);
+0029 [I, fromID]=ismember(model.comps,fromComp);
+0030 fromID=find(fromID);
+0031 if sum(I)~=1
+0032     EM='fromComps must have exactly one match in model.comps';
+0033     dispEM(EM);
+0034 end
+0035 toComps=convertCharArray(toComps);
+0036 [I, toIDs]=ismember(toComps,model.comps);
+0037 if ~all(I)
+0038     EM='All compartments in toComps must have a match in model.comps';
+0039     dispEM(EM);
+0040 end
+0041 if nargin<4
+0042     %Find all metabolites in fromComp
+0043     metNames=model.metNames(model.metComps==fromID);
+0044 elseif isempty(metNames)
+0045     %Find all metabolites in fromComp
+0046     metNames=model.metNames(ismember(model.metComps,model.comps(fromID)));
+0047 else
+0048     metNames=convertCharArray(metNames);
+0049 end
+0050 
+0051 if nargin<5
+0052     isRev=true;
+0053 end
+0054 if nargin<6
+0055     onlyToExisting=true;
+0056 end
+0057 if nargin<7
+0058     prefix='tr_';
+0059 else
+0060     prefix=char(prefix);
+0061 end
+0062 
+0063 %Check that the names are unique
+0064 if numel(unique(metNames))~=numel(metNames)
+0065     dispEM('Not all metabolite names are unique');
+0066 end
+0067 
+0068 %Get the indexes of the mets in fromComp
+0069 I=find(model.metComps==fromID);
+0070 [J, K]=ismember(metNames,model.metNames(I));
+0071 if ~all(J)
+0072     EM='Not all metabolites in metNames exist in fromComp';
+0073     dispEM(EM);
+0074 end
+0075 fromMets=I(K); %These are the ids of the metabolites to transport. The order corresponds to metNames
+0076 addedRxns={};
+0077 %Loop through and add for each compartment in toComps
+0078 for i=1:numel(toComps)
+0079     fromMetsInComp=fromMets; %If onlyToExisting==true then not all mets are transported to each compartment
+0080     %Get the indexes of the mets in the compartment
+0081     I=find(model.metComps==toIDs(i));
+0082     [J, K]=ismember(metNames,model.metNames(I));
+0083     if onlyToExisting==true || all(J)
+0084         toMets=I(K(J)); %Only look at the existing ones
+0085         fromMetsInComp=fromMetsInComp(J);
+0086     else
+0087         %This is if not all metabolites exist in the target compartment,
+0088         %and they should be added
+0089         metsToAdd.metNames=metNames(J==0);
+0090         metsToAdd.compartments=toComps{i};
+0091         model=addMets(model,metsToAdd);
+0092         
+0093         %Redo the mapping when all mets are there. A bit lazy, but it's
+0094         %fast anyways
+0095         I=find(model.metComps==toIDs(i));
+0096         [~, K]=ismember(metNames,model.metNames(I));
+0097         toMets=I(K); %All are guaranteed to be found now
+0098     end
+0099     
+0100     %Construct the S matrix
+0101     nRxns=numel(fromMetsInComp);
+0102     newS=zeros(numel(model.mets),nRxns);
+0103     newS(sub2ind(size(newS),fromMetsInComp(:),(1:nRxns)'))=-1;
+0104     newS(sub2ind(size(newS),toMets(:),(1:nRxns)'))=1;
+0105     
+0106     %Add the reactions
+0107     model.S=[model.S sparse(newS)];
+0108     if isfield(model.annotation,'defaultLB')
+0109         lb = model.annotation.defaultLB;
+0110         ub = model.annotation.defaultUB;
+0111     else
+0112         lb = -inf;
+0113         ub = inf;
+0114     end
+0115     if isRev==true
+0116         model.lb=[model.lb;ones(nRxns,1)*lb];
+0117         model.rev=[model.rev;ones(nRxns,1)];
+0118     else
+0119         model.lb=[model.lb;zeros(nRxns,1)];
+0120         model.rev=[model.rev;zeros(nRxns,1)];
+0121     end
+0122     model.ub=[model.ub;ones(nRxns,1)*ub];
+0123     model.c=[model.c;zeros(nRxns,1)];
+0124     
+0125     %Add annotation
+0126     filler=cell(nRxns,1);
+0127     filler(:)={''};
+0128     addedRxnsID=generateNewIds(model,'rxns',prefix,nRxns);
+0129     addedRxnsName=transpose(strcat(metNames, {' transport, '}, model.compNames(fromID), '-', model.compNames(toIDs(i))));
+0130     model.rxns=[model.rxns;addedRxnsID];
+0131     model.rxnNames=[model.rxnNames;addedRxnsName];
+0132     
+0133     if isfield(model,'eccodes')
+0134         model.eccodes=[model.eccodes;filler];
+0135     end
+0136     if isfield(model,'subSystems')
+0137         isNested = any(cellfun(@(x) iscell(x), model.subSystems));
+0138         ssFiller = filler;
+0139         if isRev==1
+0140             ssFiller(:) = {['Transport between ' fromComp ' and ' toComps{i}]};
+0141         else
+0142             ssFiller(:) = {['Transport from ' fromComp ' to ' toComps{i}]};
+0143         end
+0144         if isNested
+0145             ssFiller = cellfun(@(x) {x}, ssFiller, 'uni', 0);
+0146         end
+0147         model.subSystems=[model.subSystems;ssFiller];
+0148     end
+0149     if isfield(model,'grRules')
+0150         model.grRules=[model.grRules;filler];
+0151     end
+0152     if isfield(model,'rxnFrom')
+0153         model.rxnFrom=[model.rxnFrom;filler];
+0154     end
+0155     if isfield(model,'rxnMiriams')
+0156         model.rxnMiriams=[model.rxnMiriams;cell(nRxns,1)];
+0157     end
+0158     if isfield(model,'rxnComps')
+0159         model.rxnComps=[model.rxnComps;ones(nRxns,1)];
+0160         fprintf('NOTE: The added transport reactions will be added to the first compartment\n');
+0161     end
+0162     if isfield(model,'rxnGeneMat')
+0163         model.rxnGeneMat=[model.rxnGeneMat;sparse(nRxns,numel(model.genes))];
+0164     end
+0165     if isfield(model,'rxnNotes')
+0166         model.rxnNotes=[model.rxnNotes;filler];
+0167     end
+0168     if isfield(model,'rxnReferences')
+0169         model.rxnReferences=[model.rxnReferences;filler];
+0170     end
+0171     if isfield(model,'rxnConfidenceScores')
+0172         model.rxnConfidenceScores=[model.rxnConfidenceScores;ones(nRxns,1)];
+0173     end
+0174     if isfield(model,'rxnDeltaG')
+0175         model.rxnDeltaG=[model.rxnDeltaG;zeros(nRxns,1)];
+0176     end
+0177     addedRxns = [addedRxns; addedRxnsID];
+0178 end
+0179 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/analyzeSampling.html b/doc/core/analyzeSampling.html new file mode 100644 index 000000000..8394c477b --- /dev/null +++ b/doc/core/analyzeSampling.html @@ -0,0 +1,250 @@ + + + + Description of analyzeSampling + + + + + + + + + +
Home > core > analyzeSampling.m
+ + + +

analyzeSampling +

+ +

PURPOSE ^

+
analyzeSampling
+ +

SYNOPSIS ^

+
function scores=analyzeSampling(Tex, df, solutionsA, solutionsB, printResults)
+ +

DESCRIPTION ^

+
 analyzeSampling
+   Compares the significance of change in flux between two conditions with
+   the significance of change in gene expression
+
+   Tex             a vector of t-scores for the change in gene expression
+                   for each reaction. This score could be the Student t
+                   between the two conditions, or you can calculate it from
+                   a p-value (by computing the inverse of the so called error
+                   function). If you choose the second alternative you should
+                   be aware that the transcripts that increased in expression
+                   level should have positive values and those who decreased
+                   in expression level should have negative values (the
+                   p-values only tell you if the fluxes changed or not but
+                   not in which direction)
+   df              the degrees of freedom in the t-test
+   solutionsA      random solutions for the reference condition (as
+                   generated by randomSampling)
+   solutionsB      random solutions for the test condition (as generated
+                   by randomSampling)
+   printResults    prints the most significant reactions in each category
+                   (optional, default false)
+
+   scores          a Nx3 column matrix with the probabilities of a reaction:
+                   1) changing both in flux and expression in the same direction
+                   2) changing in expression but not in flux
+                   3) changing in flux but not in expression or changing
+                      in opposed directions in flux and expression.
+
+ Usage: scores=analyzeSampling(Tex, df, solutionsA, solutionsB, printResults)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 function scores=analyzeSampling(Tex, df, solutionsA, solutionsB, printResults)
+0002 % analyzeSampling
+0003 %   Compares the significance of change in flux between two conditions with
+0004 %   the significance of change in gene expression
+0005 %
+0006 %   Tex             a vector of t-scores for the change in gene expression
+0007 %                   for each reaction. This score could be the Student t
+0008 %                   between the two conditions, or you can calculate it from
+0009 %                   a p-value (by computing the inverse of the so called error
+0010 %                   function). If you choose the second alternative you should
+0011 %                   be aware that the transcripts that increased in expression
+0012 %                   level should have positive values and those who decreased
+0013 %                   in expression level should have negative values (the
+0014 %                   p-values only tell you if the fluxes changed or not but
+0015 %                   not in which direction)
+0016 %   df              the degrees of freedom in the t-test
+0017 %   solutionsA      random solutions for the reference condition (as
+0018 %                   generated by randomSampling)
+0019 %   solutionsB      random solutions for the test condition (as generated
+0020 %                   by randomSampling)
+0021 %   printResults    prints the most significant reactions in each category
+0022 %                   (optional, default false)
+0023 %
+0024 %   scores          a Nx3 column matrix with the probabilities of a reaction:
+0025 %                   1) changing both in flux and expression in the same direction
+0026 %                   2) changing in expression but not in flux
+0027 %                   3) changing in flux but not in expression or changing
+0028 %                      in opposed directions in flux and expression.
+0029 %
+0030 % Usage: scores=analyzeSampling(Tex, df, solutionsA, solutionsB, printResults)
+0031 
+0032 if nargin<5
+0033     printResults=false;
+0034 end
+0035 
+0036 nRxns=numel(Tex);
+0037 pM=zeros(nRxns,1);
+0038 pH=zeros(nRxns,1);
+0039 pR=zeros(nRxns,1);
+0040 
+0041 %Check that the number of reactions is the same in both expression and flux
+0042 if nRxns~=size(solutionsA,1)
+0043     EM='The number of reactions must be the same in Tex as in solutionsA';
+0044     dispEM(EM);
+0045 end
+0046 
+0047 %Get the Z-score and mean for the solutions
+0048 mA=mean(solutionsA,2);
+0049 mB=mean(solutionsB,2);
+0050 Zf=getFluxZ(solutionsA, solutionsB);
+0051 
+0052 %Clear up the tex if there are elements that are NaN or +/- Inf.
+0053 I=isnan(Tex) | isinf(Tex);
+0054 if any(I)
+0055     EM='There are t-scores that are NaN or +/- Inf. These values are changed to 0.0';
+0056     dispEM(EM,false);
+0057 end
+0058 Tex(I)=0;
+0059 
+0060 for i=1:nRxns
+0061     %Check how the flux has changed. The means are needed because to
+0062     %differentiate between a positive flux changing to a smaller flux and a
+0063     %negative flux changing to a more negative flux (which is a larger
+0064     %flux)
+0065     I=mB(i)/mA(i);
+0066     if I<0
+0067         pM(i)=erf(abs(Zf(i)));
+0068         pH(i)=(1-pM(i))*(2*tcdf(abs(Tex(i)),df)-1);
+0069         pR(i)=0;
+0070     else
+0071         if mB(i)<0
+0072             Zf(i)=Zf(i)*-1;
+0073         end
+0074     end
+0075 
+0076     I=Zf(i)/Tex(i);
+0077     if I<0
+0078         pM(i)=erf(abs(Zf(i)));
+0079         pH(i)=(1-pM(i))*(2*tcdf(abs(Tex(i)),df)-1);
+0080         pR(i)=0;
+0081     else
+0082         pR(i)=erf(abs(Zf(i)))*(2*tcdf(abs(Tex(i)),df)-1);
+0083         pH(i)=(2*tcdf(abs(Tex(i)),df)-1)*(1-erf(abs(Zf(i))));
+0084         pM(i)=erf(abs(Zf(i)))*(1-(2*tcdf(abs(Tex(i)),df)-1));
+0085     end
+0086 end
+0087 
+0088 scores=[pR pH pM];
+0089 
+0090 if printResults==true
+0091     fprintf('TOP SCORING REACTIONS\n\n');
+0092     %The top 10 hits in the first category
+0093     [I, J]=sort(pR,'descend');
+0094     fprintf('Reactions which change both in flux and expression in the same direction\nReaction\tProbability\n');
+0095     for i=1:10
+0096         fprintf([num2str(J(i)) '\t' num2str(I(i)) '\n']);
+0097     end
+0098 
+0099     %The top 10 hits in the first category
+0100     [I, J]=sort(pH,'descend');
+0101     fprintf('\nReactions which change in expression but not in flux\nReaction\tProbability\n');
+0102     for i=1:10
+0103         fprintf([num2str(J(i)) '\t' num2str(I(i)) '\n']);
+0104     end
+0105 
+0106     %The top 10 hits in the first category
+0107     [I, J]=sort(pM,'descend');
+0108     fprintf('\nReactions which change in flux but not in expression, or in opposed directions in flux and expression\nReaction\tProbability\n');
+0109     for i=1:10
+0110         fprintf([num2str(J(i)) '\t' num2str(I(i)) '\n']);
+0111     end
+0112 end
+0113 end
+0114 
+0115 function p = tcdf(t,v,uflag)
+0116 % TCDF Student's T cumulative distribution function (cdf).
+0117 %
+0118 % P = TCDF(X,V) computes the cdf for Student's T distribution
+0119 % with V degrees of freedom, at the values in X. V must be a
+0120 % scalar or have the same size as T.
+0121 %
+0122 % P = TCDF(X,V,'upper') computes it for the upper tail instead
+0123 % of the lower tail.
+0124 %
+0125 % This is an alternative to the TCDF function that is implemented
+0126 % in the Matlab statistics toolbox. This version originates from
+0127 % http://www.statsci.org/matlab/statbox.html and originally was called TP.
+0128 % It has been renamed to TCDF for drop-in compatibility with the Matlab
+0129 % version.
+0130 %
+0131 % Gordon Smyth, University of Queensland, gks@maths.uq.edu.au
+0132 % 3 Apr 97
+0133 %
+0134 % NaN compatible - Markus Bauer and Eric Maris, FCDC
+0135 % 27 Jan 2005
+0136 %
+0137 % fixed bug concerning NaN compatibility
+0138 % 21 Aug 2006, Markus Siegel
+0139 %
+0140 % added support for upper tail, see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=3045
+0141 % 13 Jan 2016, Robert Oostenveld
+0142 %
+0143 % taken from https://github.com/fieldtrip/fieldtrip/blob/master/external/stats/tcdf.m
+0144 % 05 May 2022
+0145 
+0146 if v <= 0, error('Degrees of freedom must be positive.'); end
+0147 
+0148 % resize v if necessary
+0149 if all(size(v)==1)
+0150     v = ones(size(t))*v;
+0151 end
+0152 
+0153 %check for NaN's - don't do calculations on them, give those out as NaNs
+0154 if any( not(isfinite(t(:))) | not(isfinite(v(:))) )
+0155     sel = find(isfinite(t) & isfinite(v));
+0156     x=nan(size(t));
+0157     p=nan(size(t));
+0158     x(sel) = t(sel).^2 ./ (v(sel) + t(sel).^2) ;
+0159     p(sel) = 0.5 .* ( 1 + sign(t(sel)) .* betainc( x(sel), 0.5, 0.5*v(sel) ) );
+0160 else
+0161     x = t.^2 ./ (v + t.^2) ;
+0162     p = 0.5 .* ( 1 + sign(t) .* betainc( x, 0.5, 0.5*v ) );
+0163 end
+0164 
+0165 if nargin==3
+0166     if strcmp(uflag, 'upper')
+0167         % compute it for the upper tail instead of the lower tail
+0168         p = 1-p;
+0169     else
+0170         error('incorrect specification of uflag');
+0171     end
+0172 end
+0173 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/buildEquation.html b/doc/core/buildEquation.html new file mode 100644 index 000000000..af52df23d --- /dev/null +++ b/doc/core/buildEquation.html @@ -0,0 +1,122 @@ + + + + Description of buildEquation + + + + + + + + + +
Home > core > buildEquation.m
+ + + +

buildEquation +

+ +

PURPOSE ^

+
buildEquation
+ +

SYNOPSIS ^

+
function equationString=buildEquation(mets,stoichCoeffs,isrev)
+ +

DESCRIPTION ^

+
 buildEquation
+   Construct single equation string for a given reaction
+
+   mets            cell array with metabolites involved in the reaction.
+   stoichCoeffs    vector with corresponding stoichiometric coeffs.
+   isrev           logical indicating if the reaction is or not
+                   reversible.
+
+   equationString  equation as a string
+
+    Usage: equationString=buildEquation(mets,stoichCoeffs,isrev)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 function equationString=buildEquation(mets,stoichCoeffs,isrev)
+0002 % buildEquation
+0003 %   Construct single equation string for a given reaction
+0004 %
+0005 %   mets            cell array with metabolites involved in the reaction.
+0006 %   stoichCoeffs    vector with corresponding stoichiometric coeffs.
+0007 %   isrev           logical indicating if the reaction is or not
+0008 %                   reversible.
+0009 %
+0010 %   equationString  equation as a string
+0011 %
+0012 %    Usage: equationString=buildEquation(mets,stoichCoeffs,isrev)
+0013 
+0014 mets=convertCharArray(mets);
+0015 if ~isnumeric(stoichCoeffs)
+0016     EM = 'stoichCoeffs must be a numeric vector';
+0017     dispEM(EM);
+0018 elseif ~islogical(isrev)
+0019     EM = 'isrev must be a logical';
+0020     dispEM(EM);
+0021 elseif length(mets) ~= length(stoichCoeffs)
+0022     EM = 'lengths of mets and stoichCoeffs should be the same';
+0023     dispEM(EM);
+0024 end
+0025 
+0026 %Reactant half:
+0027 reactants       = mets(stoichCoeffs<0);
+0028 reactantsCoeffs = abs(stoichCoeffs(stoichCoeffs<0));
+0029 reactantsEqn    = concatenateEquation(reactants,reactantsCoeffs);
+0030 
+0031 %Product half:
+0032 products       = mets(stoichCoeffs>0);
+0033 productsCoeffs = abs(stoichCoeffs(stoichCoeffs>0));
+0034 productsEqn    = concatenateEquation(products,productsCoeffs);
+0035 
+0036 %Full equation:
+0037 if isrev
+0038     equationString = [reactantsEqn ' <=> ' productsEqn];
+0039 else
+0040     equationString = [reactantsEqn ' => ' productsEqn];
+0041 end
+0042 
+0043 end
+0044 
+0045 function eqn = concatenateEquation(mets,stoichCoeffs)
+0046 %This function concatenates metabolites and stoich. coefficients to form
+0047 %either the left or right side of the rxn equation
+0048 eqn = '';
+0049 for i = 1:length(stoichCoeffs)
+0050     if i == 1
+0051         plusString='';
+0052     else
+0053         plusString=' + ';
+0054     end
+0055     stoich = stoichCoeffs(i);
+0056     if stoich == 1
+0057         stoich = '';
+0058     else
+0059         stoich = [num2str(stoich) ' '];
+0060     end
+0061     eqn = [eqn plusString stoich mets{i}];
+0062 end
+0063 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/canConsume.html b/doc/core/canConsume.html new file mode 100644 index 000000000..bedcde3c9 --- /dev/null +++ b/doc/core/canConsume.html @@ -0,0 +1,83 @@ + + + + Description of canConsume + + + + + + + + + +
Home > core > canConsume.m
+ + + +

canConsume +

+ +

PURPOSE ^

+
canConsume
+ +

SYNOPSIS ^

+
function consumed=canConsume(model,mets)
+ +

DESCRIPTION ^

+
 canConsume
+   Checks which metabolites that can be consumed by a model using the
+   specified constraints
+
+   model       a model structure
+   mets        either a cell array of metabolite IDs, a logical vector 
+               with the same number of elements as metabolites in the model,
+               or a vector of indexes to check for (optional, default model.mets)
+
+   consumed    vector with true if the corresponding metabolite could be
+               produced
+
+ Usage: consumed=canConsume(model,mets)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function consumed=canConsume(model,mets)
+0002 % canConsume
+0003 %   Checks which metabolites that can be consumed by a model using the
+0004 %   specified constraints
+0005 %
+0006 %   model       a model structure
+0007 %   mets        either a cell array of metabolite IDs, a logical vector
+0008 %               with the same number of elements as metabolites in the model,
+0009 %               or a vector of indexes to check for (optional, default model.mets)
+0010 %
+0011 %   consumed    vector with true if the corresponding metabolite could be
+0012 %               produced
+0013 %
+0014 % Usage: consumed=canConsume(model,mets)
+0015 
+0016 if nargin<2
+0017     mets=model.mets;
+0018 elseif ~islogical(mets) && ~isnumeric(mets)
+0019     mets=convertCharArray(mets);
+0020 end
+0021 
+0022 [model, rxns]=addExchangeRxns(model,'in',mets);
+0023 consumed=haveFlux(model,10^-5,rxns);
+0024 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/canProduce.html b/doc/core/canProduce.html new file mode 100644 index 000000000..40f9f0346 --- /dev/null +++ b/doc/core/canProduce.html @@ -0,0 +1,85 @@ + + + + Description of canProduce + + + + + + + + + +
Home > core > canProduce.m
+ + + +

canProduce +

+ +

PURPOSE ^

+
canProduce
+ +

SYNOPSIS ^

+
function produced=canProduce(model,mets)
+ +

DESCRIPTION ^

+
 canProduce
+   Checks which metabolites that can be produced from a model using the
+   specified constraints. This is a less advanced but faster version of
+   checkProduction.
+
+   model       a model structure
+   mets        either a cell array of metabolite IDs, a logical vector 
+               with the same number of elements as metabolites in the model,
+               or a vector of indexes to check for (optional, default model.mets)
+
+   produced    vector with true if the corresponding metabolite could be
+               produced
+
+ Usage: produced=canProduce(model,mets)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function produced=canProduce(model,mets)
+0002 % canProduce
+0003 %   Checks which metabolites that can be produced from a model using the
+0004 %   specified constraints. This is a less advanced but faster version of
+0005 %   checkProduction.
+0006 %
+0007 %   model       a model structure
+0008 %   mets        either a cell array of metabolite IDs, a logical vector
+0009 %               with the same number of elements as metabolites in the model,
+0010 %               or a vector of indexes to check for (optional, default model.mets)
+0011 %
+0012 %   produced    vector with true if the corresponding metabolite could be
+0013 %               produced
+0014 %
+0015 % Usage: produced=canProduce(model,mets)
+0016 
+0017 if nargin<2
+0018     mets=model.mets;
+0019 elseif ~islogical(mets) && ~isnumeric(mets)
+0020     mets=convertCharArray(mets);
+0021 end
+0022 
+0023 [model, rxns]=addExchangeRxns(model,'out',mets);
+0024 produced=haveFlux(model,10^-5,rxns);
+0025 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/changeGrRules.html b/doc/core/changeGrRules.html new file mode 100644 index 000000000..82d3ea2c7 --- /dev/null +++ b/doc/core/changeGrRules.html @@ -0,0 +1,116 @@ + + + + Description of changeGrRules + + + + + + + + + +
Home > core > changeGrRules.m
+ + + +

changeGrRules +

+ +

PURPOSE ^

+
changeGrRules
+ +

SYNOPSIS ^

+
function model = changeGrRules(model,rxns,grRules,replace)
+ +

DESCRIPTION ^

+
 changeGrRules
+   Changes multiple grRules at the same time.
+
+   model       a model structure to change the gene association
+   rxns        string or cell array of reaction IDs
+   grRules     string of additional or replacement gene association.
+               Should be written with ' and ' to indicate subunits, ' or '
+               to indicate isoenzymes, and brackets '()' to separate
+               different instances
+   replace     true if old gene association should be replaced with new
+               association. False if new gene association should be
+               concatenated to the old association (optional, default true)
+
+   model       an updated model structure
+
+ Usage: changeGrRules(model,rxns,grRules,replace)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function model = changeGrRules(model,rxns,grRules,replace)
+0002 % changeGrRules
+0003 %   Changes multiple grRules at the same time.
+0004 %
+0005 %   model       a model structure to change the gene association
+0006 %   rxns        string or cell array of reaction IDs
+0007 %   grRules     string of additional or replacement gene association.
+0008 %               Should be written with ' and ' to indicate subunits, ' or '
+0009 %               to indicate isoenzymes, and brackets '()' to separate
+0010 %               different instances
+0011 %   replace     true if old gene association should be replaced with new
+0012 %               association. False if new gene association should be
+0013 %               concatenated to the old association (optional, default true)
+0014 %
+0015 %   model       an updated model structure
+0016 %
+0017 % Usage: changeGrRules(model,rxns,grRules,replace)
+0018 
+0019 if nargin==3
+0020     replace=true;
+0021 end
+0022 
+0023 rxns=convertCharArray(rxns);
+0024 grRules=convertCharArray(grRules);
+0025 
+0026 if isscalar(grRules) && ~isscalar(rxns)
+0027     grRules = repmat(grRules,1,numel(rxns));
+0028 end
+0029 if ~(numel(grRules)==numel(rxns))
+0030     error('Number of rxns and grRules should be identical')
+0031 end
+0032 
+0033 % Add genes to model
+0034 geneList = getGenesFromGrRules(grRules);
+0035 genesToAdd.genes=setdiff(geneList,model.genes); % Only keep the genes that are not yet part of the model.genes.
+0036 if ~isempty(genesToAdd.genes)
+0037     model=addGenesRaven(model,genesToAdd); % Add genes
+0038 end
+0039     
+0040 % Find reaction and gene indices
+0041 idx=getIndexes(model,rxns,'rxns');
+0042 
+0043 % Change gene associations
+0044 if replace==true % Replace old gene associations
+0045     model.grRules(idx)=grRules;
+0046 else % Add gene associations, add new gene rules after 'OR'.
+0047     model.grRules(idx)=strcat('(',model.grRules(idx),') or (',grRules,')');
+0048 end
+0049 
+0050 %Fix grRules and reconstruct rxnGeneMat
+0051 [grRules,rxnGeneMat] = standardizeGrRules(model,true);
+0052 model.grRules = grRules;
+0053 model.rxnGeneMat = rxnGeneMat;
+0054 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/changeRxns.html b/doc/core/changeRxns.html new file mode 100644 index 000000000..fb5927ca2 --- /dev/null +++ b/doc/core/changeRxns.html @@ -0,0 +1,249 @@ + + + + Description of changeRxns + + + + + + + + + +
Home > core > changeRxns.m
+ + + +

changeRxns +

+ +

PURPOSE ^

+
changeRxns
+ +

SYNOPSIS ^

+
function model=changeRxns(model,rxns,equations,eqnType,compartment,allowNewMets)
+ +

DESCRIPTION ^

+
 changeRxns
+   Modifies the equations of reactions
+
+   model            a model structure
+   rxns             cell array with reaction ids
+   equations        cell array with equations. Alternatively, it can be a
+                    structure with the fields "mets" and "stoichCoeffs",
+                    in the same fashion as addRxns. E.g.:
+                    equations.mets = {{'met1','met2'},{'met1','met3'}}
+                    equations.stoichCoeffs = {[-1,+2],[-1,+1]}
+   eqnType          double describing how the equation string should be
+                    interpreted
+                    1 - The metabolites are matched to model.mets. New
+                        metabolites (if allowed) are added to
+                        "compartment" (default)
+                    2 - The metabolites are matched to model.metNames and
+                        all metabolites are assigned to "compartment". Any
+                        new metabolites that are added will be assigned
+                        IDs "m1", "m2"... If IDs on the same form are
+                        already used in the model then the numbering will
+                        start from the highest used integer+1
+                    3 - The metabolites are written as
+                        "metNames[compNames]". Only compartments in
+                        model.compNames are allowed. Any
+                        new metabolites that are added will be assigned
+                        IDs "m1", "m2"... If IDs on the same form are
+                        already used in the model then the numbering will
+                        start from the highest used integer+1
+   compartment      a string with the compartment the metabolites should
+                    be placed in when using eqnType=2. Must match
+                    model.compNames (optional when eqnType=1 or eqnType=3)
+   allowNewMets     true if the function is allowed to add new
+                    metabolites. It is highly recommended to first add
+                    any new metabolites with addMets rather than
+                    automatically through this function. addMets supports
+                    more annotation of metabolites, allows for the use of
+                    exchange metabolites, and using it reduces the risk
+                    of parsing errors (optional, default false)
+
+   model            an updated model structure
+
+   NOTE: This function should be used with some care, since it doesn't
+   care about bounds on the reactions. Changing a irreversible reaction to
+   a reversible one (or the other way around) will only change the
+   model.rev field and not the model.lb/model.ub fields. The reaction will
+   therefore still be having the same reversibility because of the
+   bounds. Use setParams to change the bounds.
+
+   NOTE: When adding metabolites to a compartment where it previously
+   doesn't exist, the function will copy any available information from
+   the metabolite in another compartment.
+
+ Usage: model=changeRxns(model,rxns,equations,eqnType,compartment,allowNewMets)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function model=changeRxns(model,rxns,equations,eqnType,compartment,allowNewMets)
+0002 % changeRxns
+0003 %   Modifies the equations of reactions
+0004 %
+0005 %   model            a model structure
+0006 %   rxns             cell array with reaction ids
+0007 %   equations        cell array with equations. Alternatively, it can be a
+0008 %                    structure with the fields "mets" and "stoichCoeffs",
+0009 %                    in the same fashion as addRxns. E.g.:
+0010 %                    equations.mets = {{'met1','met2'},{'met1','met3'}}
+0011 %                    equations.stoichCoeffs = {[-1,+2],[-1,+1]}
+0012 %   eqnType          double describing how the equation string should be
+0013 %                    interpreted
+0014 %                    1 - The metabolites are matched to model.mets. New
+0015 %                        metabolites (if allowed) are added to
+0016 %                        "compartment" (default)
+0017 %                    2 - The metabolites are matched to model.metNames and
+0018 %                        all metabolites are assigned to "compartment". Any
+0019 %                        new metabolites that are added will be assigned
+0020 %                        IDs "m1", "m2"... If IDs on the same form are
+0021 %                        already used in the model then the numbering will
+0022 %                        start from the highest used integer+1
+0023 %                    3 - The metabolites are written as
+0024 %                        "metNames[compNames]". Only compartments in
+0025 %                        model.compNames are allowed. Any
+0026 %                        new metabolites that are added will be assigned
+0027 %                        IDs "m1", "m2"... If IDs on the same form are
+0028 %                        already used in the model then the numbering will
+0029 %                        start from the highest used integer+1
+0030 %   compartment      a string with the compartment the metabolites should
+0031 %                    be placed in when using eqnType=2. Must match
+0032 %                    model.compNames (optional when eqnType=1 or eqnType=3)
+0033 %   allowNewMets     true if the function is allowed to add new
+0034 %                    metabolites. It is highly recommended to first add
+0035 %                    any new metabolites with addMets rather than
+0036 %                    automatically through this function. addMets supports
+0037 %                    more annotation of metabolites, allows for the use of
+0038 %                    exchange metabolites, and using it reduces the risk
+0039 %                    of parsing errors (optional, default false)
+0040 %
+0041 %   model            an updated model structure
+0042 %
+0043 %   NOTE: This function should be used with some care, since it doesn't
+0044 %   care about bounds on the reactions. Changing a irreversible reaction to
+0045 %   a reversible one (or the other way around) will only change the
+0046 %   model.rev field and not the model.lb/model.ub fields. The reaction will
+0047 %   therefore still be having the same reversibility because of the
+0048 %   bounds. Use setParams to change the bounds.
+0049 %
+0050 %   NOTE: When adding metabolites to a compartment where it previously
+0051 %   doesn't exist, the function will copy any available information from
+0052 %   the metabolite in another compartment.
+0053 %
+0054 % Usage: model=changeRxns(model,rxns,equations,eqnType,compartment,allowNewMets)
+0055 
+0056 if nargin<4
+0057     eqnType=1;
+0058 end
+0059 
+0060 if nargin<5
+0061     compartment=[];
+0062 end
+0063 if nargin<6
+0064     allowNewMets=false;
+0065 end
+0066 
+0067 rxns=convertCharArray(rxns);
+0068 compartment=char(compartment);
+0069 
+0070 %Find the indexes of the reactions and throw an error if they aren't all
+0071 %found
+0072 [I, J]=ismember(rxns,model.rxns);
+0073 if ~all(I)
+0074     EM='All reaction ids must exist in the model';
+0075     dispEM(EM);
+0076 end
+0077 
+0078 %The reactions are changed in the following manner. First create a
+0079 %rxns-structure by copying info from the model. Then remove the old
+0080 %reactions. Then add the updated ones using addRxns. Lastly, the model is
+0081 %reordered to match the original order. This is done like this to make use
+0082 %of the advanced parsing of equations that addRxns use.
+0083 rxnsToChange.rxns=rxns;
+0084 if isfield(equations,'mets') && isfield(equations,'stoichCoeffs')
+0085     rxnsToChange.mets=equations.mets;
+0086     rxnsToChange.stoichCoeffs=equations.stoichCoeffs;
+0087 else
+0088     rxnsToChange.equations=convertCharArray(equations);
+0089 end
+0090 if isfield(model,'rxnNames')
+0091     rxnsToChange.rxnNames=model.rxnNames(J);
+0092 end
+0093 if isfield(model,'lb')
+0094     rxnsToChange.lb=model.lb(J);
+0095 end
+0096 if isfield(model,'ub')
+0097     rxnsToChange.ub=model.ub(J);
+0098 end
+0099 if isfield(model,'c')
+0100     rxnsToChange.c=model.c(J);
+0101 end
+0102 if isfield(model,'eccodes')
+0103     rxnsToChange.eccodes=model.eccodes(J);
+0104 end
+0105 if isfield(model,'subSystems')
+0106     rxnsToChange.subSystems=model.subSystems(J);
+0107 end
+0108 if isfield(model,'rxnComps')
+0109     rxnsToChange.rxnComps=model.rxnComps(J);
+0110 end
+0111 if isfield(model,'grRules')
+0112     rxnsToChange.grRules=model.grRules(J);
+0113 end
+0114 if isfield(model,'rxnFrom')
+0115     rxnsToChange.rxnFrom=model.rxnFrom(J);
+0116 end
+0117 if isfield(model,'rxnScores')
+0118     rxnsToChange.rxnScores=model.rxnScores(J);
+0119 end
+0120 if isfield(model,'rxnMiriams')
+0121     rxnsToChange.rxnMiriams=model.rxnMiriams(J);
+0122 end
+0123 if isfield(model,'rxnNotes')
+0124     rxnsToChange.rxnNotes=model.rxnNotes(J);
+0125 end
+0126 if isfield(model,'rxnReferences')
+0127     rxnsToChange.rxnReferences=model.rxnReferences(J);
+0128 end
+0129 if isfield(model,'rxnConfidenceScores')
+0130     rxnsToChange.rxnConfidenceScores=model.rxnConfidenceScores(J);
+0131 end
+0132 if isfield(model,'rxnDeltaG')
+0133     rxnsToChange.rxnDeltaG=model.rxnDeltaG(J);
+0134 end
+0135 if isfield(model,'pwys')
+0136     rxnsToChange.pwys=model.pwys(J);
+0137 end
+0138 
+0139 %Calculate the new order of reactions
+0140 order=ones(numel(model.rxns),1);
+0141 order(J)=0;
+0142 order=cumsum(order);
+0143 order(J)=order(end)+1:order(end)+numel(rxns);
+0144 
+0145 %Remove the original reactions
+0146 model=removeReactions(model,rxns);
+0147 
+0148 model=addRxns(model,rxnsToChange,eqnType,compartment,allowNewMets);
+0149 model=permuteModel(model,order,'rxns');
+0150 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/checkModelStruct.html b/doc/core/checkModelStruct.html new file mode 100644 index 000000000..a25d6ed4e --- /dev/null +++ b/doc/core/checkModelStruct.html @@ -0,0 +1,517 @@ + + + + Description of checkModelStruct + + + + + + + + + +
Home > core > checkModelStruct.m
+ + + +

checkModelStruct +

+ +

PURPOSE ^

+
checkModelStruct
+ +

SYNOPSIS ^

+
function checkModelStruct(model,throwErrors,trimWarnings)
+ +

DESCRIPTION ^

+
 checkModelStruct
+   Performs a number of checks to ensure that a model structure is ok
+
+   model           a model structure
+   throwErrors     true if the function should throw errors if
+                   inconsistencies are found. The alternative is to
+                   print warnings for all types of issues (optional, default true)
+   trimWarnings    true if only a maximal of 10 items should be displayed in
+                   a given error/warning (optional, default true)
+
+   NOTE: This is performed after importing a model from Excel or before
+   attempting to export a model to SBML format.
+
+ Usage: checkModelStruct(model,throwErrors,trimWarnings)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 function checkModelStruct(model,throwErrors,trimWarnings)
+0002 % checkModelStruct
+0003 %   Performs a number of checks to ensure that a model structure is ok
+0004 %
+0005 %   model           a model structure
+0006 %   throwErrors     true if the function should throw errors if
+0007 %                   inconsistencies are found. The alternative is to
+0008 %                   print warnings for all types of issues (optional, default true)
+0009 %   trimWarnings    true if only a maximal of 10 items should be displayed in
+0010 %                   a given error/warning (optional, default true)
+0011 %
+0012 %   NOTE: This is performed after importing a model from Excel or before
+0013 %   attempting to export a model to SBML format.
+0014 %
+0015 % Usage: checkModelStruct(model,throwErrors,trimWarnings)
+0016 
+0017 if nargin<2
+0018     throwErrors=true;
+0019 end
+0020 if nargin<3
+0021     trimWarnings=true;
+0022 end
+0023 
+0024 %Missing elements
+0025 fields={'id';'name';'rxns';'mets';'S';'lb';'ub';'rev';'c';'b';'comps';'metComps'};
+0026 for i=1:numel(fields)
+0027     if ~isfield(model,fields{i})
+0028         EM=['The model is missing the "' fields{i} '" field'];
+0029         dispEM(EM,throwErrors);
+0030     end
+0031 end
+0032 
+0033 %Type check
+0034 if ~ischar(model.id)
+0035     EM='The "id" field must be a string';
+0036     dispEM(EM,throwErrors);
+0037 end
+0038 if ~ischar(model.name)
+0039     EM='The "name" field must be a string';
+0040     dispEM(EM,throwErrors);
+0041 end
+0042 if ~iscellstr(model.rxns)
+0043     EM='The "rxns" field must be a cell array of strings';
+0044     dispEM(EM,throwErrors);
+0045 end
+0046 if ~iscellstr(model.mets)
+0047     EM='The "mets" field must be a cell array of strings';
+0048     dispEM(EM,throwErrors);
+0049 end
+0050 if ~isnumeric(model.S)
+0051     EM='The "S" field must be of type "double"';
+0052     dispEM(EM,throwErrors);
+0053 end
+0054 if ~isnumeric(model.lb)
+0055     EM='The "lb" field must be of type "double"';
+0056     dispEM(EM,throwErrors);
+0057 end
+0058 if ~isnumeric(model.ub)
+0059     EM='The "ub" field must be of type "double"';
+0060     dispEM(EM,throwErrors);
+0061 end
+0062 if ~isnumeric(model.rev)
+0063     EM='The "rev" field must be of type "double"';
+0064     dispEM(EM,throwErrors);
+0065 end
+0066 if ~isnumeric(model.c)
+0067     EM='The "c" field must be of type "double"';
+0068     dispEM(EM,throwErrors);
+0069 end
+0070 if ~isnumeric(model.b)
+0071     EM='The "b" field must be of type "double"';
+0072     dispEM(EM,throwErrors);
+0073 end
+0074 if ~iscellstr(model.comps)
+0075     EM='The "comps" field must be a cell array of strings';
+0076     dispEM(EM,throwErrors);
+0077 end
+0078 if ~isnumeric(model.metComps)
+0079     EM='The "metComps" field must be of type "double"';
+0080     dispEM(EM,throwErrors);
+0081 end
+0082 if isfield(model,'compNames')
+0083     if ~iscellstr(model.compNames)
+0084         EM='The "compNames" field must be a cell array of strings';
+0085         dispEM(EM,throwErrors);
+0086     end
+0087 end
+0088 if isfield(model,'compOutside')
+0089     if ~iscellstr(model.compOutside)
+0090         EM='The "compOutside" field must be a cell array of strings';
+0091         dispEM(EM,throwErrors);
+0092     end
+0093 end
+0094 if isfield(model,'rxnNames')
+0095     if ~iscellstr(model.rxnNames)
+0096         EM='The "rxnNames" field must be a cell array of strings';
+0097         dispEM(EM,throwErrors);
+0098     end
+0099 end
+0100 if isfield(model,'metNames')
+0101     if ~iscellstr(model.metNames)
+0102         EM='The "metNames" field must be a cell array of strings';
+0103         dispEM(EM,throwErrors);
+0104     end
+0105 end
+0106 if isfield(model,'genes')
+0107     if ~iscellstr(model.genes)
+0108         EM='The "genes" field must be a cell array of strings';
+0109         dispEM(EM,throwErrors);
+0110     end
+0111 end
+0112 if isfield(model,'rxnGeneMat')
+0113     if ~isnumeric(model.rxnGeneMat)
+0114         EM='The "rxnGeneMat" field must be of type "double"';
+0115         dispEM(EM,throwErrors);
+0116     end
+0117 end
+0118 if isfield(model,'grRules')
+0119     if ~iscellstr(model.grRules)
+0120         EM='The "grRules" field must be a cell array of strings';
+0121         dispEM(EM,throwErrors);
+0122     end
+0123     if ~isfield(model,'genes')
+0124         EM='If "grRules" field exists, the model should also contain a "genes" field';
+0125         dispEM(EM,throwErrors);
+0126     else
+0127         %Erroneous grRules that start/end with OR/AND
+0128         EM='The following reaction(s) have grRules that start or end with ''OR'' or ''AND'':';
+0129         dispEM(EM,throwErrors,model.rxns(startsWith(model.grRules,{'or ','and '}) | endsWith(model.grRules,{' or',' and'})),trimWarnings);
+0130         %grRules that are not in genes field
+0131         geneList = getGenesFromGrRules(model.grRules);
+0132         geneList = setdiff(unique(geneList),model.genes);
+0133         if ~isempty(geneList)
+0134             problemGrRules = model.rxns(contains(model.grRules,geneList));
+0135             problemGrRules = strjoin(problemGrRules(:),'; ');
+0136             EM=['The reaction(s) "' problemGrRules '" contain the following genes in its "grRules" field, but these are not in the "genes" field:'];
+0137             dispEM(EM,throwErrors,geneList);
+0138         end
+0139     end
+0140 end
+0141 if isfield(model,'rxnComps')
+0142     if ~isnumeric(model.rxnComps)
+0143         EM='The "rxnComps" field must be of type "double"';
+0144         dispEM(EM,throwErrors);
+0145     end
+0146 end
+0147 if isfield(model,'inchis')
+0148     if ~iscellstr(model.inchis)
+0149         EM='The "inchis" field must be a cell array of strings';
+0150         dispEM(EM,throwErrors);
+0151     end
+0152 end
+0153 if isfield(model,'metSmiles')
+0154     if ~iscellstr(model.metSmiles)
+0155         EM='The "metSmiles" field must be a cell array of strings';
+0156         dispEM(EM,throwErrors);
+0157     end
+0158 end
+0159 if isfield(model,'metFormulas')
+0160     if ~iscellstr(model.metFormulas)
+0161         EM='The "metFormulas" field must be a cell array of strings';
+0162         dispEM(EM,throwErrors);
+0163     end
+0164 end
+0165 if isfield(model,'metCharges')
+0166     if ~isnumeric(model.metCharges)
+0167         EM='The "metCharges" field must be a double';
+0168         dispEM(EM,throwErrors);
+0169     end
+0170 end
+0171 if isfield(model,'metDeltaG')
+0172     if ~isnumeric(model.metDeltaG)
+0173         EM='The "metDeltaG" field must be a double';
+0174         dispEM(EM,throwErrors);
+0175     end
+0176 end
+0177 if isfield(model,'subSystems')
+0178     isNested  = any(cellfun(@(x) iscell(x), model.subSystems));
+0179     isCellStr = any(cellfun(@(x) ischar(x), model.subSystems));
+0180     if ~xor(isNested,isCellStr)
+0181         EM='The "subSystems" field must be a cell array of chars, *or* a cell array of cell arrays of chars';
+0182             dispEM(EM,throwErrors);
+0183     end
+0184 end
+0185 if isfield(model,'eccodes')
+0186     if ~iscellstr(model.eccodes)
+0187         EM='The "eccodes" field must be a cell array of strings';
+0188         dispEM(EM,throwErrors);
+0189     end
+0190 end
+0191 if isfield(model,'unconstrained')
+0192     if ~isnumeric(model.unconstrained)
+0193         EM='The "unconstrained" field must be of type "double"';
+0194         dispEM(EM,throwErrors);
+0195     end
+0196 end
+0197 if isfield(model,'rxnNotes')
+0198     if ~iscellstr(model.rxnNotes)
+0199         EM='The "rxnNotes" field must be a cell array of strings';
+0200         dispEM(EM,throwErrors);
+0201     end
+0202 end
+0203 if isfield(model,'rxnReferences')
+0204     if ~iscellstr(model.rxnReferences)
+0205         EM='The "rxnReferences" field must be a cell array of strings';
+0206         dispEM(EM,throwErrors);
+0207     end
+0208 end
+0209 if isfield(model,'rxnConfidenceScores')
+0210     if ~isnumeric(model.rxnConfidenceScores)
+0211         EM='The "rxnConfidenceScores" field must be a double';
+0212         dispEM(EM,throwErrors);
+0213     end
+0214 end
+0215 if isfield(model,'rxnDeltaG')
+0216     if ~isnumeric(model.rxnDeltaG)
+0217         EM='The "rxnDeltaG" field must be a double';
+0218         dispEM(EM,throwErrors);
+0219     end
+0220 end
+0221 
+0222 %Empty strings
+0223 if isempty(model.id)
+0224     EM='The "id" field cannot be empty';
+0225     dispEM(EM,throwErrors);
+0226 end
+0227 if any(cellfun(@isempty,model.rxns))
+0228     EM='The model contains empty reaction IDs';
+0229     dispEM(EM,throwErrors);
+0230 end
+0231 if any(cellfun(@isempty,model.mets))
+0232     EM='The model contains empty metabolite IDs';
+0233     dispEM(EM,throwErrors);
+0234 end
+0235 if any(cellfun(@isempty,model.comps))
+0236     EM='The model contains empty compartment IDs';
+0237     dispEM(EM,throwErrors);
+0238 end
+0239 EM='The following metabolites have empty names:';
+0240 dispEM(EM,throwErrors,model.mets(cellfun(@isempty,model.metNames)),trimWarnings);
+0241 
+0242 if isfield(model,'genes')
+0243     if any(cellfun(@isempty,model.genes))
+0244         EM='The model contains empty gene IDs';
+0245         dispEM(EM,throwErrors);
+0246     end
+0247 end
+0248 
+0249 %Validate format of ids
+0250 fields      = {'rxns';'mets';'comps';'genes'};
+0251 fieldNames  = {'reaction';'metabolite';'compartment';'gene'};
+0252 fieldPrefix = {'R_';'M_';'C_';'G_'};
+0253 for i=1:numel(fields)
+0254     try
+0255         numIDs = ~startsWith(model.(fields{i}),regexpPattern('^[a-zA-Z_]'));
+0256     catch
+0257         numIDs = [];
+0258     end
+0259     if any(numIDs)
+0260         EM = ['The following ' fieldNames{i} ' identifiers do not start '...
+0261             'with a letter or _ (conflicting with SBML specifications). '...
+0262             'This does not impact RAVEN functionality, but be aware that '...
+0263             'exportModel will automatically add ' fieldPrefix{i} ...
+0264             ' prefixes to all ' fieldNames{i} ' identifiers:'];
+0265         dispEM(EM,false,{model.(fields{i}){numIDs}},trimWarnings);
+0266     end
+0267 end
+0268 
+0269 %Duplicates
+0270 EM='The following reaction IDs are duplicates:';
+0271 dispEM(EM,throwErrors,model.rxns(duplicates(model.rxns)),trimWarnings);
+0272 EM='The following metabolite IDs are duplicates:';
+0273 dispEM(EM,throwErrors,model.mets(duplicates(model.mets)),trimWarnings);
+0274 EM='The following compartment IDs are duplicates:';
+0275 dispEM(EM,throwErrors,model.comps(duplicates(model.comps)),trimWarnings);
+0276 if isfield(model,'genes')
+0277     EM='The following genes are duplicates:';
+0278     dispEM(EM,throwErrors,model.genes(duplicates(model.genes)),trimWarnings);
+0279 end
+0280 metInComp=strcat(model.metNames,'[',model.comps(model.metComps),']');
+0281 EM='The following metabolites already exist in the same compartment:';
+0282 dispEM(EM,throwErrors,metInComp(duplicates(metInComp)),trimWarnings);
+0283 
+0284 %Elements never used (print only as warnings
+0285 EM='The following reactions are empty (no involved metabolites):';
+0286 dispEM(EM,false,model.rxns(~any(model.S,1)),trimWarnings);
+0287 EM='The following metabolites are never used in a reaction:';
+0288 dispEM(EM,false,model.mets(~any(model.S,2)),trimWarnings);
+0289 if isfield(model,'genes')
+0290     EM='The following genes are not associated to a reaction:';
+0291     dispEM(EM,false,model.genes(~any(model.rxnGeneMat,1)),trimWarnings);
+0292 end
+0293 I=true(numel(model.comps),1);
+0294 I(model.metComps)=false;
+0295 EM='The following compartments contain no metabolites:';
+0296 dispEM(EM,false,model.comps(I),trimWarnings);
+0297 
+0298 %Contradicting bounds
+0299 EM='The following reactions have contradicting bounds (lower bound is higher than upper bound):';
+0300 dispEM(EM,throwErrors,model.rxns(model.lb>model.ub),trimWarnings);
+0301 EM='The following reactions have lower and upper bounds that indicate reversibility, but are indicated as irreversible in model.rev:';
+0302 dispEM(EM,false,model.rxns(model.lb < 0 & model.ub > 0 & model.rev==0),trimWarnings);
+0303 
+0304 %Multiple or no objective functions not allowed in SBML L3V1 FBCv2
+0305 if numel(find(model.c))>1
+0306     EM='Multiple objective functions found. This might be intended, but results in FBCv2 non-compliant SBML file when exported';
+0307     dispEM(EM,false,model.rxns(find(model.c)),trimWarnings);
+0308 elseif ~any(model.c)
+0309     EM='No objective function found. This might be intended, but results in FBCv2 non-compliant SBML file when exported';
+0310     dispEM(EM,false);
+0311 end
+0312 
+0313 %Mapping of compartments
+0314 if isfield(model,'compOutside')
+0315     EM='The following compartments are in "compOutside" but not in "comps":';
+0316     dispEM(EM,throwErrors,setdiff(model.compOutside,[{''};model.comps]),trimWarnings);
+0317 end
+0318 
+0319 %Met names which start with number
+0320 I=false(numel(model.metNames),1);
+0321 for i=1:numel(model.metNames)
+0322     index=strfind(model.metNames{i},' ');
+0323     if any(index)
+0324         if any(str2double(model.metNames{i}(1:index(1)-1)))
+0325             I(i)=true;
+0326         end
+0327     end
+0328 end
+0329 EM='The following metabolite names begin with a number directly followed by space, which could potentially cause problems:';
+0330 dispEM(EM,false,model.metNames(I),trimWarnings);
+0331 
+0332 %Non-parseable composition
+0333 if isfield(model,'metFormulas')
+0334     [~, ~, exitFlag]=parseFormulas(model.metFormulas,true,false);
+0335     EM='The composition for the following metabolites could not be parsed:';
+0336     dispEM(EM,false,model.mets(exitFlag==-1),trimWarnings);
+0337 end
+0338 
+0339 %Check if there are metabolites with different names but the same MIRIAM
+0340 %codes
+0341 if isfield(model,'metMiriams')
+0342     miriams=containers.Map();
+0343     for i=1:numel(model.mets)
+0344         if ~isempty(model.metMiriams{i})
+0345             %Loop through and add for each miriam
+0346             for j=1:numel(model.metMiriams{i}.name)
+0347                 %Get existing metabolite indexes
+0348                 current=strcat(model.metMiriams{i}.name{j},'/',model.metMiriams{i}.value{j});
+0349                 if isKey(miriams,current)
+0350                     existing=miriams(current);
+0351                 else
+0352                     existing=[];
+0353                 end
+0354                 miriams(current)=[existing;i];
+0355             end
+0356         end
+0357     end
+0358     
+0359     %Get all keys
+0360     allMiriams=keys(miriams);
+0361     
+0362     hasMultiple=false(numel(allMiriams),1);
+0363     for i=1:numel(allMiriams)
+0364         if numel(miriams(allMiriams{i}))>1
+0365             %Check if they all have the same name
+0366             if numel(unique(model.metNames(miriams(allMiriams{i}))))>1
+0367                 if ~regexp(allMiriams{i},'^sbo\/SBO:') % SBO terms are expected to be multiple
+0368                     hasMultiple(i)=true;
+0369                 end                
+0370             end
+0371         end
+0372     end
+0373     
+0374     %Print output
+0375     EM='The following MIRIAM strings are associated to more than one unique metabolite name:';
+0376     dispEM(EM,false,allMiriams(hasMultiple),trimWarnings);
+0377 end
+0378 
+0379 %Check if there are metabolites with different names but the same InChI
+0380 %codes
+0381 if isfield(model,'inchis')
+0382     inchis=containers.Map();
+0383     for i=1:numel(model.mets)
+0384         if ~isempty(model.inchis{i})
+0385             %Get existing metabolite indexes
+0386             if isKey(inchis,model.inchis{i})
+0387                 existing=inchis(model.inchis{i});
+0388             else
+0389                 existing=[];
+0390             end
+0391             inchis(model.inchis{i})=[existing;i];
+0392         end
+0393     end
+0394     
+0395     %Get all keys
+0396     allInchis=keys(inchis);
+0397     
+0398     hasMultiple=false(numel(allInchis),1);
+0399     for i=1:numel(allInchis)
+0400         if numel(inchis(allInchis{i}))>1
+0401             %Check if they all have the same name
+0402             if numel(unique(model.metNames(inchis(allInchis{i}))))>1
+0403                 hasMultiple(i)=true;
+0404             end
+0405         end
+0406     end
+0407     
+0408     %Print output
+0409     EM='The following InChI strings are associated to more than one unique metabolite name:';
+0410     dispEM(EM,false,allInchis(hasMultiple),trimWarnings);
+0411 end
+0412 
+0413 % %Check if there are metabolites with different names but the same SMILES
+0414 % if isfield(model,'metSmiles')
+0415 %     metSmiles=containers.Map();
+0416 %     for i=1:numel(model.mets)
+0417 %         if ~isempty(model.metSmiles{i})
+0418 %             %Get existing metabolite indexes
+0419 %             if isKey(metSmiles,model.metSmiles{i})
+0420 %                 existing=metSmiles(model.metSmiles{i});
+0421 %             else
+0422 %                 existing=[];
+0423 %             end
+0424 %             metSmiles(model.metSmiles{i})=[existing;i];
+0425 %         end
+0426 %     end
+0427 %
+0428 %     %Get all keys
+0429 %     allmetSmiles=keys(metSmiles);
+0430 %
+0431 %     hasMultiple=false(numel(metSmiles),1);
+0432 %     for i=1:numel(metSmiles)
+0433 %         if numel(metSmiles(metSmiles{i}))>1
+0434 %             %Check if they all have the same name
+0435 %             if numel(unique(model.metNames(metSmiles(allmetSmiles{i}))))>1
+0436 %                 hasMultiple(i)=true;
+0437 %             end
+0438 %         end
+0439 %     end
+0440 %
+0441 %     %Print output
+0442 %     EM='The following metSmiles strings are associated to more than one unique metabolite name:';
+0443 %     dispEM(EM,false,allmetSmiles(hasMultiple),trimWarnings);
+0444 % end
+0445 end
+0446 
+0447 function I=duplicates(strings)
+0448 I=false(numel(strings),1);
+0449 [J, K]=unique(strings);
+0450 if numel(J)~=numel(strings)
+0451     L=1:numel(strings);
+0452     L(K)=[];
+0453     I(L)=true;
+0454 end
+0455 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/checkProduction.html b/doc/core/checkProduction.html new file mode 100644 index 000000000..47d2f41e9 --- /dev/null +++ b/doc/core/checkProduction.html @@ -0,0 +1,242 @@ + + + + Description of checkProduction + + + + + + + + + +
Home > core > checkProduction.m
+ + + +

checkProduction +

+ +

PURPOSE ^

+
checkProduction
+ +

SYNOPSIS ^

+
function [notProduced, notProducedNames, neededForProductionMat,minToConnect,model]=checkProduction(model,checkNeededForProduction,excretionFromCompartments,printDetails)
+ +

DESCRIPTION ^

+
 checkProduction
+   Checks which metabolites that can be produced from a model using the
+   specified constraints.
+
+   model                       a model structure
+   checkNeededForProduction    for each of the metabolites that could not
+                               be produced, include an artificial
+                               production reaction and calculate which new
+                               metabolites that could be produced as en
+                               effect of this (optional, default false)
+   excretionFromCompartments   cell array with compartment ids from which
+                               metabolites can be excreted (optional, default
+                               model.comps)
+   printDetails                print details to the screen (optional, default
+                               true)
+
+   notProduced                 cell array with metabolites that could not
+                               be produced
+   notProducedNames            cell array with names and compartments for
+                               metabolites that could not be produced
+   neededForProductionMat      matrix where n x m is true if metabolite n
+                               allows for production of metabolite m
+   minToConnect                structure with the minimal number of
+                               metabolites that need to be connected in
+                               order to be able to produce all other
+                               metabolites and which metabolites each of
+                               them connects
+   model                       updated model structure with excretion
+                               reactions added
+
+   The function is intended to be used to identify which metabolites must
+   be connected in order to have a fully connected network. It does so by
+   first identifying which metabolites could have a net production in the
+   network. Then it calculates which other metabolites must be able to
+   have net production in order to have production of all metabolites in
+   the network. So, if a network contains the equations A[external]->B,
+   C->D, and D->E it will identify that production of C will connect
+   the metabolites D and E.
+
+ Usage: [notProduced, notProducedNames,neededForProductionMat,minToConnect,model]=...
+           checkProduction(model,checkNeededForProduction,...
+           excretionFromCompartments,printDetails)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function [notProduced, notProducedNames, neededForProductionMat,minToConnect,model]=checkProduction(model,checkNeededForProduction,excretionFromCompartments,printDetails)
+0002 % checkProduction
+0003 %   Checks which metabolites that can be produced from a model using the
+0004 %   specified constraints.
+0005 %
+0006 %   model                       a model structure
+0007 %   checkNeededForProduction    for each of the metabolites that could not
+0008 %                               be produced, include an artificial
+0009 %                               production reaction and calculate which new
+0010 %                               metabolites that could be produced as en
+0011 %                               effect of this (optional, default false)
+0012 %   excretionFromCompartments   cell array with compartment ids from which
+0013 %                               metabolites can be excreted (optional, default
+0014 %                               model.comps)
+0015 %   printDetails                print details to the screen (optional, default
+0016 %                               true)
+0017 %
+0018 %   notProduced                 cell array with metabolites that could not
+0019 %                               be produced
+0020 %   notProducedNames            cell array with names and compartments for
+0021 %                               metabolites that could not be produced
+0022 %   neededForProductionMat      matrix where n x m is true if metabolite n
+0023 %                               allows for production of metabolite m
+0024 %   minToConnect                structure with the minimal number of
+0025 %                               metabolites that need to be connected in
+0026 %                               order to be able to produce all other
+0027 %                               metabolites and which metabolites each of
+0028 %                               them connects
+0029 %   model                       updated model structure with excretion
+0030 %                               reactions added
+0031 %
+0032 %   The function is intended to be used to identify which metabolites must
+0033 %   be connected in order to have a fully connected network. It does so by
+0034 %   first identifying which metabolites could have a net production in the
+0035 %   network. Then it calculates which other metabolites must be able to
+0036 %   have net production in order to have production of all metabolites in
+0037 %   the network. So, if a network contains the equations A[external]->B,
+0038 %   C->D, and D->E it will identify that production of C will connect
+0039 %   the metabolites D and E.
+0040 %
+0041 % Usage: [notProduced, notProducedNames,neededForProductionMat,minToConnect,model]=...
+0042 %           checkProduction(model,checkNeededForProduction,...
+0043 %           excretionFromCompartments,printDetails)
+0044 
+0045 if nargin<2
+0046     checkNeededForProduction=false;
+0047 end
+0048 
+0049 if nargin<3
+0050     excretionFromCompartments=model.comps;
+0051 else
+0052     excretionFromCompartments=convertCharArray(excretionFromCompartments);
+0053 end
+0054 
+0055 if nargin<4
+0056     printDetails=true;
+0057 end
+0058 
+0059 %Add an exchange reaction for each metabolite in the allowed compartments
+0060 %and see if it can carry a flux
+0061 allowedMetIds=ismember(model.comps(model.metComps),excretionFromCompartments);
+0062 allowedMetIndexes=find(allowedMetIds);
+0063 [model, addedRxns]=addExchangeRxns(model,'out',allowedMetIndexes);
+0064 
+0065 canProduce=haveFlux(model,10^-5,addedRxns);
+0066 
+0067 notProduced=find(~canProduce);
+0068 minToConnect={};
+0069 if checkNeededForProduction==true
+0070     %For each of the metabolites that couldn't be produced allow uptake and
+0071     %check which of the other metabolites that couldn't be produced that
+0072     %can be produced
+0073     neededForProductionMat=false(numel(notProduced));
+0074     for i=1:numel(notProduced)
+0075         %Add uptake for this metabolite
+0076         if i>1
+0077             %Reset last iteration
+0078             model.S(:,numel(model.rxns)-numel(addedRxns)+notProduced(i-1))=model.S(:,numel(model.rxns)-numel(addedRxns)+notProduced(i-1))*-1;
+0079         end
+0080         %Change the production reaction to an uptake reaction
+0081         model.S(:,numel(model.rxns)-numel(addedRxns)+notProduced(i))=model.S(:,numel(model.rxns)-numel(addedRxns)+notProduced(i))*-1;
+0082         
+0083         %Test which of the metabolites that couldn't be produced that can
+0084         %be produced now
+0085         neededForProductionMat(i,:)=haveFlux(model,10^-5,addedRxns(notProduced));
+0086     end
+0087     %Calculate the smallest number of metabolites that must be connected to
+0088     %make everything connected and return their names
+0089     
+0090     %The algorithm is relatively straight forward. It finds the metabolite
+0091     %that connects the most unconnected metabolites (iteratively), adds it
+0092     %and removes the now connected metabolites until all are connected.
+0093     %This is not guaranteed to find the global minimum
+0094     neededForProdTemp=neededForProductionMat;
+0095     while 1==1
+0096         %Get all metabolites a metabolite makes connected
+0097         totalConnected=false(size(neededForProdTemp));
+0098         for i=1:numel(notProduced)
+0099             totalConnected(i,:)=neededForProdTemp(i,:);
+0100             
+0101             lastIter=0;
+0102             while 1==1
+0103                 [~, a]=find(neededForProdTemp(totalConnected(i,:),:));
+0104                 totalConnected(i,a)=true;
+0105                 if numel(a)==lastIter
+0106                     break; %No more connections were possible
+0107                 else
+0108                     lastIter=numel(a);
+0109                 end
+0110             end
+0111         end
+0112         [connections, mostConnected]=max(sum(totalConnected,2));
+0113         
+0114         if connections>0
+0115             %Add the most connected metabolite to the list and remove all
+0116             %metabolites that it's connected to
+0117             metID=allowedMetIndexes(notProduced(mostConnected));
+0118             entry=[model.metNames{metID},'[',model.comps{model.metComps(metID)},'] (connects ' num2str(connections) ' metabolites)'];
+0119             minToConnect=[minToConnect;entry];
+0120             neededForProdTemp(totalConnected(mostConnected,:),:)=false;
+0121             neededForProdTemp(:,totalConnected(mostConnected,:))=false;
+0122         else
+0123             break;
+0124         end
+0125     end
+0126 else
+0127     neededForProductionMat=[];
+0128 end
+0129 
+0130 notProducedNames=strcat(model.metNames(allowedMetIndexes(notProduced)),'[',model.comps(model.metComps(allowedMetIndexes(notProduced))),']');
+0131 
+0132 if printDetails==true
+0133     fprintf('The following metabolites could not be produced:\n');
+0134     [notProducedNamesTemp,perm]=sort(notProducedNames);
+0135     
+0136     if checkNeededForProduction==true
+0137         neededForProdTemp=neededForProductionMat(:,perm);
+0138         neededForProdTemp=neededForProdTemp(perm,:);
+0139         fprintf('\tIf the production of a metabolite is dependent on some other metabolites then those are printed under the name\n\n');
+0140     end
+0141     for i=1:numel(notProducedNamesTemp)
+0142         fprintf([notProducedNamesTemp{i} '\n']);
+0143         neededForProdTemp(i,i)=false; %Not neat to do this here. Prevent printing itself
+0144         if checkNeededForProduction==true
+0145             enablesProduction=find(neededForProdTemp(:,i));
+0146             if any(enablesProduction)
+0147                 for j=1:numel(enablesProduction)
+0148                     fprintf(['\t' notProducedNamesTemp{enablesProduction(j)} '\n']);
+0149                 end
+0150             end
+0151         end
+0152     end
+0153 end
+0154 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/checkRxn.html b/doc/core/checkRxn.html new file mode 100644 index 000000000..4169caa72 --- /dev/null +++ b/doc/core/checkRxn.html @@ -0,0 +1,156 @@ + + + + Description of checkRxn + + + + + + + + + +
Home > core > checkRxn.m
+ + + +

checkRxn +

+ +

PURPOSE ^

+
checkRxn
+ +

SYNOPSIS ^

+
function report=checkRxn(model,rxn,cutoff,revDir,printReport)
+ +

DESCRIPTION ^

+
 checkRxn
+   Checks which reactants in a reaction that can be synthesized and which
+   products that can be consumed. This is primarily for debugging
+   reactions which cannot have flux
+
+   model       a model structure
+   rxn         the id of one reaction to check
+   cutoff      minimal flux for successful production/consumption (optional,
+               default 10^-7)
+   revDir      true if the reaction should be reversed (optional, default
+               false)
+   printReport print a report (optional, default true)
+
+   report
+       reactants   array with reactant indexes
+       canMake     boolean array, true if the corresponding reactant can
+                   be synthesized by the rest of the metabolic network
+       products    array with product indexes
+       canConsume  boolean array, true if the corresponding product can
+                   be consumed by the rest of the metabolic network
+
+ Usage: report=checkRxn(model,rxn,cutoff,revDir,printReport)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function report=checkRxn(model,rxn,cutoff,revDir,printReport)
+0002 % checkRxn
+0003 %   Checks which reactants in a reaction that can be synthesized and which
+0004 %   products that can be consumed. This is primarily for debugging
+0005 %   reactions which cannot have flux
+0006 %
+0007 %   model       a model structure
+0008 %   rxn         the id of one reaction to check
+0009 %   cutoff      minimal flux for successful production/consumption (optional,
+0010 %               default 10^-7)
+0011 %   revDir      true if the reaction should be reversed (optional, default
+0012 %               false)
+0013 %   printReport print a report (optional, default true)
+0014 %
+0015 %   report
+0016 %       reactants   array with reactant indexes
+0017 %       canMake     boolean array, true if the corresponding reactant can
+0018 %                   be synthesized by the rest of the metabolic network
+0019 %       products    array with product indexes
+0020 %       canConsume  boolean array, true if the corresponding product can
+0021 %                   be consumed by the rest of the metabolic network
+0022 %
+0023 % Usage: report=checkRxn(model,rxn,cutoff,revDir,printReport)
+0024 
+0025 rxn=char(rxn);
+0026 if nargin<3
+0027     cutoff=10^-7;
+0028 end
+0029 if nargin<4
+0030     revDir=false;
+0031 end
+0032 if isempty(cutoff)
+0033     cutoff=10^-7;
+0034 end
+0035 if nargin<5
+0036     printReport=true;
+0037 end
+0038 
+0039 [I, rxnID]=ismember(rxn,model.rxns);
+0040 
+0041 if ~I
+0042     EM='Reaction ID not found';
+0043     dispEM(EM);
+0044 end
+0045 
+0046 if revDir==false
+0047     report.reactants=find(model.S(:,rxnID)<0);
+0048     report.products=find(model.S(:,rxnID)>0);
+0049 else
+0050     report.reactants=find(model.S(:,rxnID)>0);
+0051     report.products=find(model.S(:,rxnID)<0);
+0052 end
+0053 report.canMake=false(numel(report.reactants),1);
+0054 report.canConsume=false(numel(report.products),1);
+0055 
+0056 %Remove this field as it would give an annoying note otherwise
+0057 if isfield(model,'rxnComps')
+0058     model=rmfield(model,'rxnComps');
+0059 end
+0060 
+0061 %There are several ways to do this. Here I choose to add the reactions one
+0062 %by one and checking their bounds. This might not be optimal
+0063 for i=1:numel(report.reactants)
+0064     [tempModel, testRxn]=addExchangeRxns(model,'out',report.reactants(i));
+0065     tempModel=setParam(tempModel,'obj',testRxn,1);
+0066     sol=solveLP(tempModel);
+0067     if sol.f>cutoff
+0068         report.canMake(i)=true;
+0069     else
+0070         if printReport==true
+0071             fprintf(['Failed to make ' model.metNames{report.reactants(i)} '[' model.comps{model.metComps(report.reactants(i))} ']\n']);
+0072         end
+0073     end
+0074 end
+0075 
+0076 for i=1:numel(report.products)
+0077     [tempModel, testRxn]=addExchangeRxns(model,'in',report.products(i));
+0078     tempModel=setParam(tempModel,'obj',testRxn,1);
+0079     sol=solveLP(tempModel);
+0080     if sol.f>cutoff
+0081         report.canConsume(i)=true;
+0082     else
+0083         if printReport==true
+0084             fprintf(['Failed to consume ' model.metNames{report.products(i)} '[' model.comps{model.metComps(report.products(i))} ']\n']);
+0085         end
+0086     end
+0087 end
+0088 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/checkTasks.html b/doc/core/checkTasks.html new file mode 100644 index 000000000..a9ea73c64 --- /dev/null +++ b/doc/core/checkTasks.html @@ -0,0 +1,351 @@ + + + + Description of checkTasks + + + + + + + + + +
Home > core > checkTasks.m
+ + + +

checkTasks +

+ +

PURPOSE ^

+
checkTasks
+ +

SYNOPSIS ^

+
function [taskReport, essentialRxns, taskStructure, essentialFluxes]=checkTasks(model,inputFile,printOutput,printOnlyFailed,getEssential,taskStructure)
+ +

DESCRIPTION ^

+
 checkTasks
+   Performs a set of simulations as defined in a task file.
+
+   Input:
+   model           a model structure
+   inputFile       a task list in Excel format. See the function
+                   parseTaskList for details (optional if taskStructure is
+                   supplied)
+   printOutput     true if the results of the test should be displayed
+                   (optional, default true)
+   printOnlyFailed true if only tasks that failed should be displayed
+                   (optional, default false)
+   getEssential    true if the essential reactions should be calculated for
+                   all the tasks. This option is used with runINIT (optional,
+                   default false)
+   taskStructure   structure with the tasks, as from parseTaskList. If
+                   this is supplied then inputFile is ignored (optional)
+
+
+   Output:
+   taskReport          structure with the results
+       id              cell array with the id of the task
+       description     cell array with the description of the task
+       ok              boolean array with true if the task was successful
+   essentialRxns       MxN matrix with the essential reactions (M) for each
+                       task (N). An element is true if the corresponding
+                       reaction is essential in the corresponding task.
+                       Failed tasks and SHOULD FAIL tasks are ignored.
+                       This is used by the INIT algorithm (if tasks
+                       are supplied). If getEssential=false then
+                       essentialRxns=false(nRxns,nTasks)
+   taskStructure       structure with the tasks, as from parseTaskList
+   essentialFluxes     The fluxes of the essential rxns - same structure as essentialRxns
+   
+
+   This function is used for defining a set of tasks for a model to
+   perform. The tasks are defined by defining constraints on the model,
+   and if the problem is feasible, then the task is considered successful.
+   In general, each row can contain one constraint on uptakes, one
+   constraint on outputs, one new equation, and one change of reaction
+   bounds. If more bounds are needed to define the task, then several rows
+   can be used for each task.
+
+ Usage: [taskReport, essentialReactions, taskStructure]=checkTasks(model,inputFile,...
+           printOutput,printOnlyFailed,getEssential,taskStructure)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function [taskReport, essentialRxns, taskStructure, essentialFluxes]=checkTasks(model,inputFile,printOutput,printOnlyFailed,getEssential,taskStructure)
+0002 % checkTasks
+0003 %   Performs a set of simulations as defined in a task file.
+0004 %
+0005 %   Input:
+0006 %   model           a model structure
+0007 %   inputFile       a task list in Excel format. See the function
+0008 %                   parseTaskList for details (optional if taskStructure is
+0009 %                   supplied)
+0010 %   printOutput     true if the results of the test should be displayed
+0011 %                   (optional, default true)
+0012 %   printOnlyFailed true if only tasks that failed should be displayed
+0013 %                   (optional, default false)
+0014 %   getEssential    true if the essential reactions should be calculated for
+0015 %                   all the tasks. This option is used with runINIT (optional,
+0016 %                   default false)
+0017 %   taskStructure   structure with the tasks, as from parseTaskList. If
+0018 %                   this is supplied then inputFile is ignored (optional)
+0019 %
+0020 %
+0021 %   Output:
+0022 %   taskReport          structure with the results
+0023 %       id              cell array with the id of the task
+0024 %       description     cell array with the description of the task
+0025 %       ok              boolean array with true if the task was successful
+0026 %   essentialRxns       MxN matrix with the essential reactions (M) for each
+0027 %                       task (N). An element is true if the corresponding
+0028 %                       reaction is essential in the corresponding task.
+0029 %                       Failed tasks and SHOULD FAIL tasks are ignored.
+0030 %                       This is used by the INIT algorithm (if tasks
+0031 %                       are supplied). If getEssential=false then
+0032 %                       essentialRxns=false(nRxns,nTasks)
+0033 %   taskStructure       structure with the tasks, as from parseTaskList
+0034 %   essentialFluxes     The fluxes of the essential rxns - same structure as essentialRxns
+0035 %
+0036 %
+0037 %   This function is used for defining a set of tasks for a model to
+0038 %   perform. The tasks are defined by defining constraints on the model,
+0039 %   and if the problem is feasible, then the task is considered successful.
+0040 %   In general, each row can contain one constraint on uptakes, one
+0041 %   constraint on outputs, one new equation, and one change of reaction
+0042 %   bounds. If more bounds are needed to define the task, then several rows
+0043 %   can be used for each task.
+0044 %
+0045 % Usage: [taskReport, essentialReactions, taskStructure]=checkTasks(model,inputFile,...
+0046 %           printOutput,printOnlyFailed,getEssential,taskStructure)
+0047 
+0048 if nargin<3 || isempty(printOutput)
+0049     printOutput=true;
+0050 end
+0051 if nargin<4 || isempty(printOnlyFailed)
+0052     printOnlyFailed=false;
+0053 end
+0054 if nargin<5 || isempty(getEssential)
+0055     getEssential=false;
+0056 end
+0057 
+0058 %Prepare the input model a little
+0059 model.b=zeros(numel(model.mets),2);
+0060 
+0061 modelMets=upper(strcat(model.metNames,'[',model.comps(model.metComps),']'));
+0062 if ~isfield(model,'unconstrained')
+0063     EM='Exchange metabolites should normally not be removed from the model when using checkTasks. Inputs and outputs are defined in the task file instead. Use importModel(file,false) to import a model with exchange metabolites remaining';
+0064     dispEM(EM,false);
+0065 end
+0066 
+0067 %Parse the task file
+0068 if nargin<6
+0069     taskStructure=parseTaskList(inputFile);
+0070 end
+0071 
+0072 essentialRxns=false(numel(model.rxns),numel(taskStructure));
+0073 essentialFluxes = NaN(numel(model.rxns),numel(taskStructure));
+0074 
+0075 tModel=model;
+0076 taskReport=[];
+0077 for i=1:numel(taskStructure)
+0078     taskReport.id{i,1}=taskStructure(i).id;
+0079     taskReport.description{i,1}=taskStructure(i).description;
+0080     %Set the inputs
+0081     if ~isempty(taskStructure(i).inputs)
+0082         [I, J]=ismember(upper(taskStructure(i).inputs),modelMets);
+0083         J=J(I); %Only keep the ones with matches
+0084         K=ismember(upper(taskStructure(i).inputs),'ALLMETS');
+0085         L=~cellfun('isempty',strfind(upper(taskStructure(i).inputs),'ALLMETSIN'));
+0086         %Check that all metabolites are either real metabolites or
+0087         %ALLMETS/ALLMETSIN
+0088         if ~all(I|K|L)
+0089             fprintf(['ERROR: Could not find all inputs in "[' taskStructure(i).id '] ' taskStructure(i).description '"\n']);
+0090             taskReport.ok(i,1)=false;
+0091             tModel=model;
+0092             continue;
+0093         end
+0094         if numel(J)~=numel(unique(J))
+0095             EM=['The constraints on some input(s) in "[' taskStructure(i).id '] ' taskStructure(i).description '" are defined more than one time'];
+0096             dispEM(EM);
+0097         end
+0098         %If all metabolites should be added
+0099         if any(K)
+0100             %Check if ALLMETS is the first metabolite. Otherwise print a
+0101             %warning since it will write over any other constraints that
+0102             %are set
+0103             if K(1)==0
+0104                 EM=['ALLMETS is used as an input in "[' taskStructure(i).id '] ' taskStructure(i).description '" but it it not the first metabolite in the list. Constraints defined for the metabolites before it will be over-written'];
+0105                 dispEM(EM,false);
+0106             end
+0107             %Use the first match of ALLMETS. There should only be one, but
+0108             %still..
+0109             tModel.b(:,1)=taskStructure(i).UBin(find(K,1))*-1;
+0110         end
+0111         %If metabolites in a specific compartment should be used
+0112         if any(L)
+0113             L=find(L);
+0114             for j=1:numel(L)
+0115                 %The compartment defined
+0116                 compartment=upper(taskStructure(i).inputs{L(j)}(11:end-1));
+0117                 %Check if it exists in the model
+0118                 C=find(ismember(upper(model.comps),compartment));
+0119                 if any(C)
+0120                     %Match to metabolites
+0121                     tModel.b(model.metComps==C,1)=taskStructure(i).UBin(L(j))*-1;
+0122                 else
+0123                     EM=['The compartment defined for ALLMETSIN in "[' taskStructure(i).id '] ' taskStructure(i).description '" does not exist'];
+0124                     dispEM(EM);
+0125                 end
+0126             end
+0127         end
+0128         %Then add the normal constraints
+0129         if any(J)
+0130             tModel.b(J,1)=taskStructure(i).UBin(I)*-1;
+0131             tModel.b(J,2)=taskStructure(i).LBin(I)*-1;
+0132         end
+0133     end
+0134     %Set the outputs
+0135     if ~isempty(taskStructure(i).outputs)
+0136         [I, J]=ismember(upper(taskStructure(i).outputs),modelMets);
+0137         J=J(I); %Only keep the ones with matches
+0138         K=ismember(upper(taskStructure(i).outputs),'ALLMETS');
+0139         L=~cellfun('isempty',strfind(upper(taskStructure(i).outputs),'ALLMETSIN'));
+0140         %Check that all metabolites are either real metabolites or
+0141         %ALLMETS/ALLMETSIN
+0142         if ~all(I|K|L)
+0143             fprintf(['ERROR: Could not find all outputs in "[' taskStructure(i).id '] ' taskStructure(i).description '"\n']);
+0144             taskReport.ok(i,1)=false;
+0145             tModel=model;
+0146             continue;
+0147         end
+0148         if numel(J)~=numel(unique(J))
+0149             EM=['The constraints on some output(s) in "[' taskStructure(i).id '] ' taskStructure(i).description '" are defined more than one time'];
+0150             dispEM(EM);
+0151         end
+0152         %If all metabolites should be added
+0153         if any(K)
+0154             %Check if ALLMETS is the first metabolite. Otherwise print a
+0155             %warning since it will write over any other constraints that
+0156             %are set
+0157             if K(1)==0
+0158                 EM=['ALLMETS is used as an output in "[' taskStructure(i).id '] ' taskStructure(i).description '" but it it not the first metabolite in the list. Constraints defined for the metabolites before it will be over-written'];
+0159                 dispEM(EM,false);
+0160             end
+0161             %Use the first match of ALLMETS. There should only be one, but
+0162             %still..
+0163             tModel.b(:,2)=taskStructure(i).UBout(find(K,1));
+0164         end
+0165         %If metabolites in a specific compartment should be used
+0166         if any(L)
+0167             L=find(L);
+0168             for j=1:numel(L)
+0169                 %The compartment defined
+0170                 compartment=upper(taskStructure(i).outputs{L(j)}(11:end-1));
+0171                 %Check if it exists in the model
+0172                 C=find(ismember(upper(model.comps),compartment));
+0173                 if any(C)
+0174                     %Match to metabolites
+0175                     tModel.b(model.metComps==C,2)=taskStructure(i).UBout(L(j));
+0176                 else
+0177                     EM=['The compartment defined for ALLMETSIN in "[' taskStructure(i).id '] ' taskStructure(i).description '" does not exist'];
+0178                     dispEM(EM);
+0179                 end
+0180             end
+0181         end
+0182         %Then add the normal constraints
+0183         if any(J)
+0184             %Verify that IN and OUT bounds are consistent. Cannot require
+0185             %that a metabolite is simultaneously input AND output at some
+0186             %nonzero flux.
+0187             I = find(I);  % otherwise indexing becomes confusing
+0188             nonzero_LBin = tModel.b(J,2) < 0;
+0189             nonzero_LBout = taskStructure(i).LBout(I) > 0;
+0190             if any(nonzero_LBin & nonzero_LBout)
+0191                 EM=['The IN LB and OUT LB in "[' taskStructure(i).id '] ' taskStructure(i).description '" cannot be nonzero for the same metabolite'];
+0192                 dispEM(EM);
+0193             end
+0194             tModel.b(J(nonzero_LBout),1)=taskStructure(i).LBout(I(nonzero_LBout));
+0195             tModel.b(J,2)=taskStructure(i).UBout(I);
+0196         end
+0197     end
+0198     %Add new rxns
+0199     if ~isempty(taskStructure(i).equations)
+0200         rxn.equations=taskStructure(i).equations;
+0201         rxn.lb=taskStructure(i).LBequ;
+0202         rxn.ub=taskStructure(i).UBequ;
+0203         rxn.rxns=strcat({'TEMPORARY_'},num2str((1:numel(taskStructure(i).equations))'));
+0204         %Allow for new metabolites to be added. This is because it should
+0205         %be possible to add, say, a whole new pathway
+0206         tModel=addRxns(tModel,rxn,3,[],true);
+0207     end
+0208     %Add changed bounds
+0209     if ~isempty(taskStructure(i).changed)
+0210         tModel=setParam(tModel,'lb',taskStructure(i).changed,taskStructure(i).LBrxn);
+0211         tModel=setParam(tModel,'ub',taskStructure(i).changed,taskStructure(i).UBrxn);
+0212     end
+0213     
+0214     %Solve and print
+0215     sol=solveLP(tModel);
+0216     if ~isempty(sol.x)
+0217         %assign the fluxes
+0218         essentialFluxes(:,i) = sol.x(1:numel(model.rxns));
+0219         
+0220         if ~taskStructure(i).shouldFail
+0221             taskReport.ok(i,1)=true;
+0222             if printOnlyFailed==false && printOutput==true
+0223                 fprintf(['PASS: [' taskStructure(i).id '] ' taskStructure(i).description '\n']);
+0224             end
+0225             %Calculate the essential reactions
+0226             if getEssential==true
+0227                 [~, taskEssential]=getEssentialRxns(tModel);
+0228                 %This is because there could be more reactions in tModel
+0229                 %than in model
+0230                 essentialRxns(taskEssential(taskEssential<=numel(model.rxns)),i)=true;
+0231             end
+0232         else
+0233             taskReport.ok(i,1)=false;
+0234             if printOutput==true
+0235                 fprintf(['PASS (should fail): [' taskStructure(i).id '] ' taskStructure(i).description '\n']);
+0236             end
+0237         end
+0238     else
+0239         if ~taskStructure(i).shouldFail
+0240             taskReport.ok(i,1)=false;
+0241             if printOutput==true
+0242                 fprintf(['FAIL: [' taskStructure(i).id '] ' taskStructure(i).description '\n']);
+0243             end
+0244         else
+0245             taskReport.ok(i,1)=true;
+0246             if printOnlyFailed==false && printOutput==true
+0247                 fprintf(['FAIL (should fail): [' taskStructure(i).id '] ' taskStructure(i).description '\n']);
+0248             end
+0249         end
+0250     end
+0251     if taskStructure(i).printFluxes && ~isempty(sol.x)
+0252         sol=solveLP(tModel,1);
+0253         if ~isempty(sol.x)
+0254             printFluxes(tModel,sol.x,false,10^-6,[],'%rxnID (%eqn):%flux\n');
+0255             fprintf('\n');
+0256         end
+0257     end
+0258     tModel=model;
+0259 end
+0260 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/compareMultipleModels.html b/doc/core/compareMultipleModels.html new file mode 100644 index 000000000..9a36fa00d --- /dev/null +++ b/doc/core/compareMultipleModels.html @@ -0,0 +1,521 @@ + + + + Description of compareMultipleModels + + + + + + + + + +
Home > core > compareMultipleModels.m
+ + + +

compareMultipleModels +

+ +

PURPOSE ^

+
compareMultipleModels
+ +

SYNOPSIS ^

+
function compStruct = compareMultipleModels(models,printResults,plotResults,groupVector,funcCompare,taskFile)
+ +

DESCRIPTION ^

+
 compareMultipleModels
+   Compares two or more condition-specific models generated from the same
+   base model using high-dimensional comparisons in the reaction-space.
+
+   models              cell array of two or more models
+   printResults        true if the results should be printed on the screen
+                       (optional, default false)
+   plotResults         true if the results should be plotted
+                       (optional, default false)
+   groupVector         numeric vector or cell array for grouping similar 
+                       models, i.e. by tissue (optional, default, all models
+                       ungrouped)
+   funcCompare         logical, should a functional comparison be run
+                       (optional,default, false)
+   taskFile            string containing the name of the task file to use
+                       for the functional comparison (should be an .xls or 
+                       .xlsx file, required for functional comparison)
+
+   compStruct          structure that contains the comparison results
+       modelIDs        cell array of model ids
+       reactions       substructure containing reaction information
+           matrix          binary matrix composed of reactions (rows) in
+                           each model (column). This matrix is used as the
+                           input for the model comparisons.
+           IDs             list of the reactions contained in the reaction
+                           matrix.
+       subsystems      substructure containing subsystem information
+           matrix          matrix with comparison of number of rxns per
+                           subsystem
+           ID              vector consisting of names of all subsystems
+       structComp      matrix with pairwise comparisons of model structure
+                       based on (1-Hamming distance) between models
+       structCompMap   matrix with 3D tSNE (or MDS) mapping of model
+                       structures based on Hamming distances
+       funcComp        substructure containing function comparison results
+           matrix          matrix with PASS / FAIL (1 / 0) values for each
+                           task
+           tasks           vector containing names of all tasks
+
+ Usage: compStruct=compareMultipleModels(models,printResults,...
+                       plotResults,groupVector,funcCompare,taskFile);
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 function compStruct = compareMultipleModels(models,printResults,plotResults,groupVector,funcCompare,taskFile)
+0002 % compareMultipleModels
+0003 %   Compares two or more condition-specific models generated from the same
+0004 %   base model using high-dimensional comparisons in the reaction-space.
+0005 %
+0006 %   models              cell array of two or more models
+0007 %   printResults        true if the results should be printed on the screen
+0008 %                       (optional, default false)
+0009 %   plotResults         true if the results should be plotted
+0010 %                       (optional, default false)
+0011 %   groupVector         numeric vector or cell array for grouping similar
+0012 %                       models, i.e. by tissue (optional, default, all models
+0013 %                       ungrouped)
+0014 %   funcCompare         logical, should a functional comparison be run
+0015 %                       (optional,default, false)
+0016 %   taskFile            string containing the name of the task file to use
+0017 %                       for the functional comparison (should be an .xls or
+0018 %                       .xlsx file, required for functional comparison)
+0019 %
+0020 %   compStruct          structure that contains the comparison results
+0021 %       modelIDs        cell array of model ids
+0022 %       reactions       substructure containing reaction information
+0023 %           matrix          binary matrix composed of reactions (rows) in
+0024 %                           each model (column). This matrix is used as the
+0025 %                           input for the model comparisons.
+0026 %           IDs             list of the reactions contained in the reaction
+0027 %                           matrix.
+0028 %       subsystems      substructure containing subsystem information
+0029 %           matrix          matrix with comparison of number of rxns per
+0030 %                           subsystem
+0031 %           ID              vector consisting of names of all subsystems
+0032 %       structComp      matrix with pairwise comparisons of model structure
+0033 %                       based on (1-Hamming distance) between models
+0034 %       structCompMap   matrix with 3D tSNE (or MDS) mapping of model
+0035 %                       structures based on Hamming distances
+0036 %       funcComp        substructure containing function comparison results
+0037 %           matrix          matrix with PASS / FAIL (1 / 0) values for each
+0038 %                           task
+0039 %           tasks           vector containing names of all tasks
+0040 %
+0041 % Usage: compStruct=compareMultipleModels(models,printResults,...
+0042 %                       plotResults,groupVector,funcCompare,taskFile);
+0043 
+0044 %% Stats toolbox required
+0045 if ~(exist('mdscale.m','file') && exist('pdist.m','file') && exist('squareform.m','file') && exist('tsne.m','file'))
+0046     error('The MATLAB Statistics and Machine Learning Toolbox is required for this function')
+0047 end
+0048 
+0049 %% Set up input defaults
+0050 if nargin < 2 || isempty(printResults)
+0051     printResults=false;
+0052 end
+0053 if nargin < 3 || isempty(plotResults)
+0054     plotResults=false;
+0055 end
+0056 if nargin < 4
+0057     groupVector = [];
+0058 elseif ~isnumeric(groupVector)
+0059     % convert strings to numeric groups
+0060     [groupNames,~,groupVector] = unique(groupVector);
+0061 else
+0062     % generate group names for vector of numbers
+0063     groupNames = arrayfun(@num2str,unique(groupVector),'UniformOutput',false);
+0064 end
+0065 if nargin < 5 || isempty(funcCompare)
+0066     funcCompare = false;
+0067 end
+0068 if nargin < 6
+0069     taskFile = [];
+0070 else
+0071     taskFile=char(taskFile);
+0072 end
+0073 if numel(models) <= 1
+0074     EM = 'Cannot compare only one model. Use printModelStats if you want a summary of a model';
+0075     dispEM(EM);
+0076 end
+0077 if isempty(taskFile) && funcCompare
+0078     EM = 'Cannot perform the functional comparison without a task file. Specify taskFile or set funcCompare to FALSE.';
+0079     dispEM(EM);
+0080 end
+0081 
+0082 %% Set up model ID structure
+0083 compStruct.modelIDs = {};
+0084 fprintf('\n Getting model IDs \n')    
+0085 for i = 1:numel(models)
+0086     if ~ischar(models{i}.id)  % to deal with non-character IDs (cells, strings, etc)
+0087         compStruct.modelIDs{i,1} = models{i}.id{1};
+0088     else
+0089         compStruct.modelIDs{i,1} = models{i}.id;
+0090     end
+0091 end
+0092 fprintf('*** Done \n\n')
+0093 
+0094 
+0095 %% Compare models structure & function based on high-dimensional methods
+0096 % Compare number of reactions in each subsystem in each model using a heatmap
+0097 field = 'subSystems';
+0098 fprintf('\n Comparing subsystem utilization \n')
+0099 if any(~cellfun(@(m) isfield(m,field),models))
+0100     fprintf('\nWARNING: At least one model does not contain the field "subSystems". \n')
+0101     fprintf('         Skipping subsystem comparison. \n\n')
+0102 else
+0103     %% Flatten model subSystems field
+0104     % Convert from cell array of cells to cell array of strings
+0105     % NOTE: this function currently only recognizes one subSystem per reaction;
+0106     %       additional subSystems will be ignored!
+0107     for i = 1:numel(models)
+0108         if any(cellfun(@(x) iscell(x), models{i}.subSystems));
+0109             cells = cellfun(@iscell,models{i}.subSystems);
+0110             models{i}.subSystems(cells) = cellfun(@(s) s{1}, models{i}.subSystems(cells), 'UniformOutput', false);
+0111         end
+0112     end
+0113     [id,compMat] = compareModelField(models,field);
+0114     compStruct.subsystems.ID = id;
+0115     compStruct.subsystems.matrix = compMat;
+0116     fprintf('*** Done \n\n')
+0117     
+0118     if printResults
+0119         % This could use some cleaning up
+0120         fprintf('*** Comparison of reaction subsystem populations:\n\n');
+0121         
+0122         nrow = min([15,numel(compStruct.subsystems.ID)]);
+0123         ncol = min([10,numel(compStruct.modelIDs)]);
+0124         summaryArray = [{field}, compStruct.modelIDs(1:ncol)'];
+0125         summaryArray = [summaryArray; [compStruct.subsystems.ID(1:nrow), ...
+0126             arrayfun(@num2str,compStruct.subsystems.matrix(1:nrow,1:ncol),'UniformOutput',false)]];
+0127         
+0128         charArray = [];
+0129         for i = 1:size(summaryArray,2)
+0130             charArray = [charArray, char(strcat(summaryArray(:,i),{'   '}))];
+0131         end
+0132         disp(charArray);
+0133         if numel(compStruct.subsystems.ID) > 15
+0134             fprintf('...\n');
+0135         end
+0136         fprintf('\n\n');
+0137     end
+0138     
+0139     if plotResults==true
+0140         % Plot all subsystems
+0141         figure;
+0142         plottingData = (compStruct.subsystems.matrix - mean(compStruct.subsystems.matrix,2))./mean(compStruct.subsystems.matrix,2);
+0143         color_map = redblue(length(0:.01:2));
+0144         h = genHeatMap(plottingData',compStruct.subsystems.ID,compStruct.modelIDs,'both','euclidean',color_map,[-1,1]);
+0145         title('Subsystem Coverage - all subsystems','FontSize',18,'FontWeight','bold')
+0146         
+0147         % Plot only subsystems with deviation from mean
+0148         keepSubs = (sum(plottingData~=0,2) ~= 0);
+0149         if sum(keepSubs) > 1
+0150             figure;
+0151             h_small = genHeatMap(plottingData(keepSubs,:)',compStruct.subsystems.ID(keepSubs),...
+0152                 compStruct.modelIDs,'both','euclidean',color_map,[-1,1]);
+0153             title('Subsystem Coverage','FontSize',18,'FontWeight','bold')
+0154             
+0155             % Plot enrichment in subsystems with deviation from mean
+0156             figure;
+0157             color_map_bw = [1 1 1;0 0 0];
+0158             h_enriched = genHeatMap(plottingData(keepSubs,:)',compStruct.subsystems.ID(keepSubs),...
+0159                 compStruct.modelIDs,'both','euclidean',color_map_bw,[-10^-4,10^-4]);
+0160             title('Subsystem Enrichment','FontSize',18,'FontWeight','bold')
+0161         end
+0162     end
+0163     
+0164 end
+0165 
+0166 % Compare overall reaction structure across all models using a heatmap
+0167 field = 'rxns';
+0168 fprintf('\n Comparing model reaction correlations \n')
+0169 
+0170 % Create binary matrix of reactions
+0171 [id,binary_matrix] = compareModelField(models,field);
+0172 compStruct.reactions.IDs = id;
+0173 compStruct.reactions.matrix = binary_matrix;
+0174 
+0175 % calculate hamming similarity
+0176 compStruct.structComp = 1-squareform(pdist(binary_matrix','hamming'));
+0177 fprintf('*** Done \n\n')
+0178 if plotResults == true
+0179     color_map = [ones(100,1) linspace(1,0,100)' linspace(1,0,100)'];
+0180     figure;
+0181     h = genHeatMap(compStruct.structComp,compStruct.modelIDs,compStruct.modelIDs,'both','euclidean',color_map);
+0182     title('Structural Similarity','FontSize',18,'FontWeight','bold')
+0183 end
+0184 
+0185 % Compare overall reaction structure across all models using tSNE projection
+0186 rng(42) % For consistency
+0187 fprintf('\n Comparing model reaction structures \n')
+0188 if exist('tsne') > 0
+0189     proj_coords = tsne(double(binary_matrix'),'Distance','hamming','NumDimensions',3); % 3D
+0190     compStruct.structCompMap = proj_coords;
+0191     axis_labels = {'tSNE 1';'tSNE 2';'tSNE 3'};
+0192 else % Seems odd to use mdscale if tsne is not found, as both are
+0193      % distributed with stats toolbox. If tsne is not present, then also
+0194      % mdscale is missing. Anyway, will leave this for now.
+0195     [proj_coords,stress,disparities] = mdscale(pdist(double(binary_matrix'),'hamming'),3);
+0196     compStruct.structCompMap = proj_coords;
+0197     axis_labels = {'MDS 1';'MDS 2';'MDS 3'};
+0198 end
+0199 fprintf('*** Done \n\n')
+0200 
+0201 % plot structure comparison results
+0202 if plotResults == true
+0203     figure; hold on;
+0204     if ~isempty(groupVector)
+0205         color_data = groupVector;
+0206         if length(groupNames) <= 7
+0207             % "lines" colormap only has 7 unique colors
+0208             color_palette = lines(length(groupNames));
+0209         else
+0210             color_palette = parula(length(groupNames));
+0211         end
+0212         colormap(color_palette);
+0213     else
+0214         color_data = 'k';
+0215     end
+0216     scatter3(proj_coords(:,1),proj_coords(:,2),proj_coords(:,3),35,color_data,'filled');
+0217     view(135,25);  % to make it obvious that it is a 3D plot
+0218     xlabel(axis_labels{1}); ylabel(axis_labels{2}); zlabel(axis_labels{3});
+0219     set(gca,'FontSize',14,'LineWidth',1.25);
+0220     title('Structural Comparison','FontSize',18,'FontWeight','bold')
+0221     
+0222     % add legend
+0223     if ~isempty(groupVector)
+0224         for i = 1:length(groupNames)
+0225             h(i) = scatter3([],[],[],35,color_palette(i,:),'filled');
+0226         end
+0227         legend(h,groupNames);
+0228     end
+0229 end
+0230 
+0231 % Compare model functions by assessing their capacity to perform tasks
+0232 if funcCompare == true && ~isempty(taskFile)
+0233     fprintf('\n Checking model performance on specified tasks. \n')
+0234     taskStructure=parseTaskList(taskFile);
+0235     for i = 1:numel(models)
+0236         fprintf('\n Checking model # %.0f \n',i)
+0237         taskReport{i} = checkTasks(models{i},[],false,false,false,taskStructure);
+0238     end    
+0239     
+0240     % Save results
+0241     taskMatrix = zeros(length(taskReport{1}.ok),numel(taskReport));
+0242         for i = 1:numel(taskReport)
+0243             taskMatrix(:,i) = taskReport{i}.ok;
+0244         end
+0245     compStruct.funcComp.matrix = taskMatrix;
+0246     compStruct.funcComp.tasks = taskReport{1}.description;
+0247     fprintf('*** Done \n\n')
+0248    
+0249     % Plot results
+0250     if plotResults == true
+0251         figure;
+0252         color_map_bw = [1 1 1;0 0 0];
+0253         h_enriched = genHeatMap(taskMatrix,compStruct.modelIDs,...
+0254             taskReport{1}.description,'both','euclidean',color_map_bw,[0,1]);
+0255         title('Functional Comparison - All Tasks','FontSize',18,'FontWeight','bold')
+0256         
+0257         figure;
+0258         color_map_bw = [1 1 1;0 0 0];
+0259         h_enriched = genHeatMap(taskMatrix(intersect(find(sum(taskMatrix,2)~=numel(models)),find(sum(taskMatrix,2)~=0)),:),...
+0260             compStruct.modelIDs,taskReport{1}.description(intersect(find(sum(taskMatrix,2)~=numel(models)),find(sum(taskMatrix,2)~=0))),...
+0261             'both','euclidean',color_map_bw,[0,1]);
+0262         title('Functional Similarity','FontSize',18,'FontWeight','bold')
+0263     end
+0264 end
+0265 
+0266 end
+0267 
+0268 %% Additional Functions
+0269 
+0270 function [id,compMat] = compareModelField(models,field)
+0271     % Generates a list of unique field entries and a matrix quantifying the
+0272     % number of appearances of each field entry in each model
+0273     
+0274     % get unique list of field entries
+0275     hasfield = cellfun(@(m) isfield(m,field),models);
+0276     id = cellfun(@(m) m.(field),models(hasfield),'UniformOutput',false);
+0277     id = unique(vertcat(id{:}));
+0278     
+0279     % assemble matrix comparing frequency of each entry in each model
+0280     compMat = zeros(numel(id),numel(models));
+0281     for i = 1:numel(models)
+0282         [~,entryIndex] = ismember(models{i}.(field),id);  % get index of each field entry in the unique id list
+0283         compMat(:,i) = histcounts(entryIndex, 0.5:1:(numel(id)+0.5));  % determine the frequency at which each index appears
+0284     end
+0285 end
+0286 
+0287 
+0288 function h = genHeatMap(data,colnames,rownames,clust_dim,clust_dist,col_map,col_bounds,grid_color)
+0289 %genHeatMap  Generate a heatmap for a given matrix of data.
+0290 %
+0291 % Usage:
+0292 %
+0293 %   genHeatMap(data,colnames,rownames,clust_dim,clust_dist,col_map,col_bounds,grid_color);
+0294 %
+0295 % Inputs:
+0296 %
+0297 % data        Numerical matrix.
+0298 %
+0299 % colnames    Cell array of data column names.
+0300 %
+0301 % rownames    Cell array of data row names.
+0302 %
+0303 % clust_dim   'none' - the data will be plotted as provided (DEFAULT)
+0304 %             'rows' - cluster/rearrange the rows based on distance
+0305 %             'cols' - cluster/rearrange the columns based on distance
+0306 %             'both' - cluster/rearrange rows and columns based on distance
+0307 %
+0308 % clust_dist  Distance metric to be used for clustering, ignored if
+0309 %             clust_dim is 'none'. Options are the same as those for
+0310 %             distance in, e.g., PDIST ('euclidean', 'hamming', etc.).
+0311 %             (DEFAULT = 'euclidean')
+0312 %
+0313 % col_map     Colormap, provided as string (e.g., 'parula', 'hot', 'etc.')
+0314 %             or an Nx3 RGB matrix of N colors.
+0315 %             (DEFAULT = 'hot')
+0316 %
+0317 % col_bounds  A 2-element vector with min and max values, to manually set
+0318 %             the bounds of the colormap.
+0319 %             (DEFAULT = min/max of data).
+0320 %
+0321 % grid_color  Color of the grid surrounding the heatmap cells.
+0322 %             (DEFAULT = 'none')
+0323 %
+0324 %
+0325 
+0326 % handle input arguments
+0327 if nargin < 4 || isempty(clust_dim)
+0328     clust_dim = 'none';
+0329 elseif ~ismember(clust_dim,{'none','rows','cols','both'})
+0330     error('%s is not a valid CLUST_DIM option. Choose "none", "rows", "cols", or "both".',clust_dim);
+0331 end
+0332 if nargin < 5 || isempty(clust_dist)
+0333     clust_dist = 'euclidean';
+0334 end
+0335 if nargin < 6 || isempty(col_map)
+0336     col_map = 'hot';
+0337 end
+0338 if nargin < 7 || isempty(col_bounds)
+0339     col_bounds = [min(data(:)),max(data(:))];
+0340 end
+0341 if nargin < 8
+0342     grid_color = 'none';
+0343 end
+0344 
+0345 % perform hierarchical clustering to sort rows (if specified)
+0346 linkage_method = 'average';
+0347 if ismember(clust_dim,{'rows','both'})
+0348     L = linkage(data,linkage_method,clust_dist);
+0349     row_ind = optimalleaforder(L,pdist(data,clust_dist));
+0350 else
+0351     row_ind = 1:size(data,1);
+0352 end
+0353 % perform hierarchical clustering to sort columns (if specified)
+0354 if ismember(clust_dim,{'cols','both'})
+0355     L = linkage(data',linkage_method,clust_dist);
+0356     col_ind = optimalleaforder(L,pdist(data',clust_dist));
+0357 else
+0358     col_ind = 1:size(data,2);
+0359 end
+0360 
+0361 % reorder data matrix according to clustering results
+0362 sortdata = data(row_ind,col_ind);
+0363 sortrows = rownames(row_ind);
+0364 sortcols = colnames(col_ind);
+0365 
+0366 % check if data is square matrix with identical row and column names
+0367 if (length(colnames) == length(rownames)) && all(strcmp(colnames,rownames))
+0368     % flip data so the diagonal is from upper left to lower right
+0369     sortdata = fliplr(sortdata);
+0370     sortcols = flipud(sortcols);
+0371 end
+0372 
+0373 % pad data matrix with zeros (pcolor cuts off last row and column)
+0374 sortdata(end+1,end+1) = 0;
+0375 
+0376 % generate pcolor plot
+0377 a = axes;
+0378 set(a,'YAxisLocation','Right','XTick',[],'YTick', (1:size(sortdata,1))+0.5,'YTickLabels',sortrows);
+0379 set(a,'TickLength',[0 0],'XLim',[1 size(sortdata,2)],'YLim',[1 size(sortdata,1)]);
+0380 hold on
+0381 
+0382 h = pcolor(sortdata);
+0383 set(h,'EdgeColor',grid_color);
+0384 set(gca,'XTick', (1:size(sortdata,2))+0.5);
+0385 set(gca,'YTick', (1:size(sortdata,1))+0.5);
+0386 set(gca,'XTickLabels',sortcols,'YTickLabels',sortrows);
+0387 set(gca,'XTickLabelRotation',90);
+0388 colormap(col_map);
+0389 
+0390 if ~isempty(col_bounds)
+0391     caxis(col_bounds);
+0392 end
+0393 
+0394 end
+0395 
+0396 
+0397 function c = redblue(m)
+0398 %REDBLUE    Shades of red and blue color map
+0399 %   REDBLUE(M), is an M-by-3 matrix that defines a colormap.
+0400 %   The colors begin with bright blue, range through shades of
+0401 %   blue to white, and then through shades of red to bright red.
+0402 %   REDBLUE, by itself, is the same length as the current figure's
+0403 %   colormap. If no figure exists, MATLAB creates one.
+0404 %
+0405 %   For example, to reset the colormap of the current figure:
+0406 %
+0407 %             colormap(redblue)
+0408 %
+0409 %   See also HSV, GRAY, HOT, BONE, COPPER, PINK, FLAG,
+0410 %   COLORMAP, RGBPLOT.
+0411 if nargin < 1, m = size(get(gcf,'colormap'),1); end
+0412 
+0413 if (mod(m,2) == 0)
+0414     % From [0 0 1] to [1 1 1], then [1 1 1] to [1 0 0];
+0415     m1 = m*0.5;
+0416     r = (0:m1-1)'/max(m1-1,1);
+0417     g = r;
+0418     r = [r; ones(m1,1)];
+0419     g = [g; flipud(g)];
+0420     b = flipud(r);
+0421 else
+0422     % From [0 0 1] to [1 1 1] to [1 0 0];
+0423     m1 = floor(m*0.5);
+0424     r = (0:m1-1)'/max(m1,1);
+0425     g = r;
+0426     r = [r; ones(m1+1,1)];
+0427     g = [g; 1; flipud(g)];
+0428     b = flipud(r);
+0429 end
+0430 
+0431 c = [r g b];
+0432 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/compareRxnsGenesMetsComps.html b/doc/core/compareRxnsGenesMetsComps.html new file mode 100644 index 000000000..8fd6da1bb --- /dev/null +++ b/doc/core/compareRxnsGenesMetsComps.html @@ -0,0 +1,247 @@ + + + + Description of compareRxnsGenesMetsComps + + + + + + + + + +
Home > core > compareRxnsGenesMetsComps.m
+ + + +

compareRxnsGenesMetsComps +

+ +

PURPOSE ^

+
compareRxnsGenesMetsComps
+ +

SYNOPSIS ^

+
function compStruct=compareRxnsGenesMetsComps(models,printResults)
+ +

DESCRIPTION ^

+
 compareRxnsGenesMetsComps
+   Compares two or more models with respect to overlap in terms of genes,
+   reactions, metabolites and compartments.
+
+   models              cell array of two or more models
+   printResults        true if the results should be printed on the screen
+                       (optional, default false)
+
+   compStruct          structure that contains the comparison
+       modelIDs        cell array of model ids
+       rxns            These contain the comparison for each field. 'equ' are
+                       the equations after sorting and 'uEqu' are the
+                       equations when not taking compartmentalization into acount
+       mets
+       genes
+       eccodes
+       metNames
+       equ
+       uEqu
+           comparison    binary matrix where each row indicate which models are
+                       included in the comparison
+           nElements   vector with the number of elements for each
+                       comparison
+
+ Usage: compStruct=compareRxnsGenesMetsComps(models,printResults)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 function compStruct=compareRxnsGenesMetsComps(models,printResults)
+0002 % compareRxnsGenesMetsComps
+0003 %   Compares two or more models with respect to overlap in terms of genes,
+0004 %   reactions, metabolites and compartments.
+0005 %
+0006 %   models              cell array of two or more models
+0007 %   printResults        true if the results should be printed on the screen
+0008 %                       (optional, default false)
+0009 %
+0010 %   compStruct          structure that contains the comparison
+0011 %       modelIDs        cell array of model ids
+0012 %       rxns            These contain the comparison for each field. 'equ' are
+0013 %                       the equations after sorting and 'uEqu' are the
+0014 %                       equations when not taking compartmentalization into acount
+0015 %       mets
+0016 %       genes
+0017 %       eccodes
+0018 %       metNames
+0019 %       equ
+0020 %       uEqu
+0021 %           comparison    binary matrix where each row indicate which models are
+0022 %                       included in the comparison
+0023 %           nElements   vector with the number of elements for each
+0024 %                       comparison
+0025 %
+0026 % Usage: compStruct=compareRxnsGenesMetsComps(models,printResults)
+0027 
+0028 if nargin<2
+0029     printResults=true;
+0030 end
+0031 
+0032 if numel(models)<=1
+0033     EM='Cannot compare only one model. Use printModelStats if you want a summary of a model';
+0034     dispEM(EM);
+0035 end
+0036 
+0037 compStruct.modelIDs={};
+0038 for i=1:numel(models)
+0039     compStruct.modelIDs=[compStruct.modelIDs;models{i}.id];
+0040     models{i}.equ=constructEquations(models{i},models{i}.rxns,true,true,true);
+0041     models{i}.uEqu=constructEquations(models{i},models{i}.rxns,false,true,true);
+0042 end
+0043 
+0044 field='rxns';
+0045 compStruct.rxns.comparison=getToCheck(models,field);
+0046 compStruct.rxns.nElements=checkStuff(getElements(models,field),compStruct.rxns.comparison);
+0047 if printResults==true
+0048     fprintf('*** Comparison of reaction IDs:\n');
+0049     printList(models,compStruct.rxns.comparison,compStruct.rxns.nElements);
+0050     fprintf('\n\n');
+0051 end
+0052 
+0053 field='mets';
+0054 compStruct.mets.comparison=getToCheck(models,field);
+0055 compStruct.mets.nElements=checkStuff(getElements(models,field),compStruct.mets.comparison);
+0056 if printResults==true
+0057     fprintf('*** Comparison of metabolite IDs:\n');
+0058     printList(models,compStruct.mets.comparison,compStruct.mets.nElements);
+0059     fprintf('\n\n');
+0060 end
+0061 
+0062 field='genes';
+0063 compStruct.genes.comparison=getToCheck(models,field);
+0064 compStruct.genes.nElements=checkStuff(getElements(models,field),compStruct.genes.comparison);
+0065 if printResults==true
+0066     fprintf('*** Comparison of gene IDs:\n');
+0067     printList(models,compStruct.genes.comparison,compStruct.genes.nElements);
+0068     fprintf('\n\n');
+0069 end
+0070 
+0071 field='eccodes';
+0072 compStruct.eccodes.comparison=getToCheck(models,field);
+0073 compStruct.eccodes.nElements=checkStuff(getElements(models,field),compStruct.eccodes.comparison);
+0074 if printResults==true
+0075     fprintf('*** Comparison of ec-numbers:\n');
+0076     printList(models,compStruct.eccodes.comparison,compStruct.eccodes.nElements);
+0077     fprintf('\n\n');
+0078 end
+0079 
+0080 field='metNames';
+0081 compStruct.metNames.comparison=getToCheck(models,field);
+0082 compStruct.metNames.nElements=checkStuff(getElements(models,field),compStruct.metNames.comparison);
+0083 if printResults==true
+0084     fprintf('*** Comparison of metabolite names:\n');
+0085     printList(models,compStruct.metNames.comparison,compStruct.metNames.nElements);
+0086     fprintf('\n\n');
+0087 end
+0088 
+0089 field='equ';
+0090 compStruct.equ.comparison=getToCheck(models,field);
+0091 compStruct.equ.nElements=checkStuff(getElements(models,field),compStruct.equ.comparison);
+0092 if printResults==true
+0093     fprintf('*** Comparison of equations with compartment:\n');
+0094     printList(models,compStruct.equ.comparison,compStruct.equ.nElements);
+0095     fprintf('\n\n');
+0096 end
+0097 
+0098 field='uEqu';
+0099 compStruct.uEqu.comparison=getToCheck(models,field);
+0100 compStruct.uEqu.nElements=checkStuff(getElements(models,field),compStruct.uEqu.comparison);
+0101 if printResults==true
+0102     fprintf('*** Comparison of equations without compartment:\n');
+0103     printList(models,compStruct.uEqu.comparison,compStruct.uEqu.nElements);
+0104     fprintf('\n\n');
+0105 end
+0106 end
+0107 
+0108 function A=getElements(models,field)
+0109 A={};
+0110 for i=1:numel(models)
+0111     if isfield(models{i},field)
+0112         A=[A;{models{i}.(field)}];
+0113     end
+0114 end
+0115 end
+0116 
+0117 function toCheck=getToCheck(models,field)
+0118 %Get all the combinations that should be checked for overlap (including the
+0119 %single ones)
+0120 toCheckA=[];
+0121 I=find(cellfun(@checkField,models));
+0122 nI=numel(I);
+0123 for i=nI:-1:1
+0124     combs=combnk(1:nI,i);
+0125     toAdd=false(size(combs,1),nI);
+0126     for j=1:size(combs,1)
+0127         toAdd(j,combs(j,:))=true;
+0128     end
+0129     toCheckA=[toCheckA;toAdd];
+0130 end
+0131 
+0132 %If not all of the models have the required field
+0133 toCheck=false(size(toCheckA,1),numel(models));
+0134 toCheck(:,I)=toCheckA;
+0135 
+0136 %Ugly thing to get around parameters
+0137     function I=checkField(A)
+0138         I=isfield(A,field);
+0139     end
+0140 end
+0141 
+0142 function printList(models,toCheck,nElements)
+0143 %To guess how many spaces that are needed to align
+0144 firstLen=[];
+0145 for i=1:size(toCheck,1)
+0146     label=[];
+0147     I=find(toCheck(i,:));
+0148     for j=1:numel(I)
+0149         label=[label models{I(j)}.id '/'];
+0150     end
+0151     if i==1
+0152         firstLen=numel(label);
+0153     end
+0154     nSpaces=firstLen-numel(label);
+0155     fprintf([label(1:end-1) '  ' repmat(sprintf(' '),1,nSpaces) num2str(nElements(i)) '\n']);
+0156 end
+0157 end
+0158 
+0159 function nElements=checkStuff(A,toCheck)
+0160 %Now loop through the toCheck matrix, starting with the combination with
+0161 %the most models. Only elements that weren't in iteration n are considered
+0162 %in iteration n+1.
+0163 nElements=zeros(size(toCheck,1),1);
+0164 alreadyChecked=[];
+0165 for i=1:size(toCheck,1)
+0166     I=find(toCheck(i,:));
+0167     inCommon=setdiff(A{I(1)},alreadyChecked);
+0168     for j=2:numel(I)
+0169         inCommon=intersect(inCommon,A{I(j)});
+0170     end
+0171     alreadyChecked=union(alreadyChecked,inCommon);
+0172     nElements(i)=numel(inCommon);
+0173 end
+0174 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/constructEquations.html b/doc/core/constructEquations.html new file mode 100644 index 000000000..aa6eb6d07 --- /dev/null +++ b/doc/core/constructEquations.html @@ -0,0 +1,182 @@ + + + + Description of constructEquations + + + + + + + + + +
Home > core > constructEquations.m
+ + + +

constructEquations +

+ +

PURPOSE ^

+
constructEquations
+ +

SYNOPSIS ^

+
function equationStrings=constructEquations(model,rxns,useComps,sortRevRxns,sortMetNames,useMetID,useFormula,useRevField)
+ +

DESCRIPTION ^

+
 constructEquations
+   Construct equation strings for reactions
+
+ Input:
+   model             a model structure
+   rxns              either a cell array of reaction IDs, a logical vector
+                     with the same number of elements as reactions in the
+                     model, or a vector of reaction indexes (optional, default
+                     model.rxns)
+   useComps          include the compartment of each metabolite (optional,
+                     default true)
+   sortRevRxns       sort reversible reactions so that the metabolite that
+                     is first in the lexiographic order is a reactant
+                     (optional, default false)
+   sortMetNames      sort the metabolite names in the equation. Uses
+                     compartment even if useComps is false (optional, default
+                     false)
+   useMetID          use metabolite ID in generated equations (optional,
+                     default false)
+   useFormula        use metabolite formula in generated equations (optional,
+                     default false)
+   useRevField       use the model.rev field to indicate reaction
+                     reversibility, alternatively this is determined from
+                     the model.ub and model.lb fields (optional, default true)
+
+ Output:
+   equationStrings   a cell array with equations
+
+ If useRevField is false, then reactions should be organized in their
+ forward direction (e.g. ub = 1000 and lb = -1000/0) for the 
+ reversibility to be correctly determined.
+
+ Usage: equationStrings = constructEquations(model, rxns, useComps,...
+           sortRevRxns, sortMetNames, useMetID, useFormula, useRevField)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function equationStrings=constructEquations(model,rxns,useComps,sortRevRxns,sortMetNames,useMetID,useFormula,useRevField)
+0002 % constructEquations
+0003 %   Construct equation strings for reactions
+0004 %
+0005 % Input:
+0006 %   model             a model structure
+0007 %   rxns              either a cell array of reaction IDs, a logical vector
+0008 %                     with the same number of elements as reactions in the
+0009 %                     model, or a vector of reaction indexes (optional, default
+0010 %                     model.rxns)
+0011 %   useComps          include the compartment of each metabolite (optional,
+0012 %                     default true)
+0013 %   sortRevRxns       sort reversible reactions so that the metabolite that
+0014 %                     is first in the lexiographic order is a reactant
+0015 %                     (optional, default false)
+0016 %   sortMetNames      sort the metabolite names in the equation. Uses
+0017 %                     compartment even if useComps is false (optional, default
+0018 %                     false)
+0019 %   useMetID          use metabolite ID in generated equations (optional,
+0020 %                     default false)
+0021 %   useFormula        use metabolite formula in generated equations (optional,
+0022 %                     default false)
+0023 %   useRevField       use the model.rev field to indicate reaction
+0024 %                     reversibility, alternatively this is determined from
+0025 %                     the model.ub and model.lb fields (optional, default true)
+0026 %
+0027 % Output:
+0028 %   equationStrings   a cell array with equations
+0029 %
+0030 % If useRevField is false, then reactions should be organized in their
+0031 % forward direction (e.g. ub = 1000 and lb = -1000/0) for the
+0032 % reversibility to be correctly determined.
+0033 %
+0034 % Usage: equationStrings = constructEquations(model, rxns, useComps,...
+0035 %           sortRevRxns, sortMetNames, useMetID, useFormula, useRevField)
+0036 
+0037 if nargin<2 || isempty(rxns)
+0038     rxns=model.rxns;
+0039 elseif ~islogical(rxns) && ~isnumeric(rxns)
+0040     rxns=convertCharArray(rxns);
+0041 end
+0042 if nargin<3
+0043     useComps=true;
+0044 end
+0045 if nargin<4
+0046     sortRevRxns=false;
+0047 end
+0048 if nargin<5
+0049     sortMetNames=false;
+0050 end
+0051 if nargin<6
+0052     useMetID=false;
+0053 end
+0054 if nargin<7
+0055     useFormula=false;
+0056 end
+0057 if nargin<8
+0058     useRevField=true;
+0059 end
+0060 
+0061 %Sort reversible equations
+0062 if sortRevRxns==true
+0063     model=sortModel(model);
+0064 end
+0065 
+0066 %Sort metabolite names, including compartment
+0067 if sortMetNames==true
+0068     model=sortModel(model,false,true);
+0069 end
+0070 
+0071 Rindexes=getIndexes(model,rxns,'rxns');
+0072 
+0073 equationStrings=cell(numel(Rindexes),1);
+0074 
+0075 for i=1:numel(Rindexes)
+0076     Mindexes=find(model.S(:,Rindexes(i)));
+0077     %Define metabolites by id, formula or name, and with or without compartment:
+0078     if useMetID==true && useFormula==false
+0079         mets = model.mets(Mindexes);
+0080     elseif useMetID==false && useFormula==true
+0081         mets = strcat('[',model.metFormulas(Mindexes),']');
+0082     elseif useMetID==true && useFormula==true
+0083         error('Arguments useMetID and useFormula cannot be both TRUE!');
+0084     else
+0085         mets = model.metNames(Mindexes);
+0086     end
+0087     if useComps==true
+0088         comps = model.comps(model.metComps(Mindexes));
+0089         mets  = strcat(mets,'[',comps,']');
+0090     end
+0091     %Define stoich coeffs and reversibility:
+0092     stoichCoeffs = model.S(Mindexes,Rindexes(i));
+0093     if useRevField == true
+0094         isrev        = model.rev(Rindexes(i))==1;
+0095     else
+0096         isrev        = model.lb(Rindexes(i))<0 & model.ub(Rindexes(i))>0;
+0097     end
+0098     
+0099     %Construct equation:
+0100     equationStrings{i} = buildEquation(mets,stoichCoeffs,isrev);
+0101 end
+0102 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/constructS.html b/doc/core/constructS.html new file mode 100644 index 000000000..0ba99957d --- /dev/null +++ b/doc/core/constructS.html @@ -0,0 +1,250 @@ + + + + Description of constructS + + + + + + + + + +
Home > core > constructS.m
+ + + +

constructS +

+ +

PURPOSE ^

+
constructS
+ +

SYNOPSIS ^

+
function [S, mets, badRxns, reversible]=constructS(equations,mets,rxns)
+ +

DESCRIPTION ^

+
 constructS
+   Constructs a stoichiometric matrix from a cell array of equations
+
+   equations   cell array of equations on the form 'A + 2 B <=> 3 C',
+               where <=> indicates reversible and => irreversible reactions
+   mets        cell array of metabolites. All metabolites in the equations
+               must be present in the list (optional, default generated from
+               the equations)
+   rxns        cell array of reaction ids. This is only used for printing
+               reaction ids instead of equations in warnings/errors (optional,
+               default [])
+
+   S           the resulting stoichiometric matrix mets cell array with
+               metabolites that corresponds to the order in the S matrix
+   badRxns     boolean vector with the reactions that have one or more
+               metabolites as both substrate and product. An example would
+               be the phosphotransferase ATP + ADP <=> ADP + ATP. In the
+               stoichiometric matrix this equals to an empty reaction
+               which can be problematic
+   reversible  boolean vector with true if the equation is reversible
+
+ Usage: [S, mets, badRxns, reversible]=constructS(equations,mets)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 function [S, mets, badRxns, reversible]=constructS(equations,mets,rxns)
+0002 % constructS
+0003 %   Constructs a stoichiometric matrix from a cell array of equations
+0004 %
+0005 %   equations   cell array of equations on the form 'A + 2 B <=> 3 C',
+0006 %               where <=> indicates reversible and => irreversible reactions
+0007 %   mets        cell array of metabolites. All metabolites in the equations
+0008 %               must be present in the list (optional, default generated from
+0009 %               the equations)
+0010 %   rxns        cell array of reaction ids. This is only used for printing
+0011 %               reaction ids instead of equations in warnings/errors (optional,
+0012 %               default [])
+0013 %
+0014 %   S           the resulting stoichiometric matrix mets cell array with
+0015 %               metabolites that corresponds to the order in the S matrix
+0016 %   badRxns     boolean vector with the reactions that have one or more
+0017 %               metabolites as both substrate and product. An example would
+0018 %               be the phosphotransferase ATP + ADP <=> ADP + ATP. In the
+0019 %               stoichiometric matrix this equals to an empty reaction
+0020 %               which can be problematic
+0021 %   reversible  boolean vector with true if the equation is reversible
+0022 %
+0023 % Usage: [S, mets, badRxns, reversible]=constructS(equations,mets)
+0024 
+0025 equations=convertCharArray(equations);
+0026 switch nargin
+0027     case 2
+0028         mets=convertCharArray(mets);
+0029     case 3
+0030         rxns=convertCharArray(rxns);
+0031 end
+0032 
+0033 badRxns=false(numel(equations),1);
+0034 
+0035 %Check that no equations are too short to have reversibility data
+0036 I=cellfun(@numel,equations);
+0037 I=find(I<4,1);
+0038 if any(I)
+0039     if isempty(rxns)
+0040         EM=['The following equation does not have reversibility data: ' equations{I} ];
+0041         dispEM(EM);
+0042     else
+0043         EM=['The reaction ' rxns{I} ' does not have reversibility data'];
+0044         dispEM(EM);
+0045     end
+0046 end
+0047 
+0048 %Makes life a little easier
+0049 equations=strtrim(equations);
+0050 equations=fixEquations(equations);
+0051 
+0052 if nargin<2
+0053     mets=parseRxnEqu(equations);
+0054 end
+0055 if nargin<3
+0056     rxns=[];
+0057 end
+0058 
+0059 %Get which reactions are reversible
+0060 reversible=cellfun(@any,strfind(equations,' <=> '));
+0061 
+0062 %Make them all reversible. This is not all that neat, but nevermind
+0063 equations=strrep(equations,' => ',' <=> ');
+0064 
+0065 %Replace the the plus signs with some weird character that will be used for
+0066 %parsing
+0067 equations=strrep(equations,' + ', '€');
+0068 
+0069 %Generate the stoichiometric matrix
+0070 S=zeros(numel(mets),numel(equations));
+0071 
+0072 %Keep track of coefficients to be added to S-matrix
+0073 metsToS = cell(100000,1);
+0074 rxnsToS = zeros(100000,1);
+0075 coefToS = zeros(100000,1);
+0076 newEntry = 1;
+0077 %Loop through the equations and add the info to the S matrix
+0078 for i=1:numel(equations)
+0079     %Start by finding the position of the (=> or <=>)
+0080     arrowIndex=strfind(equations{i},' <=> ');
+0081     
+0082     if numel(arrowIndex)~=1
+0083         if isempty(rxns)
+0084             EM=['The following equation does not have reversibility data: ' equations{i} ];
+0085             dispEM(EM);
+0086         else
+0087             EM=['The reaction ' rxns{i} ' does not have reversibility data'];
+0088             dispEM(EM);
+0089         end
+0090     end
+0091     
+0092     reactants=regexp(equations{i}(1:arrowIndex-1),'€','split');
+0093     products=regexp(equations{i}(arrowIndex+5:end),'€','split');
+0094     
+0095     %If the splitting character is at the end (if exchange rxns), then an
+0096     %empty string will exist together with the real ones. Remove it
+0097     reactants(cellfun(@isempty,reactants))=[];
+0098     products(cellfun(@isempty,products))=[];
+0099     
+0100     %A vector where an element is -1 is the corresponding metabolite is a
+0101     %reactant and 1 if it's a product
+0102     multiplyWith=[ones(numel(reactants),1)*-1; ones(numel(products),1)];
+0103     
+0104     metabolites=strtrim([reactants products]);
+0105     
+0106     %Now loop through the reactants and see if the metabolite has a
+0107     %coefficient (it will look as 'number name')
+0108     for j=1:numel(metabolites)
+0109         space=strfind(metabolites{j},' ');
+0110         
+0111         if isempty(space)
+0112             %No coefficient
+0113             coeff=1;
+0114             name=metabolites{j};
+0115         else
+0116             coeff=str2double(metabolites{j}(1:space(1)));
+0117             
+0118             %If it was not a coefficiant
+0119             if isnan(coeff)
+0120                 coeff=1;
+0121                 name=strtrim(metabolites{j});
+0122             else
+0123                 name=strtrim(metabolites{j}(space(1)+1:end));
+0124             end
+0125         end
+0126         
+0127         %Find the name in the mets list [a b]=ismember(name,mets);
+0128         metsToS{newEntry}=name;
+0129         rxnsToS(newEntry)=i;
+0130         coefToS(newEntry)=coeff*multiplyWith(j);
+0131         newEntry=newEntry+1;
+0132     end
+0133 end
+0134 %Remove unused fields
+0135 metsToS(newEntry:end)=[];
+0136 rxnsToS(newEntry:end)=[];
+0137 coefToS(newEntry:end)=[];
+0138 
+0139 %Match to mets array
+0140 [metsPresent,metsLoc]=ismember(metsToS,mets);
+0141 
+0142 %Find badRxns
+0143 [~,I]=unique([rxnsToS,metsLoc],'rows','stable');
+0144 x=1:length(rxnsToS);
+0145 x(I)=[];
+0146 x=unique(rxnsToS(x));
+0147 badRxns(x)=true;
+0148 
+0149 if any(~metsPresent)
+0150     if isempty(rxns)
+0151         error(['Could not find the following metabolites in the metabolite list: ',...
+0152         strjoin(unique(metsToS(~metsPresent)),', ')],'')
+0153     else
+0154         missingMet = find(~metsPresent);
+0155         missingMet = strcat(metsToS(missingMet),' (reaction:',rxns(rxnsToS(missingMet)),')\n');
+0156         missingMet = strjoin(missingMet,'');
+0157         error(['Could not find the following metabolites (reaction indicated) in the metabolite list: \n' ...
+0158             missingMet '%s'],'');
+0159     end
+0160 end
+0161 linearIndices=sub2ind(size(S),metsLoc,rxnsToS);
+0162 S(linearIndices)=coefToS;
+0163 S=sparse(S);
+0164 end
+0165 
+0166 function equ=fixEquations(equ)
+0167 %If the equation starts with "=>" or "<=>" then add a space again. This is
+0168 %an alternative way to represent uptake reactions. The opposite way for
+0169 %producing reactions
+0170 equ=equ(:);
+0171 for i=1:numel(equ)
+0172     if strcmp(equ{i}(1:2),'=>') || strcmp(equ{i}(1:3),'<=>')
+0173         equ{i}=[' ' equ{i}];
+0174     else
+0175         if strcmp(equ{i}(end-1:end),'=>') || strcmp(equ{i}(end-2:end),'<=>')
+0176             equ{i}=[equ{i} ' '];
+0177         end
+0178     end
+0179 end
+0180 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/consumeSomething.html b/doc/core/consumeSomething.html new file mode 100644 index 000000000..77930041e --- /dev/null +++ b/doc/core/consumeSomething.html @@ -0,0 +1,263 @@ + + + + Description of consumeSomething + + + + + + + + + +
Home > core > consumeSomething.m
+ + + +

consumeSomething +

+ +

PURPOSE ^

+
consumeSomething
+ +

SYNOPSIS ^

+
function [solution, metabolite]=consumeSomething(model,ignoreMets,isNames,minNrFluxes,params,ignoreIntBounds)
+ +

DESCRIPTION ^

+
 consumeSomething
+   Tries to consume any metabolite using as few reactions as possible.
+   The intended use is when you want to make sure that you model cannot
+   consume anything without producing something. It is intended to be used
+   with no active exchange reactions.
+
+   model           a model structure
+   ignoreMets      either a cell array of metabolite IDs, a logical vector
+                   with the same number of elements as metabolites in the model,
+                   of a vector of indexes for metabolites to exclude from
+                   this analysis (optional, default [])
+   isNames         true if the supplied mets represent metabolite names
+                   (as opposed to IDs). This is a way to delete
+                   metabolites in several compartments at once without
+                   knowing the exact IDs. This only works if ignoreMets
+                   is a cell array (optional, default false)
+   minNrFluxes     solves the MILP problem of minimizing the number of
+                   fluxes instead of the sum. Slower, but can be
+                   used if the sum gives too many fluxes (optional, default
+                   false)
+   params          *obsolete option*
+   ignoreIntBounds    true if internal bounds (including reversibility)
+                   should be ignored. Exchange reactions are not affected.
+                   This can be used to find unbalanced solutions which are
+                   not possible using the default constraints (optional,
+                   default false)
+
+   solution        flux vector for the solution
+   metabolite      the index of the metabolite(s) which was consumed. If
+                   possible only one metabolite is reported, but there are
+                   situations where metabolites can only be consumed in
+                   pairs (or more)
+
+   NOTE: This works by forcing at least 1 unit of "any metabolites" to be
+   consumed and then minimize for the sum of fluxes. If more than one
+   metabolite is consumed, it picks one of them to be consumed and then
+   minimizes for the sum of fluxes.
+
+ Usage: [solution, metabolite]=consumeSomething(model,ignoreMets,isNames,...
+               minNrFluxes,params,ignoreIntBounds)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function [solution, metabolite]=consumeSomething(model,ignoreMets,isNames,minNrFluxes,params,ignoreIntBounds)
+0002 % consumeSomething
+0003 %   Tries to consume any metabolite using as few reactions as possible.
+0004 %   The intended use is when you want to make sure that you model cannot
+0005 %   consume anything without producing something. It is intended to be used
+0006 %   with no active exchange reactions.
+0007 %
+0008 %   model           a model structure
+0009 %   ignoreMets      either a cell array of metabolite IDs, a logical vector
+0010 %                   with the same number of elements as metabolites in the model,
+0011 %                   of a vector of indexes for metabolites to exclude from
+0012 %                   this analysis (optional, default [])
+0013 %   isNames         true if the supplied mets represent metabolite names
+0014 %                   (as opposed to IDs). This is a way to delete
+0015 %                   metabolites in several compartments at once without
+0016 %                   knowing the exact IDs. This only works if ignoreMets
+0017 %                   is a cell array (optional, default false)
+0018 %   minNrFluxes     solves the MILP problem of minimizing the number of
+0019 %                   fluxes instead of the sum. Slower, but can be
+0020 %                   used if the sum gives too many fluxes (optional, default
+0021 %                   false)
+0022 %   params          *obsolete option*
+0023 %   ignoreIntBounds    true if internal bounds (including reversibility)
+0024 %                   should be ignored. Exchange reactions are not affected.
+0025 %                   This can be used to find unbalanced solutions which are
+0026 %                   not possible using the default constraints (optional,
+0027 %                   default false)
+0028 %
+0029 %   solution        flux vector for the solution
+0030 %   metabolite      the index of the metabolite(s) which was consumed. If
+0031 %                   possible only one metabolite is reported, but there are
+0032 %                   situations where metabolites can only be consumed in
+0033 %                   pairs (or more)
+0034 %
+0035 %   NOTE: This works by forcing at least 1 unit of "any metabolites" to be
+0036 %   consumed and then minimize for the sum of fluxes. If more than one
+0037 %   metabolite is consumed, it picks one of them to be consumed and then
+0038 %   minimizes for the sum of fluxes.
+0039 %
+0040 % Usage: [solution, metabolite]=consumeSomething(model,ignoreMets,isNames,...
+0041 %               minNrFluxes,params,ignoreIntBounds)
+0042 
+0043 if nargin<2
+0044     ignoreMets=[];
+0045 elseif ~islogical(ignoreMets) && ~isnumeric(ignoreMets)
+0046     ignoreMets=convertCharArray(ignoreMets);
+0047 end
+0048 if nargin<3
+0049     isNames=false;
+0050 end
+0051 if nargin<4
+0052     minNrFluxes=false;
+0053 end
+0054 if nargin<5
+0055     params.relGap=0.8;
+0056 end
+0057 if nargin<6
+0058     ignoreIntBounds=false;
+0059 end
+0060 
+0061 if isNames==true && ~isempty(ignoreMets)
+0062     %Check that metsToRemove is a cell array
+0063     if iscellstr(ignoreMets)==false
+0064         EM='Must supply a cell array of strings if isNames=true';
+0065         dispEM(EM);
+0066     end
+0067 end
+0068 
+0069 if isNames==false
+0070     indexesToIgnore=getIndexes(model,ignoreMets,'mets');
+0071 else
+0072     indexesToIgnore=[];
+0073     for i=1:numel(ignoreMets)
+0074         indexesToIgnore=[indexesToIgnore;find(strcmp(ignoreMets(i),model.metNames))];
+0075     end
+0076 end
+0077 
+0078 %Change all internal reactions to be unbounded in both directions
+0079 if ignoreIntBounds==true
+0080     [~, I]=getExchangeRxns(model);
+0081     nonExc=true(numel(model.rxns),1);
+0082     nonExc(I)=false;
+0083     model=setParam(model,'lb',nonExc,-1000);
+0084     model=setParam(model,'ub',nonExc,1000);
+0085     model=setParam(model,'rev',nonExc,1);
+0086 end
+0087 
+0088 solution=[];
+0089 metabolite=[];
+0090 
+0091 nRxns=numel(model.rxns);
+0092 nMets=numel(model.mets);
+0093 
+0094 %Add uptake reactions for all metabolites
+0095 model.S=[model.S speye(nMets)];
+0096 
+0097 %Add so that they all consume a fake metabolite
+0098 model.S=[model.S;[sparse(1,nRxns) ones(1,nMets)*-1]];
+0099 
+0100 %Change so that the ignoreMets have a coefficient 0 in their reactions.
+0101 %Does not remove the actual reaction to make mapping easier later
+0102 model.S(:,indexesToIgnore+nRxns)=0;
+0103 
+0104 %Add an uptake reaction for this last fake metabolite
+0105 model.S(size(model.S,1),size(model.S,2)+1)=1;
+0106 model.b=[model.b;zeros(1,size(model.b,2))];
+0107 model.lb=[model.lb;zeros(nMets,1);1];
+0108 model.ub=[model.ub;inf(nMets+1,1)];
+0109 model.rev=[model.rev;zeros(nMets+1,1)];
+0110 model.c=zeros(size(model.S,2),1);
+0111 
+0112 %Add padding to the reaction annotation to prevent an error in solveLP
+0113 padding=1:numel(model.rev);
+0114 padding=num2cell(padding)';
+0115 padding=cellfun(@num2str,padding,'uniformoutput',false);
+0116 model.rxns=padding;
+0117 model.rxnNames=padding;
+0118 model.eccodes=padding;
+0119 model.rxnMiriams=padding;
+0120 model.grRules=padding;
+0121 if isfield(model,'genes')
+0122     model.rxnGeneMat=sparse(numel(model.rev),numel(model.genes));
+0123 end
+0124 model.subSystems=padding;
+0125 model.rxnFrom=padding;
+0126 model.rxnComps=ones(numel(model.rev),1);
+0127 model.rxnNotes=padding;
+0128 model.rxnReferences=padding;
+0129 model.rxnConfidenceScores=NaN(numel(model.rev),1);
+0130 
+0131 sol=solveLP(model,1);
+0132 if any(sol.x)
+0133     %It could be that several metabolites were consumed in order to get the
+0134     %best solution. The setdiff is to avoid including the last fake
+0135     %metabolite
+0136     I=setdiff(find(sol.x(nRxns+1:end)>0.1),size(model.S,1));
+0137     
+0138     if any(I) %This should always be true
+0139         %Change the coefficients so that only the first is consumed. This
+0140         %is not always possible, but it is tested for since it it results
+0141         %in more easily interpretable results
+0142         
+0143         oldS=model.S;
+0144         foundSingle=false;
+0145         %Test if any of the metabolites could be consumed on their own
+0146         for i=1:numel(I)
+0147             model.S=oldS;
+0148             J=nRxns+1:numel(model.lb)-1;
+0149             J(I(i))=[];
+0150             model.S(:,J)=0;
+0151             sol=solveLP(model);
+0152             if any(sol.x)
+0153                 foundSingle=true;
+0154                 break;
+0155             end
+0156         end
+0157         %This means that there was no metabolite which could be consumed on
+0158         %its own. Then let all the consumeable metabolites be consumed.
+0159         if foundSingle==false
+0160             model.S=oldS;
+0161         end
+0162         if minNrFluxes==true
+0163             %Has to add names for the rxns to prevent an error in
+0164             %minNrFluxes
+0165             model.rxns=cell(numel(model.lb),1);
+0166             model.rxns(:)={'TEMP'};
+0167             model.mets=cell(size(model.b,1),1);
+0168             model.mets(:)={'TEMP'};
+0169             sol=solveLP(model,3,params);
+0170         else
+0171             sol=solveLP(model,1);
+0172         end
+0173         solution=sol.x(1:nRxns);
+0174         metabolite=find(sol.x(nRxns+1:end-1)>0.1);
+0175     end
+0176 end
+0177 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/contractModel.html b/doc/core/contractModel.html new file mode 100644 index 000000000..260bdc3e0 --- /dev/null +++ b/doc/core/contractModel.html @@ -0,0 +1,251 @@ + + + + Description of contractModel + + + + + + + + + +
Home > core > contractModel.m
+ + + +

contractModel +

+ +

PURPOSE ^

+
contractModel
+ +

SYNOPSIS ^

+
function [reducedModel, removedRxns, indexedDuplicateRxns]=contractModel(model,distReverse,mets)
+ +

DESCRIPTION ^

+
 contractModel
+   Contracts a model by grouping all identical reactions. Similar to the
+   deleteDuplicates part in simplifyModel but more care is taken here
+   when it comes to gene associations. If the duplicated reactions have
+   '_EXP_*' suffixes (where * is a digit), then the model is assumed to
+   have been passed through expandModel, and these suffixes are removed
+   here.
+
+   model                  a model structure
+   distReverse            distinguish reactions with same metabolites
+                          but different reversibility as different
+                          reactions (optional, default true)
+   mets                   string or cell array of strings with metabolite
+                          identifiers, whose involved reactions should be
+                          checked for duplication (optional, by default all
+                          reactions are considered) (option is used by
+                          replaceMets)
+
+   reducedModel           a model structure without duplicate reactions
+   removedRxns            cell array for the removed duplicate reactions
+   indexedDuplicateRxns   indexed cell array for the removed duplicate
+                          reactions (multiple valuess separated by semicolon)
+
+   NOTE: This code might not work for advanced grRules strings
+         that involve nested expressions of 'and' and 'or'.
+
+ Usage: [reducedModel, removedRxns, indexedDuplicateRxns]=contractModel(model,distReverse,mets)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 function [reducedModel, removedRxns, indexedDuplicateRxns]=contractModel(model,distReverse,mets)
+0002 % contractModel
+0003 %   Contracts a model by grouping all identical reactions. Similar to the
+0004 %   deleteDuplicates part in simplifyModel but more care is taken here
+0005 %   when it comes to gene associations. If the duplicated reactions have
+0006 %   '_EXP_*' suffixes (where * is a digit), then the model is assumed to
+0007 %   have been passed through expandModel, and these suffixes are removed
+0008 %   here.
+0009 %
+0010 %   model                  a model structure
+0011 %   distReverse            distinguish reactions with same metabolites
+0012 %                          but different reversibility as different
+0013 %                          reactions (optional, default true)
+0014 %   mets                   string or cell array of strings with metabolite
+0015 %                          identifiers, whose involved reactions should be
+0016 %                          checked for duplication (optional, by default all
+0017 %                          reactions are considered) (option is used by
+0018 %                          replaceMets)
+0019 %
+0020 %   reducedModel           a model structure without duplicate reactions
+0021 %   removedRxns            cell array for the removed duplicate reactions
+0022 %   indexedDuplicateRxns   indexed cell array for the removed duplicate
+0023 %                          reactions (multiple valuess separated by semicolon)
+0024 %
+0025 %   NOTE: This code might not work for advanced grRules strings
+0026 %         that involve nested expressions of 'and' and 'or'.
+0027 %
+0028 % Usage: [reducedModel, removedRxns, indexedDuplicateRxns]=contractModel(model,distReverse,mets)
+0029 
+0030 if nargin<2
+0031     distReverse=true;
+0032 end
+0033 
+0034 %First sort the model so that reversible reactions are in the same
+0035 %direction
+0036 modelS=sortModel(model);
+0037 
+0038 %Get a list of duplicate reactions
+0039 if distReverse
+0040     x=[modelS.S; model.rev']';
+0041 else
+0042     x=modelS.S';
+0043 end
+0044 if nargin>2
+0045     toCheck = getIndexes(model,mets,'mets');
+0046     [~, toCheck] = find(modelS.S(toCheck,:));
+0047     x = [x, (1:size(x,1))']; % Make all other rxns unique by additional column
+0048     x(toCheck,end) = 0;
+0049 end
+0050 
+0051 [~,I,J] = unique(x,'rows','first');
+0052 
+0053 %Initialize cell array of indexedDuplicateRxns
+0054 indexedDuplicateRxns=cell(numel(model.rxns),1);
+0055 indexedDuplicateRxns(:)={''};
+0056 
+0057 duplicateRxns=setdiff(1:numel(model.rxns),I);
+0058 mergeTo=I(J(duplicateRxns));
+0059 
+0060 mergedRxns=unique(mergeTo);
+0061 
+0062 %Now add all the info from this one. Print a warning if they have different
+0063 %bounds or objective function coefficients. Uses the widest bounds and
+0064 %largest magnitude of objective coefficient
+0065 for i=1:numel(mergedRxns)
+0066     duplRxn=transpose([mergedRxns(i),duplicateRxns(mergeTo==mergedRxns(i))]);
+0067     if numel(unique(model.lb(duplRxn)))>1
+0068         EM=['Duplicates of reaction ' model.rxns{mergedRxns(i)} ' have different lower bound. Uses the most negative/smallest lower bound'];
+0069         dispEM(EM,false);
+0070         model.lb(mergedRxns(i))=min(model.lb(duplRxn));
+0071     end
+0072     if numel(unique(model.ub(duplRxn)))>1
+0073         EM=['Duplicates of reaction ' model.rxns{mergedRxns(i)} ' have different upper bound. Uses the most positive/largest upper bound'];
+0074         dispEM(EM,false);
+0075         model.ub(mergedRxns(i))=max(model.ub(duplRxn));
+0076     end
+0077     if numel(unique(model.c(duplRxn)))>1
+0078         EM=['Duplicates of reaction ' model.rxns{mergedRxns(i)} ' has a different objective function coefficient. Uses the largest coefficient'];
+0079         dispEM(EM,false);
+0080         model.c(mergedRxns(i))=max(model.c(duplRxn));
+0081     end
+0082     if isfield(model,'grRules') && any(~isempty(model.grRules(duplRxn)))
+0083         rules=model.grRules(duplRxn);
+0084         allRules={};
+0085         for j=1:numel(rules)
+0086             rules{j}=ignoreORinComplex(rules{j});
+0087             allRules=[allRules regexp(rules{j},' or ','split')];
+0088         end
+0089         allRules=unique(allRules);
+0090         allRules=strrep(allRules,'__OR__',' or ');
+0091         andRules=contains(allRules,' and ');
+0092         allRules(andRules)=strcat('(',allRules(andRules),')');
+0093         if numel(allRules)==1
+0094             model.grRules{mergedRxns(i)}=allRules{1};
+0095         else
+0096             model.grRules{mergedRxns(i)}=strjoin(allRules,' or ');
+0097         end
+0098     end    
+0099     if isfield(model,'eccodes') && any(~isempty(model.eccodes(duplRxn)))
+0100         codes=model.eccodes(duplRxn);
+0101         allCodes={};
+0102         for j=1:numel(codes)
+0103             allCodes=[allCodes regexp(codes{j},';','split')];
+0104         end
+0105         allCodes=unique(allCodes);
+0106         if numel(allCodes)==1
+0107             model.eccodes{mergedRxns(i)}=allCodes{1};
+0108         else
+0109             model.eccodes{mergedRxns(i)}=strjoin(allCodes,';');
+0110         end
+0111     end
+0112     %Generate indexedDuplicateRxns cell array
+0113     if numel(duplRxn)==2
+0114         indexedDuplicateRxns{duplRxn(1)}=model.rxns{duplRxn(2)};
+0115     else
+0116         indexedDuplicateRxns{duplRxn(1)}=strjoin(model.rxns(duplRxn(2:end)),';');
+0117     end
+0118     %If all reactions have _EXP_* (where * is digit) as suffix, then the
+0119     %model had passed through expandModel(), and these suffixes are removed.
+0120     if all(~cellfun(@isempty,regexp(model.rxns(duplRxn),'_EXP_\d+$')))
+0121         model.rxns(duplRxn(1))=regexprep(model.rxns(duplRxn(1)),'_EXP_\d+$','');
+0122     end
+0123 end
+0124 
+0125 %Delete the duplicate reactions
+0126 reducedModel=removeReactions(model,duplicateRxns);
+0127 removedRxns=model.rxns(duplicateRxns);
+0128 [~, index]=ismember(reducedModel.rxns,model.rxns);
+0129 indexedDuplicateRxns=indexedDuplicateRxns(index);
+0130 
+0131 if isfield(reducedModel,'rxnGeneMat')
+0132     %Fix grRules and reconstruct rxnGeneMat
+0133     [grRules,rxnGeneMat] = standardizeGrRules(reducedModel,true);
+0134     reducedModel.grRules = grRules;
+0135     reducedModel.rxnGeneMat = rxnGeneMat;
+0136 end
+0137 end
+0138 
+0139 function grRule = ignoreORinComplex(grRule)
+0140 %In a grRule, if OR relationship is nested in an AND relationship, then
+0141 %obfuscate the OR before splitting isoenzymes
+0142 grRule=['(' grRule ')'];
+0143 brOpen=strfind(grRule,'(');
+0144 brClose=strfind(grRule,')');
+0145 andPos=strfind(grRule,' and ');
+0146 %Find opening bracket closest before AND
+0147 stillCapturing = 0;
+0148 for i=1:numel(andPos)
+0149     searchPos = andPos(i);
+0150     while stillCapturing == 0
+0151         closestOpen = brOpen(max(find(brOpen<searchPos)));
+0152         inbetweenClose = brClose(brClose<searchPos & brClose>closestOpen);
+0153         if ~isempty(inbetweenClose)
+0154             searchPos=max(inbetweenClose);
+0155         else
+0156             stillCapturing = 1;
+0157             beginPos = closestOpen;
+0158         end
+0159     end
+0160     stillCapturing = 0;
+0161     searchPos = andPos(i);
+0162     while stillCapturing == 0
+0163         closestClose = brClose(min(find(brClose>searchPos)));
+0164         inbetweenOpen = brOpen(brOpen>searchPos & brOpen<closestOpen);
+0165         if ~isempty(inbetweenOpen)
+0166             searchPos=min(closestClose);
+0167         else
+0168             stillCapturing = 1;
+0169             endPos = closestClose;
+0170         end
+0171     end
+0172     replacePart=regexprep(grRule(beginPos:endPos),' or ','__OR__');
+0173     grRule=strrep(grRule,grRule(beginPos:endPos),replacePart);
+0174 end
+0175 grRule=grRule(2:end-1);
+0176 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/convertCharArray.html b/doc/core/convertCharArray.html new file mode 100644 index 000000000..f2f5bae0c --- /dev/null +++ b/doc/core/convertCharArray.html @@ -0,0 +1,84 @@ + + + + Description of convertCharArray + + + + + + + + + +
Home > core > convertCharArray.m
+ + + +

convertCharArray +

+ +

PURPOSE ^

+
convertCharArray
+ +

SYNOPSIS ^

+
function inputConverted = convertCharArray(funcInput)
+ +

DESCRIPTION ^

+
convertCharArray
+   Converts input to make sure it is a cell array of character vectors.
+   String arrays are transformed into character vectors, and if only one
+   character vector is given. Output is always a cell array, also if only
+   one character vector is given as input.
+
+   Input:
+   funcInput          function input that should be checked
+
+   Output:
+   inputConverted      cell array of character vectors
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function inputConverted = convertCharArray(funcInput)
+0002 %convertCharArray
+0003 %   Converts input to make sure it is a cell array of character vectors.
+0004 %   String arrays are transformed into character vectors, and if only one
+0005 %   character vector is given. Output is always a cell array, also if only
+0006 %   one character vector is given as input.
+0007 %
+0008 %   Input:
+0009 %   funcInput          function input that should be checked
+0010 %
+0011 %   Output:
+0012 %   inputConverted      cell array of character vectors
+0013 %
+0014 
+0015 if ~isempty(funcInput)
+0016     if ischar(funcInput) || isstring(funcInput)
+0017         inputConverted = {char(funcInput)};
+0018     elseif ~iscell(funcInput) && ~(all(cellfun(@ischar, funcInput)) || all(cellfun(@isstring, funcInput)))
+0019         error([inputname(1) ' should be a (cell array of) character vector(s)'])
+0020     else
+0021         inputConverted = cellstr(funcInput);
+0022     end
+0023 else
+0024     inputConverted=[];
+0025 end
+0026 end
+0027
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/convertToIrrev.html b/doc/core/convertToIrrev.html new file mode 100644 index 000000000..2e2817afa --- /dev/null +++ b/doc/core/convertToIrrev.html @@ -0,0 +1,182 @@ + + + + Description of convertToIrrev + + + + + + + + + +
Home > core > convertToIrrev.m
+ + + +

convertToIrrev +

+ +

PURPOSE ^

+
convertToIrrev
+ +

SYNOPSIS ^

+
function [irrevModel,matchRev,rev2irrev,irrev2rev]=convertToIrrev(model,rxns)
+ +

DESCRIPTION ^

+
 convertToIrrev
+   Converts a model to irreversible form
+
+ Input:
+   model         a model structure
+   rxns          cell array with the reactions so split (if reversible)
+                 (optional, default model.rxns)
+
+ Output:
+   irrevModel    a model structure where reversible reactions have
+                 been split into one forward and one reverse reaction
+   matchRev      matching forward reaction to its backward reaction
+   rev2irrev     forward and backward reactions for reversible reactions
+   irrev2rev     matching all reactions back to original model
+
+   The reverse reactions are saved as 'rxnID_REV'. A warning is shown if
+   some reaction identifiers already end with '_REV'.
+
+ Usage: [irrevModel,matchRev,rev2irrev,irrev2rev]=convertToIrrev(model,rxns)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function [irrevModel,matchRev,rev2irrev,irrev2rev]=convertToIrrev(model,rxns)
+0002 % convertToIrrev
+0003 %   Converts a model to irreversible form
+0004 %
+0005 % Input:
+0006 %   model         a model structure
+0007 %   rxns          cell array with the reactions so split (if reversible)
+0008 %                 (optional, default model.rxns)
+0009 %
+0010 % Output:
+0011 %   irrevModel    a model structure where reversible reactions have
+0012 %                 been split into one forward and one reverse reaction
+0013 %   matchRev      matching forward reaction to its backward reaction
+0014 %   rev2irrev     forward and backward reactions for reversible reactions
+0015 %   irrev2rev     matching all reactions back to original model
+0016 %
+0017 %   The reverse reactions are saved as 'rxnID_REV'. A warning is shown if
+0018 %   some reaction identifiers already end with '_REV'.
+0019 %
+0020 % Usage: [irrevModel,matchRev,rev2irrev,irrev2rev]=convertToIrrev(model,rxns)
+0021 
+0022 if nargin<2
+0023     I=true(numel(model.rxns),1);
+0024 else
+0025     rxns=convertCharArray(rxns);
+0026     I=getIndexes(model,rxns,'rxns',true);
+0027 end
+0028 
+0029 irrevModel=model;
+0030 
+0031 revIndexesBool=model.rev~=0 & I;
+0032 revIndexes=find(revIndexesBool);
+0033 numOrigRxns=numel(model.rxns);
+0034 numRevRxns=numel(revIndexes);
+0035 
+0036 if any(revIndexesBool)
+0037     irrevModel.S=[model.S,model.S(:,revIndexes)*-1];
+0038     irrevModel.rev(revIndexes)=0;
+0039     irrevModel.rev=[irrevModel.rev;zeros(numRevRxns,1)];
+0040     
+0041     %Get the limits for all normal and reversible rxns
+0042     ubNormal=irrevModel.ub;
+0043     ubNormal(revIndexes(ubNormal(revIndexes)<0))=0;
+0044     lbNormal=irrevModel.lb;
+0045     lbNormal(revIndexes(lbNormal(revIndexes)<0))=0;
+0046     ubRev=irrevModel.lb(revIndexes)*-1;
+0047     ubRev(ubRev<0)=0;
+0048     lbRev=irrevModel.ub(revIndexes)*-1;
+0049     lbRev(lbRev<0)=0;
+0050     irrevModel.ub=[ubNormal;ubRev];
+0051     irrevModel.lb=[lbNormal;lbRev];
+0052     
+0053     %The objective coefficents should be zero for the backwards reversible
+0054     %reactions unless they were negative in the original. In that case they
+0055     %should be positive for the backwards reversible and deleted from the
+0056     %original
+0057     irrevC=zeros(numRevRxns,1);
+0058     
+0059     if any(irrevModel.c(revIndexes)<0)
+0060         originalC=irrevModel.c(revIndexes);
+0061         irrevC(irrevModel.c(revIndexes)<0)=originalC(originalC<0)*-1;
+0062         irrevModel.c(irrevModel.c<0 & revIndexesBool)=0;
+0063     end
+0064     irrevModel.c=[irrevModel.c;irrevC];
+0065     
+0066     irrevModel.rxns=[irrevModel.rxns;strcat(irrevModel.rxns(revIndexes),'_REV')];
+0067     irrevModel.rxnNames=[irrevModel.rxnNames;strcat(irrevModel.rxnNames(revIndexes),' (reversible)')];
+0068     
+0069     if isfield(irrevModel,'grRules')
+0070         irrevModel.grRules=[irrevModel.grRules;irrevModel.grRules(revIndexes,:)];
+0071     end
+0072     if isfield(irrevModel,'rxnMiriams')
+0073         irrevModel.rxnMiriams=[irrevModel.rxnMiriams;irrevModel.rxnMiriams(revIndexes,:)];
+0074     end
+0075     if isfield(irrevModel,'rxnGeneMat')
+0076         irrevModel.rxnGeneMat=[irrevModel.rxnGeneMat;irrevModel.rxnGeneMat(revIndexes,:)];
+0077     end
+0078     if isfield(irrevModel,'subSystems')
+0079         irrevModel.subSystems=[irrevModel.subSystems;irrevModel.subSystems(revIndexes)];
+0080     end
+0081     if isfield(irrevModel,'eccodes')
+0082         irrevModel.eccodes=[irrevModel.eccodes;irrevModel.eccodes(revIndexes)];
+0083     end
+0084     if isfield(irrevModel,'rxnComps')
+0085         irrevModel.rxnComps=[irrevModel.rxnComps;irrevModel.rxnComps(revIndexes)];
+0086     end
+0087     if isfield(irrevModel,'rxnFrom')
+0088         irrevModel.rxnFrom=[irrevModel.rxnFrom;irrevModel.rxnFrom(revIndexes)];
+0089     end
+0090     if isfield(irrevModel,'rxnScores')
+0091         irrevModel.rxnScores=[irrevModel.rxnScores;irrevModel.rxnScores(revIndexes)];
+0092     end
+0093     if isfield(irrevModel,'rxnNotes')
+0094         irrevModel.rxnNotes=[irrevModel.rxnNotes;irrevModel.rxnNotes(revIndexes)];
+0095     end
+0096     if isfield(irrevModel,'rxnConfidenceScores')
+0097         irrevModel.rxnConfidenceScores=[irrevModel.rxnConfidenceScores;irrevModel.rxnConfidenceScores(revIndexes)];
+0098     end
+0099     if isfield(irrevModel,'rxnDeltaG')
+0100         irrevModel.rxnDeltaG=[irrevModel.rxnDeltaG;-irrevModel.rxnDeltaG(revIndexes)]; % Invert dG for reversed rxns
+0101     end
+0102     if isfield(irrevModel,'rxnReferences')
+0103         irrevModel.rxnReferences=[irrevModel.rxnReferences;irrevModel.rxnReferences(revIndexes)];
+0104     end
+0105 end
+0106     % Additional output
+0107     if nargout>1
+0108         irrev2rev = [transpose(1:numOrigRxns);revIndexes];
+0109         rev2irrev = num2cell(transpose(1:numOrigRxns));
+0110         newIdxs   = [revIndexes transpose(1:numRevRxns)];
+0111         for i=1:numRevRxns
+0112             rev2irrev{revIndexes(i)} = newIdxs(i,:);
+0113         end
+0114         matchRev  = zeros(numel(irrev2rev),1);
+0115         matchRev(revIndexes) = (1:numRevRxns)+numOrigRxns;
+0116     end
+0117 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/copyToComps.html b/doc/core/copyToComps.html new file mode 100644 index 000000000..33b17a6e0 --- /dev/null +++ b/doc/core/copyToComps.html @@ -0,0 +1,175 @@ + + + + Description of copyToComps + + + + + + + + + +
Home > core > copyToComps.m
+ + + +

copyToComps +

+ +

PURPOSE ^

+
copyToComps
+ +

SYNOPSIS ^

+
function model=copyToComps(model,toComps,rxns,deleteOriginal,compNames,compOutside)
+ +

DESCRIPTION ^

+
 copyToComps
+   Copies reactions to new compartment(s)
+
+   model           a model structure
+   toComps         cell array of compartment ids. If there is no match
+                   to model.comps then it is added as a new compartment
+                   (see below for details)
+   rxns            either a cell array of reaction IDs, a logical vector 
+                   with the same number of elements as reactions in the model,
+                   or a vector of indexes to remove (optional, default
+                   model.rxns)
+   deleteOriginal  true if the original reactions should be removed
+                   (making it move the reactions instead) (optional, default
+                   false)
+   compNames       cell array of compartment names. This is used if new
+                   compartments should be added (optional, default toComps)
+   compOutside     cell array of the id (as in comps) for the compartment
+                   surrounding each of the compartments. This is used if
+                   new compartments should be added (optional, default all {''})
+
+   model           an updated model structure
+
+   NOTE: New reactions and metabolites will be named as "id_toComps(i)".
+
+ Usage: model=copyToComps(model,toComps,rxns,deleteOriginal,compNames,compOutside)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function model=copyToComps(model,toComps,rxns,deleteOriginal,compNames,compOutside)
+0002 % copyToComps
+0003 %   Copies reactions to new compartment(s)
+0004 %
+0005 %   model           a model structure
+0006 %   toComps         cell array of compartment ids. If there is no match
+0007 %                   to model.comps then it is added as a new compartment
+0008 %                   (see below for details)
+0009 %   rxns            either a cell array of reaction IDs, a logical vector
+0010 %                   with the same number of elements as reactions in the model,
+0011 %                   or a vector of indexes to remove (optional, default
+0012 %                   model.rxns)
+0013 %   deleteOriginal  true if the original reactions should be removed
+0014 %                   (making it move the reactions instead) (optional, default
+0015 %                   false)
+0016 %   compNames       cell array of compartment names. This is used if new
+0017 %                   compartments should be added (optional, default toComps)
+0018 %   compOutside     cell array of the id (as in comps) for the compartment
+0019 %                   surrounding each of the compartments. This is used if
+0020 %                   new compartments should be added (optional, default all {''})
+0021 %
+0022 %   model           an updated model structure
+0023 %
+0024 %   NOTE: New reactions and metabolites will be named as "id_toComps(i)".
+0025 %
+0026 % Usage: model=copyToComps(model,toComps,rxns,deleteOriginal,compNames,compOutside)
+0027 
+0028 arguments
+0029     model (1,1) struct
+0030     toComps {emptyOrTextOrCellOfText}
+0031     rxns = model.rxns
+0032     deleteOriginal {emptyOrLogicalScalar} = false
+0033     compNames {emptyOrTextOrCellOfText} = toComps
+0034     compOutside {emptyOrTextOrCellOfText} = '';
+0035 end
+0036 
+0037 if nargin >= 3 && ~islogical(rxns) && ~isnumeric(rxns)
+0038     rxns = convertCharArray(rxns);
+0039 end
+0040 if nargin >= 5
+0041     compNames=convertCharArray(compNames);
+0042 end
+0043 if nargin >= 6
+0044     compOutside=convertCharArray(compOutside);
+0045     if length(compOutside) ~= length(compNames)
+0046         error('compOutside and compNames should be of equal size.');
+0047     end
+0048 end
+0049 
+0050 originalID=model.id;
+0051 originalName=model.name;
+0052 
+0053 rxns=getIndexes(model,rxns,'rxns');
+0054 
+0055 for i=1:numel(toComps)
+0056     %Check if the compartment exists, otherwise add it
+0057     [I,J]=ismember(toComps(i),model.comps);
+0058     if I==false
+0059         model.comps=[model.comps;toComps(i)];
+0060         model.compNames=[model.compNames;compNames(i)];
+0061         if isfield(model,'compOutside')
+0062             model.compOutside=[model.compOutside;compOutside(i)];
+0063         end
+0064         if isfield(model,'compMiriams')
+0065             model.compMiriams=[model.compMiriams;cell(1,1)];
+0066         end
+0067         J=numel(model.comps);
+0068     end
+0069     %Copy the reactions by making a model structure with only them, then
+0070     %change the localization, and finally merge with the original model
+0071     modelToAdd=model;
+0072     modelToAdd=removeReactions(modelToAdd,setdiff(1:numel(model.rxns),rxns),true,true);
+0073     modelToAdd.rxns=strcat(modelToAdd.rxns,'_',toComps(i));
+0074     modelToAdd.mets=strcat(modelToAdd.mets,'_',toComps(i));
+0075     modelToAdd.comps=modelToAdd.comps(J);
+0076     modelToAdd.compNames=modelToAdd.compNames(J);
+0077     if isfield(modelToAdd,'compOutside')
+0078         modelToAdd.compOutside=modelToAdd.compOutside(J);
+0079     end
+0080     if isfield(modelToAdd,'compMiriams')
+0081         modelToAdd.compMiriams=modelToAdd.compMiriams(J);
+0082     end
+0083     modelToAdd.metComps=ones(numel(modelToAdd.mets),1);
+0084     if isfield(modelToAdd,'metFrom')
+0085         modelToAdd = rmfield(modelToAdd,'metFrom');
+0086     end
+0087     if isfield(modelToAdd,'rxnFrom')
+0088         modelToAdd = rmfield(modelToAdd,'rxnFrom');
+0089     end
+0090     if isfield(modelToAdd,'geneFrom')
+0091         modelToAdd = rmfield(modelToAdd,'geneFrom');
+0092     end
+0093   
+0094     %Merge the models
+0095     model=mergeModels({model;modelToAdd},'metNames',[],true);
+0096 end
+0097 
+0098 if deleteOriginal==true
+0099     model=removeReactions(model,rxns,true,true,true); %Also delete unused compartments
+0100 end
+0101 
+0102 model.id=originalID;
+0103 model.name=originalName;
+0104 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/deleteUnusedGenes.html b/doc/core/deleteUnusedGenes.html new file mode 100644 index 000000000..6a9bd7b12 --- /dev/null +++ b/doc/core/deleteUnusedGenes.html @@ -0,0 +1,111 @@ + + + + Description of deleteUnusedGenes + + + + + + + + + +
Home > core > deleteUnusedGenes.m
+ + + +

deleteUnusedGenes +

+ +

PURPOSE ^

+
deleteUnusedGenes
+ +

SYNOPSIS ^

+
function reducedModel=deleteUnusedGenes(model,verbose)
+ +

DESCRIPTION ^

+
 deleteUnusedGenes
+   Deletes all genes that are not associated to any reaction
+
+   model           a model structure
+   verbose         0 for silent; 1 for printing number of deleted genes;
+                   2 for printing the list of deleted genes (optional, default 1)
+
+   reducedModel    an updated model structure
+
+ Usage: reducedModel=deleteUnusedGenes(model)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function reducedModel=deleteUnusedGenes(model,verbose)
+0002 % deleteUnusedGenes
+0003 %   Deletes all genes that are not associated to any reaction
+0004 %
+0005 %   model           a model structure
+0006 %   verbose         0 for silent; 1 for printing number of deleted genes;
+0007 %                   2 for printing the list of deleted genes (optional, default 1)
+0008 %
+0009 %   reducedModel    an updated model structure
+0010 %
+0011 % Usage: reducedModel=deleteUnusedGenes(model)
+0012 
+0013 if nargin<2
+0014     verbose=1;
+0015 end
+0016 reducedModel=model;
+0017 
+0018 %Find all genes that are not used
+0019 [~, b]=find(reducedModel.rxnGeneMat);
+0020 toKeep=false(numel(reducedModel.genes),1);
+0021 toKeep(b)=true;
+0022 
+0023 switch verbose
+0024     case 1
+0025         disp('Number of unused genes removed from the model:')
+0026         disp(numel(toKeep(~toKeep)))
+0027     case 2
+0028         disp('The following genes were removed from the model:')
+0029         disp(reducedModel.genes(~toKeep))
+0030     case 0
+0031 end
+0032         
+0033 reducedModel.genes=reducedModel.genes(toKeep);
+0034 reducedModel.rxnGeneMat=reducedModel.rxnGeneMat(:,toKeep);
+0035 
+0036 if isfield(reducedModel,'geneShortNames')
+0037     reducedModel.geneShortNames=reducedModel.geneShortNames(toKeep);
+0038 end
+0039 
+0040 if isfield(reducedModel,'proteins')
+0041     reducedModel.proteins=reducedModel.proteins(toKeep);
+0042 end
+0043 
+0044 if isfield(reducedModel,'geneMiriams')
+0045     reducedModel.geneMiriams=reducedModel.geneMiriams(toKeep);
+0046 end
+0047 
+0048 if isfield(reducedModel,'geneFrom')
+0049     reducedModel.geneFrom=reducedModel.geneFrom(toKeep);
+0050 end
+0051 
+0052 if isfield(reducedModel,'geneComps')
+0053     reducedModel.geneComps=reducedModel.geneComps(toKeep);
+0054 end
+0055 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/dispEM.html b/doc/core/dispEM.html new file mode 100644 index 000000000..745229f22 --- /dev/null +++ b/doc/core/dispEM.html @@ -0,0 +1,115 @@ + + + + Description of dispEM + + + + + + + + + +
Home > core > dispEM.m
+ + + +

dispEM +

+ +

PURPOSE ^

+
dispEM
+ +

SYNOPSIS ^

+
function dispEM(string,throwErrors,toList,trimWarnings)
+ +

DESCRIPTION ^

+
 dispEM
+   Helper function to print warning/errors
+
+   string          the warning/error to show. "WARNING: " is appended automatically
+                   if a warning
+   throwErrors     true if the function should throw an error (optional, default true)
+   toList          a cell array of items to list. If supplied, then the
+                   string will be printed followed by each element in
+                   toList. If it is supplied but empty then nothing is
+                   printed (optional, default {})
+   trimWarnings    true if only a maximal of 10 items should be displayed in
+                   a given error/warning (optional, default true)
+
+ Usage: dispEM(string,throwErrors,toList,trimWarnings)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function dispEM(string,throwErrors,toList,trimWarnings)
+0002 % dispEM
+0003 %   Helper function to print warning/errors
+0004 %
+0005 %   string          the warning/error to show. "WARNING: " is appended automatically
+0006 %                   if a warning
+0007 %   throwErrors     true if the function should throw an error (optional, default true)
+0008 %   toList          a cell array of items to list. If supplied, then the
+0009 %                   string will be printed followed by each element in
+0010 %                   toList. If it is supplied but empty then nothing is
+0011 %                   printed (optional, default {})
+0012 %   trimWarnings    true if only a maximal of 10 items should be displayed in
+0013 %                   a given error/warning (optional, default true)
+0014 %
+0015 % Usage: dispEM(string,throwErrors,toList,trimWarnings)
+0016 
+0017 if nargin<2
+0018     throwErrors=true;
+0019 end
+0020 if nargin<3
+0021     toList=[];
+0022 elseif isempty(toList)
+0023     return;
+0024 else
+0025     toList=convertCharArray(toList);
+0026 end
+0027 if nargin<4
+0028     trimWarnings=true;
+0029 end
+0030 if numel(toList)>10 && trimWarnings==true
+0031     toList{10}=['...and ' num2str(numel(toList)-9) ' more'];
+0032     toList(11:end)=[];
+0033 end
+0034 if throwErrors==false
+0035     errorText=['WARNING: ' string '\n'];
+0036     % Wrap text to command window size
+0037     sz = get(0, 'CommandWindowSize');
+0038     errorText = textwrap({errorText},sz(1));
+0039     errorText = strjoin(errorText,'\n');
+0040 else
+0041     errorText=[string '\n'];
+0042 end
+0043 if ~isempty(toList)
+0044     for i=1:numel(toList)
+0045         errorText=[errorText '\t' toList{i} '\n'];
+0046     end
+0047 end
+0048 if throwErrors==false
+0049     %Escape special characters, required for fprintf
+0050     errorText=regexprep(errorText,'(\\|\%|'')(\\n)$','\\$0');
+0051     fprintf([errorText '\n']);
+0052 else
+0053     throw(MException('',errorText));
+0054 end
+0055 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/expandModel.html b/doc/core/expandModel.html new file mode 100644 index 000000000..6f4e866d8 --- /dev/null +++ b/doc/core/expandModel.html @@ -0,0 +1,212 @@ + + + + Description of expandModel + + + + + + + + + +
Home > core > expandModel.m
+ + + +

expandModel +

+ +

PURPOSE ^

+
expandModel
+ +

SYNOPSIS ^

+
function [newModel, rxnToCheck]=expandModel(model)
+ +

DESCRIPTION ^

+
 expandModel
+   Expands a model which uses several gene associations for one reaction.
+   Each such reaction is split into several reactions, each under the control
+   of only one gene.
+  
+ Input:
+   model       model structure
+ 
+ Output:
+   newModel    model structure with separate reactions for iso-enzymes, where
+               the reaction ids are renamed as to id_EXP_1, id_EXP_2, etc. 
+   rxnToCheck  cell array with original reaction identifiers for those
+               that contained nested and/or-relationships in grRules.
+
+   NOTE: grRules strings that involve nested expressions of 'and' and 'or'
+         might not be parsed correctly if they are not standardized (if the
+         standardizeGrRules functions was not first run on the model). For
+         those reactions, it is therefore advisable to inspect the reactions in
+         rxnToCheck to confirm correct model expansion.
+
+ Usage: [newModel, rxnToCheck]=expandModel(model)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function [newModel, rxnToCheck]=expandModel(model)
+0002 % expandModel
+0003 %   Expands a model which uses several gene associations for one reaction.
+0004 %   Each such reaction is split into several reactions, each under the control
+0005 %   of only one gene.
+0006 %
+0007 % Input:
+0008 %   model       model structure
+0009 %
+0010 % Output:
+0011 %   newModel    model structure with separate reactions for iso-enzymes, where
+0012 %               the reaction ids are renamed as to id_EXP_1, id_EXP_2, etc.
+0013 %   rxnToCheck  cell array with original reaction identifiers for those
+0014 %               that contained nested and/or-relationships in grRules.
+0015 %
+0016 %   NOTE: grRules strings that involve nested expressions of 'and' and 'or'
+0017 %         might not be parsed correctly if they are not standardized (if the
+0018 %         standardizeGrRules functions was not first run on the model). For
+0019 %         those reactions, it is therefore advisable to inspect the reactions in
+0020 %         rxnToCheck to confirm correct model expansion.
+0021 %
+0022 % Usage: [newModel, rxnToCheck]=expandModel(model)
+0023 
+0024 %Check how many reactions we will create (the number of or:s in the GPRs).
+0025 %This way, we can preallocate all fields and save much computation time
+0026 
+0027 numOrs = count(model.grRules, ' or ');
+0028 toAdd = sum(numOrs);
+0029 prevNumRxns = length(model.rxns);
+0030 rxnToCheck={};
+0031 if toAdd > 0
+0032     %Calculate indices to expand
+0033     %For example, if a reaction with index x has 2 or:s, meaning it has 3
+0034     %reactions after the split, we should add two copies of this reaction
+0035     %For fields that should just be copied to the new reactions, we just keep
+0036     %track of that there are two copies, i.e., we add x x to this vector.
+0037     %That is exactly what repelem does for us.
+0038     cpyIndices = repelem(1:prevNumRxns, numOrs);
+0039     
+0040     %Copy all fields that should just be copied
+0041     model.S=[model.S model.S(:,cpyIndices)];
+0042     model.rxnNames=[model.rxnNames;model.rxnNames(cpyIndices)];
+0043     model.lb=[model.lb;model.lb(cpyIndices)];
+0044     model.ub=[model.ub;model.ub(cpyIndices)];
+0045     model.rev=[model.rev;model.rev(cpyIndices)];
+0046     model.c=[model.c;model.c(cpyIndices)];
+0047     if isfield(model,'subSystems')
+0048         model.subSystems=[model.subSystems;model.subSystems(cpyIndices)];
+0049     end
+0050     if isfield(model,'eccodes')
+0051         model.eccodes=[model.eccodes;model.eccodes(cpyIndices)];
+0052     end
+0053     if isfield(model,'equations')
+0054         model.equations=[model.equations;model.equations(cpyIndices)];
+0055     end
+0056     if isfield(model,'rxnMiriams')
+0057         model.rxnMiriams=[model.rxnMiriams;model.rxnMiriams(cpyIndices)];
+0058     end
+0059     if isfield(model,'rxnComps')
+0060         model.rxnComps=[model.rxnComps;model.rxnComps(cpyIndices)];
+0061     end
+0062     if isfield(model,'rxnFrom')
+0063         model.rxnFrom=[model.rxnFrom;model.rxnFrom(cpyIndices)];
+0064     end
+0065     if isfield(model,'rxnNotes')
+0066         model.rxnNotes=[model.rxnNotes;model.rxnNotes(cpyIndices)];
+0067     end
+0068     if isfield(model,'rxnReferences')
+0069         model.rxnReferences=[model.rxnReferences;model.rxnReferences(cpyIndices)];
+0070     end
+0071     if isfield(model,'rxnConfidenceScores')
+0072         model.rxnConfidenceScores=[model.rxnConfidenceScores;model.rxnConfidenceScores(cpyIndices)];
+0073     end
+0074     if isfield(model,'rxnDeltaG')
+0075         model.rxnDeltaG=[model.rxnDeltaG;model.rxnDeltaG(cpyIndices)];
+0076     end
+0077     
+0078     %now expand the more complex fields - will be filled in later
+0079     model.rxns=[model.rxns;cell(toAdd,1)];
+0080     model.grRules=[model.grRules;cell(toAdd,1)];
+0081     model.rxnGeneMat=[model.rxnGeneMat;sparse(toAdd,size(model.rxnGeneMat,2))];
+0082     
+0083     %Loop throught those reactions and fill in the expanded data
+0084     nextIndex = prevNumRxns + 1;
+0085     for i=1:prevNumRxns
+0086         if (numOrs(i) > 0)
+0087             %Check that it doesn't contain nested 'and' and 'or' relations and
+0088             %print a warning if it does
+0089             if ~isempty(strfind(model.grRules{i},' and '))
+0090                 rxnToCheck{end+1,1}=model.rxns{i};
+0091             end
+0092 
+0093             %Get rid of all '(' and ')' since I'm not looking at complex stuff
+0094             %anyways
+0095             geneString=model.grRules{i};
+0096             geneString=strrep(geneString,'(','');
+0097             geneString=strrep(geneString,')','');
+0098             geneString=strrep(geneString,' or ',';');
+0099 
+0100             %Split the string into gene names
+0101             geneNames=regexp(geneString,';','split');
+0102 
+0103             %Update the reaction to only use the first gene
+0104             model.grRules{i}=['(' geneNames{1} ')'];
+0105             %Find the gene in the gene list If ' and ' relationship, first
+0106             %split the genes
+0107             model.rxnGeneMat(i,:)=0;
+0108             if ~isempty(strfind(geneNames(1),' and '))
+0109                 andGenes=regexp(geneNames{1},' and ','split');
+0110                 model.rxnGeneMat(i,ismember(model.genes,andGenes)) = 1;
+0111             else
+0112                 [~, index]=ismember(geneNames(1),model.genes);
+0113                 model.rxnGeneMat(i,index)=1;
+0114             end
+0115 
+0116             %Insert the reactions at the end of the model and without
+0117             %allocating space. This is not nice, but ok for now
+0118             for j=2:numel(geneNames)
+0119                 ind = nextIndex+j-2;
+0120                 model.rxns{ind}=[model.rxns{i} '_EXP_' num2str(j)];
+0121                 
+0122                 model.grRules{ind}=['(' geneNames{j} ')'];
+0123 
+0124                 if ~isempty(strfind(geneNames(j),' and '))
+0125                     andGenes=regexp(geneNames{j},' and ','split');
+0126                     model.rxnGeneMat(ind,ismember(model.genes,andGenes)) = 1;
+0127                 else
+0128                     model.rxnGeneMat(ind,ismember(model.genes,geneNames(j))) = 1;
+0129                 end
+0130             end
+0131             model.rxns{i}=[model.rxns{i}, '_EXP_1'];
+0132             nextIndex = nextIndex + numOrs(i);
+0133         end        
+0134     end
+0135     newModel=model;
+0136 else
+0137     %There are no reactions to expand, return the model as is
+0138     newModel=model;
+0139 end
+0140 
+0141 %Fix grRules and reconstruct rxnGeneMat
+0142 [grRules,rxnGeneMat] = standardizeGrRules(newModel,true);
+0143 newModel.grRules = grRules;
+0144 newModel.rxnGeneMat = rxnGeneMat;
+0145 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/fillGaps.html b/doc/core/fillGaps.html new file mode 100644 index 000000000..ba68613ac --- /dev/null +++ b/doc/core/fillGaps.html @@ -0,0 +1,325 @@ + + + + Description of fillGaps + + + + + + + + + +
Home > core > fillGaps.m
+ + + +

fillGaps +

+ +

PURPOSE ^

+
fillGaps
+ +

SYNOPSIS ^

+
function [newConnected, cannotConnect, addedRxns, newModel, exitFlag]=fillGaps(model,models,allowNetProduction,useModelConstraints,supressWarnings,rxnScores)
+ +

DESCRIPTION ^

+
 fillGaps
+   Uses template model(s) to fill gaps in a model
+
+   model               a model structure that may contains gaps to be filled
+   models              a cell array of reference models or a model structure.
+                       The gaps will be filled using reactions from these models
+   allowNetProduction  true if net production of all metabolites is
+                       allowed. A reaction can be unable to carry flux because one of
+                       the reactants is unavailable or because one of the
+                       products can't be further processed. If this
+                       parameter is true, only the first type of
+                       unconnectivity is considered (optional, default false)
+   useModelConstraints true if the constraints specified in the model
+                       structure should be used. If false then reactions
+                       included from the template model(s) so that as many
+                       reactions as possible in model can carry flux
+                       (optional, default false)
+   supressWarnings     false if warnings should be displayed (optional, default
+                       false)
+   rxnScores           array with scores for each of the reactions in the
+                       reference model(s). If more than one model is supplied,
+                       then rxnScores should be a cell array of vectors.
+                       The solver will try to maximize the sum of the
+                       scores for the included reactions (optional, default
+                       is -1 for all reactions)
+
+   newConnected        cell array with the reactions that could be
+                       connected. This is not calulated if
+                       useModelConstraints is true
+   cannotConnect       cell array with reactions that could not be
+                       connected. This is not calculated if
+                       useModelConstraints is true
+   addedRxns           cell array with the reactions that were added from
+                       "models"
+   newModel            the model with reactions added to fill gaps
+   exitFlag            1: optimal solution found
+                      -1: no feasible solution found
+                      -2: optimization time out
+
+   This method works by merging the model to the reference model(s) and
+   checking which reactions can carry flux. All reactions that can't
+   carry flux are removed (cannotConnect).
+   If useModelConstraints is false it then solves the MILP problem of
+   minimizing the number of active reactions from the reference models
+   that are required to have flux in all the reactions in model. This
+   requires that the input model has exchange reactions present for the
+   nutrients that are needed for its metabolism. If useModelConstraints is
+   true then the problem is to include as few reactions as possible from
+   the reference models in order to satisfy the model constraints.
+   The intended use is that the user can attempt a general gap-filling using
+   useModelConstraint=false or a more targeted gap-filling by setting
+   constraints in the model structure and then use
+   useModelConstraints=true. Say that the user want to include reactions
+   so that all biomass components can be synthesized. He/she could then
+   define a biomass equation and set the lower bound to >0. Running this
+   function with useModelConstraints=true would then give the smallest set
+   of reactions that have to be included in order for the model to produce
+   biomass.
+
+ Usage: [newConnected, cannotConnect, addedRxns, newModel, exitFlag]=...
+           fillGaps(model,models,allowNetProduction,useModelConstraints,...
+           supressWarnings,rxnScores,params)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function [newConnected, cannotConnect, addedRxns, newModel, exitFlag]=fillGaps(model,models,allowNetProduction,useModelConstraints,supressWarnings,rxnScores)
+0002 % fillGaps
+0003 %   Uses template model(s) to fill gaps in a model
+0004 %
+0005 %   model               a model structure that may contains gaps to be filled
+0006 %   models              a cell array of reference models or a model structure.
+0007 %                       The gaps will be filled using reactions from these models
+0008 %   allowNetProduction  true if net production of all metabolites is
+0009 %                       allowed. A reaction can be unable to carry flux because one of
+0010 %                       the reactants is unavailable or because one of the
+0011 %                       products can't be further processed. If this
+0012 %                       parameter is true, only the first type of
+0013 %                       unconnectivity is considered (optional, default false)
+0014 %   useModelConstraints true if the constraints specified in the model
+0015 %                       structure should be used. If false then reactions
+0016 %                       included from the template model(s) so that as many
+0017 %                       reactions as possible in model can carry flux
+0018 %                       (optional, default false)
+0019 %   supressWarnings     false if warnings should be displayed (optional, default
+0020 %                       false)
+0021 %   rxnScores           array with scores for each of the reactions in the
+0022 %                       reference model(s). If more than one model is supplied,
+0023 %                       then rxnScores should be a cell array of vectors.
+0024 %                       The solver will try to maximize the sum of the
+0025 %                       scores for the included reactions (optional, default
+0026 %                       is -1 for all reactions)
+0027 %
+0028 %   newConnected        cell array with the reactions that could be
+0029 %                       connected. This is not calulated if
+0030 %                       useModelConstraints is true
+0031 %   cannotConnect       cell array with reactions that could not be
+0032 %                       connected. This is not calculated if
+0033 %                       useModelConstraints is true
+0034 %   addedRxns           cell array with the reactions that were added from
+0035 %                       "models"
+0036 %   newModel            the model with reactions added to fill gaps
+0037 %   exitFlag            1: optimal solution found
+0038 %                      -1: no feasible solution found
+0039 %                      -2: optimization time out
+0040 %
+0041 %   This method works by merging the model to the reference model(s) and
+0042 %   checking which reactions can carry flux. All reactions that can't
+0043 %   carry flux are removed (cannotConnect).
+0044 %   If useModelConstraints is false it then solves the MILP problem of
+0045 %   minimizing the number of active reactions from the reference models
+0046 %   that are required to have flux in all the reactions in model. This
+0047 %   requires that the input model has exchange reactions present for the
+0048 %   nutrients that are needed for its metabolism. If useModelConstraints is
+0049 %   true then the problem is to include as few reactions as possible from
+0050 %   the reference models in order to satisfy the model constraints.
+0051 %   The intended use is that the user can attempt a general gap-filling using
+0052 %   useModelConstraint=false or a more targeted gap-filling by setting
+0053 %   constraints in the model structure and then use
+0054 %   useModelConstraints=true. Say that the user want to include reactions
+0055 %   so that all biomass components can be synthesized. He/she could then
+0056 %   define a biomass equation and set the lower bound to >0. Running this
+0057 %   function with useModelConstraints=true would then give the smallest set
+0058 %   of reactions that have to be included in order for the model to produce
+0059 %   biomass.
+0060 %
+0061 % Usage: [newConnected, cannotConnect, addedRxns, newModel, exitFlag]=...
+0062 %           fillGaps(model,models,allowNetProduction,useModelConstraints,...
+0063 %           supressWarnings,rxnScores,params)
+0064 
+0065 %If the user only supplied a single template model
+0066 if ~iscell(models)
+0067     models={models};
+0068 end
+0069 
+0070 if nargin<3
+0071     allowNetProduction=false;
+0072 end
+0073 if nargin<4
+0074     useModelConstraints=false;
+0075 end
+0076 if nargin<5
+0077     supressWarnings=false;
+0078 end
+0079 if nargin<6
+0080     rxnScores=cell(numel(models),1);
+0081     for i=1:numel(models)
+0082         rxnScores{i}=ones(numel(models{i}.rxns),1)*-1;
+0083     end
+0084 end
+0085 if isempty(rxnScores)
+0086     rxnScores=cell(numel(models),1);
+0087     for i=1:numel(models)
+0088         rxnScores{i}=ones(numel(models{i}.rxns),1)*-1;
+0089     end
+0090 end
+0091 if nargin<7
+0092     params=struct();
+0093 end
+0094 
+0095 if ~iscell(rxnScores)
+0096     rxnScores={rxnScores};
+0097 end
+0098 
+0099 models=models(:);
+0100 rxnScores=rxnScores(:);
+0101 
+0102 %Check if the original model has an unconstrained field. If so, give a
+0103 %warning
+0104 if supressWarnings==false
+0105     if isfield(model,'unconstrained')
+0106         EM='This algorithm is meant to function on a model with exchange reactions for uptake and excretion of metabolites. The current model still has the "unconstrained" field';
+0107         dispEM(EM,false);
+0108     else
+0109         if isempty(getExchangeRxns(model,'both'))
+0110             fprintf('NOTE: This algorithm is meant to function on a model with exchange reactions for uptake and excretion of metabolites. The current model does not seem to contain any such reactions.\n');
+0111         end
+0112     end
+0113 end
+0114 
+0115 %Simplify the template models to remove constrained rxns. At the same time,
+0116 %check that the id of the template models isn't the same as the model. That
+0117 %would cause an error further down
+0118 for i=1:numel(models)
+0119     models{i}.rxnScores=rxnScores{i};
+0120     models{i}=simplifyModel(models{i},false,false,true);
+0121     if strcmpi(models{i}.id,model.id)
+0122         EM='The reference model(s) cannot have the same id as the model';
+0123         dispEM(EM);
+0124     end
+0125 end
+0126 
+0127 %This is a rather ugly solution to the issue that it's a bit tricky to keep
+0128 %track of which scores belong to which reactions. This requires that
+0129 %removeReactions and mergeModels are modified to check for the new field.
+0130 model.rxnScores=zeros(numel(model.rxns),1);
+0131 
+0132 %First merge all models into one big one
+0133 allModels=mergeModels([{model};models],'metNames',true);
+0134 
+0135 %Add that net production is ok
+0136 if allowNetProduction==true
+0137     %A second column in model.b means that the b field is lower and upper
+0138     %bound on the RHS.
+0139     model.b=[model.b(:,1) inf(numel(model.mets),1)];
+0140     allModels.b=[allModels.b(:,1) inf(numel(allModels.mets),1)];
+0141 end
+0142 
+0143 if useModelConstraints==true
+0144     newConnected={};
+0145     cannotConnect={};
+0146     
+0147     %Check that the input model isn't solveable without any input
+0148     sol=solveLP(model);
+0149     if ~isempty(sol.f)
+0150         addedRxns={};
+0151         newModel=model;
+0152         exitFlag=1;
+0153         return;
+0154     end
+0155     
+0156     %Then check that the merged model is solveable
+0157     sol=solveLP(allModels);
+0158     if isempty(sol.f)
+0159         EM='There are no reactions in the template model(s) that can make the model constraints satisfied';
+0160         dispEM(EM);
+0161     end
+0162     
+0163     %Remove dead ends for speed reasons. This has to be done here and
+0164     %duplicate below because there is otherwise a risk that a reaction
+0165     %which is constrained to something relevant is removed
+0166     allModels=simplifyModel(allModels,false,false,false,true,false,false,false,[],true);
+0167     allModels.c(:)=0;
+0168 else
+0169     %Remove dead ends for speed reasons
+0170     allModels=simplifyModel(allModels,false,false,false,true,false,false,false,[],true);
+0171     allModels.c(:)=0;
+0172     
+0173     %If model constraints shouldn't be used, then determine which reactions
+0174     %to force to have flux
+0175     
+0176     %Get the reactions that can carry flux in the original model
+0177     originalFlux=haveFlux(model,1);
+0178     
+0179     %For the ones that can't carry flux, see if they can do so in the
+0180     %merged model
+0181     toCheck=intersect(allModels.rxns(strcmp(allModels.rxnFrom,model.id)),model.rxns(~originalFlux));
+0182     
+0183     %Get the ones that still cannot carry flux
+0184     I=haveFlux(allModels,1,toCheck);
+0185     
+0186     %Get the reactions that can't carry flux in the original model, but can
+0187     %in the merged one
+0188     K=toCheck(I);
+0189     
+0190     %This is a temporary thing to only look at the non-reversible rxns.
+0191     %This is because all reversible rxns can have a flux in the
+0192     %irreversible model format that is used by getMinNrFluxes
+0193     [~, I]=ismember(K,model.rxns);
+0194     K(model.rev(I)~=0)=[];
+0195     
+0196     %Constrain all reactions in the original model to have a flux
+0197     allModels.lb(ismember(allModels.rxns,K))=0.1;
+0198     
+0199     %Return stuff
+0200     newConnected=K;
+0201     cannotConnect=setdiff(model.rxns(~originalFlux),newConnected);
+0202 end
+0203 
+0204 %Then minimize for the number of fluxes used. The fixed rxns doesn't need
+0205 %to participate
+0206 templateRxns=find(~strcmp(allModels.rxnFrom,model.id));
+0207 [~, J, exitFlag]=getMinNrFluxes(allModels,templateRxns,params,allModels.rxnScores(templateRxns));
+0208 
+0209 %Remove everything except for the added ones
+0210 I=true(numel(allModels.rxns),1);
+0211 I(templateRxns(J))=false;
+0212 addedModel=removeReactions(allModels,I,true,true,true);
+0213 
+0214 newModel=mergeModels({model;addedModel},'metNames',true);
+0215 addedRxns=setdiff(newModel.rxns,model.rxns);
+0216 newModel=rmfield(newModel,'rxnScores');
+0217 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/findGeneDeletions.html b/doc/core/findGeneDeletions.html new file mode 100644 index 000000000..cb115c6ea --- /dev/null +++ b/doc/core/findGeneDeletions.html @@ -0,0 +1,293 @@ + + + + Description of findGeneDeletions + + + + + + + + + +
Home > core > findGeneDeletions.m
+ + + +

findGeneDeletions +

+ +

PURPOSE ^

+
findGeneDeletions
+ +

SYNOPSIS ^

+
function [genes, fluxes, originalGenes, details, grRatioMuts]=findGeneDeletions(model,testType,analysisType,refModel,oeFactor)
+ +

DESCRIPTION ^

+
 findGeneDeletions
+   Deletes genes, optimizes the model, and keeps track of the resulting
+   fluxes. This is used for identifying gene deletion targets.
+
+   model           a model structure
+   testType        single/double gene deletions/over expressions. Over
+                   expression only available if using MOMA
+                   'sgd'   single gene deletion
+                   'dgd'   double gene deletion
+                   'sgo'   single gene over expression
+                   'dgo'   double gene over expression
+                   (optional, default 'sgd')
+   analysisType    determines whether to use FBA ('fba') or MOMA ('moma')
+                   in the optimization. (optional, default 'fba')
+   refModel        MOMA works by fitting the flux distributions of two
+                   models to be as similar as possible. The most common
+                   application is where you have a reference model where
+                   some of the fluxes are constrained from experimental
+                   data. This model is required when using MOMA
+   oeFactor        a factor by which the fluxes should be increased if a
+                   gene is overexpressed (optional, default 10)
+
+   genes           a matrix with the genes that were deleted in each
+                   optimization (the gene indexes in originalGenes). Each
+                   row corresponds to a column in fluxes
+   fluxes          a matrix with the resulting fluxes. Double deletions
+                   that result in an unsolvable problem have all zero
+                   flux. Single deletions that result in an unsolvable
+                   problem are indicated in details instead
+   originalGenes   simply the genes in the input model. Included for
+                   simple presentation of the output
+   details         not all genes will be deleted in all analyses. It is
+                   for example not necessary to delete genes for dead end
+                   reactions. This is a vector with details about
+                   each gene in originalGenes and why or why not it was
+                   deleted
+                   1: Was deleted/overexpressed
+                   2: Proved lethal in sgd (single gene deletion)
+                   3: - redundant, no longer used -
+                   4: Involved in dead-end reaction
+   grRatioMuts     growth rate ratio between mutated strain and wild type,
+                   matches the originalGenes(genes) mutants. Note that
+                   this does not directly map to model.genes, as is the case
+                   for COBRA getEssentialGenes. However, this can be 
+                   obtained by afterwards running:
+                       grRatio=zeros(1,numel(model.genes));
+                       grRatio(genes)=grRatioMuts;
+
+ Usage: [genes, fluxes, originalGenes, details, grRatioMuts]=findGeneDeletions(model,testType,analysisType,...
+           refModel,oeFactor)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function [genes, fluxes, originalGenes, details, grRatioMuts]=findGeneDeletions(model,testType,analysisType,refModel,oeFactor)
+0002 % findGeneDeletions
+0003 %   Deletes genes, optimizes the model, and keeps track of the resulting
+0004 %   fluxes. This is used for identifying gene deletion targets.
+0005 %
+0006 %   model           a model structure
+0007 %   testType        single/double gene deletions/over expressions. Over
+0008 %                   expression only available if using MOMA
+0009 %                   'sgd'   single gene deletion
+0010 %                   'dgd'   double gene deletion
+0011 %                   'sgo'   single gene over expression
+0012 %                   'dgo'   double gene over expression
+0013 %                   (optional, default 'sgd')
+0014 %   analysisType    determines whether to use FBA ('fba') or MOMA ('moma')
+0015 %                   in the optimization. (optional, default 'fba')
+0016 %   refModel        MOMA works by fitting the flux distributions of two
+0017 %                   models to be as similar as possible. The most common
+0018 %                   application is where you have a reference model where
+0019 %                   some of the fluxes are constrained from experimental
+0020 %                   data. This model is required when using MOMA
+0021 %   oeFactor        a factor by which the fluxes should be increased if a
+0022 %                   gene is overexpressed (optional, default 10)
+0023 %
+0024 %   genes           a matrix with the genes that were deleted in each
+0025 %                   optimization (the gene indexes in originalGenes). Each
+0026 %                   row corresponds to a column in fluxes
+0027 %   fluxes          a matrix with the resulting fluxes. Double deletions
+0028 %                   that result in an unsolvable problem have all zero
+0029 %                   flux. Single deletions that result in an unsolvable
+0030 %                   problem are indicated in details instead
+0031 %   originalGenes   simply the genes in the input model. Included for
+0032 %                   simple presentation of the output
+0033 %   details         not all genes will be deleted in all analyses. It is
+0034 %                   for example not necessary to delete genes for dead end
+0035 %                   reactions. This is a vector with details about
+0036 %                   each gene in originalGenes and why or why not it was
+0037 %                   deleted
+0038 %                   1: Was deleted/overexpressed
+0039 %                   2: Proved lethal in sgd (single gene deletion)
+0040 %                   3: - redundant, no longer used -
+0041 %                   4: Involved in dead-end reaction
+0042 %   grRatioMuts     growth rate ratio between mutated strain and wild type,
+0043 %                   matches the originalGenes(genes) mutants. Note that
+0044 %                   this does not directly map to model.genes, as is the case
+0045 %                   for COBRA getEssentialGenes. However, this can be
+0046 %                   obtained by afterwards running:
+0047 %                       grRatio=zeros(1,numel(model.genes));
+0048 %                       grRatio(genes)=grRatioMuts;
+0049 %
+0050 % Usage: [genes, fluxes, originalGenes, details, grRatioMuts]=findGeneDeletions(model,testType,analysisType,...
+0051 %           refModel,oeFactor)
+0052 
+0053 originalModel=model;
+0054 if nargin<5
+0055     oeFactor=10;
+0056 end
+0057 if nargin<2
+0058     testType='sgd';
+0059 else
+0060     testType=char(testType);
+0061 end
+0062 
+0063 %Check that the test type is correct
+0064 if ~strcmpi(testType,'sgd') && ~strcmpi(testType,'dgd') && ~strcmpi(testType,'sgo') && ~strcmpi(testType,'dgo')
+0065     EM='Incorrect test type';
+0066     dispEM(EM);
+0067 end
+0068 
+0069 %Check that the analysis type is correct
+0070 if nargin<3
+0071     analysisType = 'fba';
+0072 else
+0073     analysisType=char(analysisType);
+0074     if ~any(strcmpi(analysisType,{'fba','moma'}))
+0075         EM='Incorrect analysis type';
+0076         dispEM(EM);
+0077     end
+0078 end
+0079 
+0080 if (strcmpi(testType,'sgo') || strcmpi(testType,'dgo')) && strcmpi(analysisType,'fba')
+0081     EM='Over expression is only available when using MOMA';
+0082     dispEM(EM);
+0083 end
+0084 
+0085 if strcmpi(analysisType,'moma') && nargin<4
+0086     EM='A reference model must be supplied when using MOMA';
+0087     dispEM(EM);
+0088 end
+0089 
+0090 originalGenes=model.genes;
+0091 details=zeros(numel(model.genes),1);
+0092 
+0093 %First simplify the model to reduce the size
+0094 model=simplifyModel(model,true,false,true,true);
+0095 model=removeReactions(model,{},true,true); %Removes unused genes
+0096 details(~ismember(originalGenes,model.genes))=4;
+0097 
+0098 [~, geneMapping]=ismember(model.genes,originalGenes);
+0099 growthWT=solveLP(model);
+0100 growthWT=growthWT.f;
+0101 
+0102 %Do single deletion/over expression. This is done here since the double
+0103 %deletion depends on which single deletions prove lethal (to reduce the
+0104 %size of the system)
+0105 if strcmpi(testType,'sgd') || strcmpi(testType,'sgo') || strcmpi(testType,'dgd')
+0106     fluxes=zeros(numel(model.rxns),numel(model.genes));
+0107     grRatioMuts=zeros(1,numel(model.genes));
+0108     for i=1:numel(model.genes)
+0109         if strcmpi(testType,'sgd') || strcmpi(testType,'dgd')
+0110             %Constrain all reactions involving the gene to 0
+0111             tempModel=removeGenes(model,i,false,false,false);
+0112         else
+0113             %To over express a gene, the stoichiometry of the corresponding
+0114             %reactions are changed so that the same flux leads to a higher
+0115             %production
+0116             tempModel=model;
+0117             I=find(model.rxnGeneMat(:,i));
+0118             tempModel.S(:,I)=tempModel.S(:,I).*oeFactor;
+0119         end
+0120         if strcmpi(analysisType,'fba') || strcmpi(testType,'dgd')
+0121             sol=solveLP(tempModel);
+0122         else
+0123             [fluxA, ~, flag]=qMOMA(tempModel,refModel);
+0124             sol.x=fluxA;
+0125             sol.stat=flag;
+0126         end
+0127         
+0128         %If the optimization terminated successfully
+0129         if sol.stat==1
+0130             fluxes(:,i)=sol.x;
+0131             grRatioMuts(i)=sol.f/growthWT;
+0132             details(geneMapping(i))=1;
+0133         else
+0134             fluxes(:,i)=0;
+0135             grRatioMuts(i)=0;
+0136             details(geneMapping(i))=2;
+0137         end
+0138     end
+0139     genes=geneMapping;
+0140 end
+0141 
+0142 %Now do for DGO. This is rather straight forward since it is always
+0143 %solvable and it doesn't matter if there are iso-enzymes
+0144 if strcmpi(testType,'dgo')
+0145     genesToModify=nchoosek(1:numel(model.genes),2);
+0146     genes=geneMapping(genesToModify);
+0147     %Since I assume that this is never lethal I set the details already
+0148     details(geneMapping)=1;
+0149     
+0150     fluxes=sparse(numel(model.rxns),size(genesToModify,1));
+0151     for i=1:size(genesToModify,1)
+0152         I=find(model.rxnGeneMat(:,genesToModify(i,:)));
+0153         %To over express a gene, the stoichiometry of the corresponding
+0154         %reactions are changed so that the same flux leads to a higher
+0155         %production
+0156         tempModel=model;
+0157         tempModel.S(:,I)=tempModel.S(:,I).*oeFactor;
+0158         fluxA=qMOMA(tempModel,refModel);
+0159         fluxes(:,i)=fluxA;
+0160         grRatioMuts(i)=fluxA(logical(model.c))/growthWT;
+0161     end
+0162 end
+0163 
+0164 %For double deletions FBA or MOMA
+0165 if strcmpi(testType,'dgd')
+0166     %This is a little lazy but it's fine. Check which genes have already
+0167     %been deleted in 'sgd' analysis.
+0168     [~, I]=ismember(originalGenes(details==1),model.genes);
+0169     genesToModify=nchoosek(I,2);
+0170     genes=geneMapping(genesToModify);
+0171     grRatioMuts=zeros(1,numel(genes));
+0172     fluxes=sparse(numel(model.rxns),size(genesToModify,1));
+0173     for i=1:size(genesToModify,1)
+0174         tempModel=removeGenes(model,genesToModify(i,:),false,false,false);
+0175         
+0176         if strcmpi(analysisType,'fba')
+0177             sol=solveLP(tempModel);
+0178         else
+0179             [fluxA, ~, flag]=qMOMA(tempModel,refModel);
+0180             sol.x=fluxA;
+0181             sol.stat=flag;
+0182         end
+0183         
+0184         if sol.stat==1
+0185             fluxes(:,i)=sol.x;
+0186             grRatioMuts(i)=sol.f/growthWT;
+0187         end
+0188     end
+0189 end
+0190 
+0191 %Map back to the old model
+0192 [~, I]=ismember(model.rxns,originalModel.rxns);
+0193 temp=fluxes;
+0194 fluxes=sparse(numel(originalModel.rxns),size(temp,2));
+0195 fluxes(I,:)=temp;
+0196 end
+0197
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/findRAVENroot.html b/doc/core/findRAVENroot.html new file mode 100644 index 000000000..df783a87b --- /dev/null +++ b/doc/core/findRAVENroot.html @@ -0,0 +1,78 @@ + + + + Description of findRAVENroot + + + + + + + + + +
Home > core > findRAVENroot.m
+ + + +

findRAVENroot +

+ +

PURPOSE ^

+
findRAVENroot
+ +

SYNOPSIS ^

+
function [ravenPath, prevDir] = findRAVENroot()
+ +

DESCRIPTION ^

+
 findRAVENroot
+   Finds the root of the RAVEN directory, first by  by searching for the path to
+   RAVEN2.png. Can also record the current directory, in case a function will
+   use the ravenPath to navigate to a precise folder, and it should return to
+   the previous directory afterwards. See e.g. optimizeProb calling glpk.
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function [ravenPath, prevDir] = findRAVENroot()
+0002 % findRAVENroot
+0003 %   Finds the root of the RAVEN directory, first by  by searching for the path to
+0004 %   RAVEN2.png. Can also record the current directory, in case a function will
+0005 %   use the ravenPath to navigate to a precise folder, and it should return to
+0006 %   the previous directory afterwards. See e.g. optimizeProb calling glpk.
+0007 
+0008 ST=dbstack('-completenames');
+0009 prevDir = pwd();
+0010 if ispref('RAVEN','ravenPath')
+0011     ravenPath = getpref('RAVEN','ravenPath');
+0012 else
+0013     ravenPath = ST(strcmp({ST.name},'findRAVENroot')).file;
+0014     rootFound = 0;
+0015     while rootFound == 0
+0016         isRoot = isfile(fullfile(ravenPath,'RAVEN2.png'));
+0017         if isRoot
+0018             rootFound = 1;
+0019         else
+0020             ravenPathOld = ravenPath;
+0021             ravenPath = fileparts(ravenPath);
+0022             if strcmp(ravenPathOld,ravenPath)
+0023                 error('Cannot find the RAVEN root directory. Make sure you have not removed the RAVEN2.png file from your RAVEN installation.')
+0024             end
+0025         end
+0026     end
+0027 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/fitParameters.html b/doc/core/fitParameters.html new file mode 100644 index 000000000..6e19da4ba --- /dev/null +++ b/doc/core/fitParameters.html @@ -0,0 +1,199 @@ + + + + Description of fitParameters + + + + + + + + + +
Home > core > fitParameters.m
+ + + +

fitParameters +

+ +

PURPOSE ^

+
fitParameters
+ +

SYNOPSIS ^

+
function [parameters, fitnessScore, exitFlag, newModel]=fitParameters(model,xRxns,xValues,rxnsToFit,valuesToFit,parameterPositions,fitToRatio,initialGuess,plotFitting)
+ +

DESCRIPTION ^

+
 fitParameters
+   Fits parameters such as maintenance ATP by quadratic programming
+
+   model                 a model structure
+   xRxns                 cell array with the IDs of the reactions that will be
+                         fixed for each data point
+   xValues               matrix with the corresponding values for each
+                         xRxns (columns are reactions)
+   rxnsToFit             cell array with the IDs of reactions that will be fitted to
+   valuesToFit           matrix with the corresponding values for each
+                         rxnsToFit (columns are reactions)
+   parameterPositions    stucture that determines where the parameters are in the
+                         stoichiometric matrix. Contains the fields:
+       position          cell array of vectors where each element contains
+                         the positions in the S-matrix for that parameter
+       isNegative        cell array of vectors where the elements are true
+                         if that position should be the negative of the
+                         fitted value (to differentiate between
+                         production/consumption)
+    fitToRatio            if the ratio of simulated to measured values should
+                         be fitted instead of the absolute value. Used to prevent
+                         large fluxes from having too large impact (optional,
+                         default true)
+   initialGuess          initial guess of the parameters (optional)
+   plotFitting           true if the resulting fitting should be plotted
+                         (optional, default false)
+
+   parameters            fitted parameters in the same order as in
+                         parameterPositions
+   fitnessScore          the correponding residual sum of squares
+   newModel              updated model structure with the fitted parameters
+
+ Usage: [parameters, fitnessScore, exitFlag, newModel]=fitParameters(model,...
+           xRxns,xValues,rxnsToFit,valuesToFit,parameterPositions,fitToRatio,...
+           initialGuess,plotFitting)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 function [parameters, fitnessScore, exitFlag, newModel]=fitParameters(model,xRxns,xValues,rxnsToFit,valuesToFit,parameterPositions,fitToRatio,initialGuess,plotFitting)
+0002 % fitParameters
+0003 %   Fits parameters such as maintenance ATP by quadratic programming
+0004 %
+0005 %   model                 a model structure
+0006 %   xRxns                 cell array with the IDs of the reactions that will be
+0007 %                         fixed for each data point
+0008 %   xValues               matrix with the corresponding values for each
+0009 %                         xRxns (columns are reactions)
+0010 %   rxnsToFit             cell array with the IDs of reactions that will be fitted to
+0011 %   valuesToFit           matrix with the corresponding values for each
+0012 %                         rxnsToFit (columns are reactions)
+0013 %   parameterPositions    stucture that determines where the parameters are in the
+0014 %                         stoichiometric matrix. Contains the fields:
+0015 %       position          cell array of vectors where each element contains
+0016 %                         the positions in the S-matrix for that parameter
+0017 %       isNegative        cell array of vectors where the elements are true
+0018 %                         if that position should be the negative of the
+0019 %                         fitted value (to differentiate between
+0020 %                         production/consumption)
+0021 %    fitToRatio            if the ratio of simulated to measured values should
+0022 %                         be fitted instead of the absolute value. Used to prevent
+0023 %                         large fluxes from having too large impact (optional,
+0024 %                         default true)
+0025 %   initialGuess          initial guess of the parameters (optional)
+0026 %   plotFitting           true if the resulting fitting should be plotted
+0027 %                         (optional, default false)
+0028 %
+0029 %   parameters            fitted parameters in the same order as in
+0030 %                         parameterPositions
+0031 %   fitnessScore          the correponding residual sum of squares
+0032 %   newModel              updated model structure with the fitted parameters
+0033 %
+0034 % Usage: [parameters, fitnessScore, exitFlag, newModel]=fitParameters(model,...
+0035 %           xRxns,xValues,rxnsToFit,valuesToFit,parameterPositions,fitToRatio,...
+0036 %           initialGuess,plotFitting)
+0037 
+0038 if nargin<7
+0039     fitToRatio=true;
+0040 end
+0041 if nargin<8
+0042     initialGuess=ones(numel(parameterPositions.position),1);
+0043 end
+0044 if isempty(initialGuess)
+0045     initialGuess=ones(numel(parameterPositions.position),1);
+0046 end
+0047 if nargin<9
+0048     plotFitting=false;
+0049 end
+0050 
+0051 xRxns=convertCharArray(xRxns);
+0052 rxnsToFit=convertCharArray(rxnsToFit);
+0053 
+0054 %Find the indexes of reactions that will be fitted
+0055 [I, rxnsToFitIndexes]=ismember(rxnsToFit,model.rxns);
+0056 
+0057 if ~all(I)
+0058     EM='Could not find all reactions in rxnsToFit';
+0059     dispEM(EM);
+0060 end
+0061 
+0062 %Find the indexes of reactions that will be used for constraints.
+0063 [I, xRxnsIndexes]=ismember(xRxns,model.rxns);
+0064 
+0065 if ~all(I)
+0066     EM='Could not find all reactions in xRxns';
+0067     dispEM(EM);
+0068 end
+0069 
+0070 [parameters, fitnessScore, exitFlag]=fminsearch(@(parameters) getRSS(parameters,model,xRxnsIndexes,xValues,rxnsToFitIndexes,valuesToFit,parameterPositions,fitToRatio),initialGuess);
+0071 
+0072 parameters=abs(parameters);
+0073 
+0074 if plotFitting==true
+0075     %Set the resulting parameters
+0076     [~, resultingFluxes, newModel]=getRSS(parameters,model,xRxnsIndexes,xValues,rxnsToFitIndexes,valuesToFit,parameterPositions,true);
+0077     plot(xValues,valuesToFit,'o',xValues,resultingFluxes,'-*');
+0078 end
+0079 end
+0080 
+0081 function [rss, resultingFluxes, newModel]=getRSS(parameters,model,xRxnsIndexes,xValues,rxnsToFitIndexes,valuesToFit,parameterPositions,fitToRatio)
+0082 parameters=abs(parameters);
+0083 
+0084 %Set the parameters at the positions specified in parameterPositions
+0085 for i=1:numel(parameterPositions.position)
+0086     %Set positive
+0087     model.S(parameterPositions.position{i}(parameterPositions.isNegative{i}==false))=parameters(i);
+0088     
+0089     %Set negative
+0090     model.S(parameterPositions.position{i}(parameterPositions.isNegative{i}==true))=parameters(i)*-1;
+0091 end
+0092 
+0093 %Also return an updated model
+0094 newModel=model;
+0095 
+0096 %Loop through each data point, set xRxns to xValues and calculate the sum
+0097 %of squares for the rxnsToFit
+0098 rss=0;
+0099 resultingFluxes=[];
+0100 for i=1:size(xValues,1)
+0101     %Fix for more xRxns!
+0102     model.lb(xRxnsIndexes)=xValues(i,:);
+0103     model.ub(xRxnsIndexes)=xValues(i);
+0104     
+0105     sol=solveLP(model);
+0106     
+0107     %Calculate the rss
+0108     if fitToRatio==false
+0109         rs=sol.x(rxnsToFitIndexes)'-valuesToFit(i,:);
+0110     else
+0111         rs=sol.x(rxnsToFitIndexes)'./valuesToFit(i,:)-ones(1,size(valuesToFit,2));
+0112     end
+0113     rss=rss+rs*rs';
+0114     resultingFluxes=[resultingFluxes sol.x(rxnsToFitIndexes)];
+0115 end
+0116 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/fitTasks.html b/doc/core/fitTasks.html new file mode 100644 index 000000000..03cc88954 --- /dev/null +++ b/doc/core/fitTasks.html @@ -0,0 +1,409 @@ + + + + Description of fitTasks + + + + + + + + + +
Home > core > fitTasks.m
+ + + +

fitTasks +

+ +

PURPOSE ^

+
fitTasks
+ +

SYNOPSIS ^

+
function [outModel, addedRxns]=fitTasks(model,refModel,inputFile,printOutput,rxnScores,taskStructure)
+ +

DESCRIPTION ^

+
 fitTasks
+   Fills gaps in a model by including reactions from a reference model,
+   so that the resulting model can perform all the tasks in a task list
+
+   Input:
+   model           model structure
+   refModel        reference model from which to include reactions
+   inputFile       a task list in Excel format. See the function
+                   parseTaskList for details (optional if taskStructure is
+                   supplied)
+   printOutput     true if the results of the test should be displayed
+                   (optional, default true)
+   rxnScores       scores for each of the reactions in the reference
+                   model. Only negative scores are allowed. The solver will
+                   try to maximize the sum of the scores for the included
+                   reactions (optional, default is -1 for all reactions)
+   taskStructure   structure with the tasks, as from parseTaskList. If
+                   this is supplied then inputFile is ignored (optional)
+
+
+   Output:
+   outModel        model structure with reactions added to perform the
+                   tasks
+   addedRxns       MxN matrix with the added reactions (M) from refModel
+                   for each task (N). An element is true if the corresponding
+                   reaction is added in the corresponding task.
+                   Failed tasks and SHOULD FAIL tasks are ignored
+
+   This function fills gaps in a model by using a reference model, so
+   that the resulting model can perform a list of metabolic tasks. The
+   gap-filling is done in a task-by-task manner, rather than solving for
+   all tasks at once. This means that the order of the tasks could influence
+   the result.
+
+ Usage: [outModel, addedRxns]=fitTasks(model,refModel,inputFile,printOutput,...
+           rxnScores,taskStructure)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function [outModel, addedRxns]=fitTasks(model,refModel,inputFile,printOutput,rxnScores,taskStructure)
+0002 % fitTasks
+0003 %   Fills gaps in a model by including reactions from a reference model,
+0004 %   so that the resulting model can perform all the tasks in a task list
+0005 %
+0006 %   Input:
+0007 %   model           model structure
+0008 %   refModel        reference model from which to include reactions
+0009 %   inputFile       a task list in Excel format. See the function
+0010 %                   parseTaskList for details (optional if taskStructure is
+0011 %                   supplied)
+0012 %   printOutput     true if the results of the test should be displayed
+0013 %                   (optional, default true)
+0014 %   rxnScores       scores for each of the reactions in the reference
+0015 %                   model. Only negative scores are allowed. The solver will
+0016 %                   try to maximize the sum of the scores for the included
+0017 %                   reactions (optional, default is -1 for all reactions)
+0018 %   taskStructure   structure with the tasks, as from parseTaskList. If
+0019 %                   this is supplied then inputFile is ignored (optional)
+0020 %
+0021 %
+0022 %   Output:
+0023 %   outModel        model structure with reactions added to perform the
+0024 %                   tasks
+0025 %   addedRxns       MxN matrix with the added reactions (M) from refModel
+0026 %                   for each task (N). An element is true if the corresponding
+0027 %                   reaction is added in the corresponding task.
+0028 %                   Failed tasks and SHOULD FAIL tasks are ignored
+0029 %
+0030 %   This function fills gaps in a model by using a reference model, so
+0031 %   that the resulting model can perform a list of metabolic tasks. The
+0032 %   gap-filling is done in a task-by-task manner, rather than solving for
+0033 %   all tasks at once. This means that the order of the tasks could influence
+0034 %   the result.
+0035 %
+0036 % Usage: [outModel, addedRxns]=fitTasks(model,refModel,inputFile,printOutput,...
+0037 %           rxnScores,taskStructure)
+0038 
+0039 if nargin<4
+0040     printOutput=true;
+0041 end
+0042 if nargin<5
+0043     rxnScores=ones(numel(refModel.rxns),1)*-1;
+0044 end
+0045 if isempty(rxnScores)
+0046     rxnScores=ones(numel(refModel.rxns),1)*-1;
+0047 end
+0048 if nargin<6
+0049     taskStructure=[];
+0050 end
+0051 
+0052 if isempty(taskStructure) && ~isfile(inputFile)
+0053     error('Task file %s cannot be found',string(inputFile));
+0054 end
+0055 
+0056 if strcmpi(model.id,refModel.id)
+0057     fprintf('NOTE: The model and reference model have the same IDs. The ID for the reference model was set to "refModel" in order to keep track of the origin of reactions.\n');
+0058     refModel.id='refModel';
+0059 end
+0060 
+0061 if any(rxnScores>=0)
+0062     EM='Only negative values are allowed in rxnScores';
+0063     dispEM(EM);
+0064 end
+0065 
+0066 %Prepare the input models a little
+0067 model.b=zeros(numel(model.mets),2);
+0068 modelMets=upper(strcat(model.metNames,'[',model.comps(model.metComps),']'));
+0069 %This is the mets in the reference model. Used if the tasks involve
+0070 %metabolites that doesn't exist in the model
+0071 largeModelMets=upper(strcat(refModel.metNames,'[',refModel.comps(refModel.metComps),']'));
+0072 
+0073 if ~isfield(model,'unconstrained')
+0074     EM='Exchange metabolites should normally not be removed from the model when using checkTasks. Inputs and outputs are defined in the task file instead. Use importModel(file,false) to import a model with exchange metabolites remaining';
+0075     dispEM(EM,false);
+0076 end
+0077 
+0078 if isempty(taskStructure)
+0079     taskStructure=parseTaskList(inputFile);
+0080 end
+0081 
+0082 tModel=model;
+0083 addedRxns=false(numel(refModel.rxns),numel(taskStructure));
+0084 supressWarnings=false;
+0085 nAdded=0;
+0086 for i=1:numel(taskStructure)
+0087     if ~taskStructure(i).shouldFail
+0088         %Set the inputs
+0089         if ~isempty(taskStructure(i).inputs)
+0090             [I, J]=ismember(upper(taskStructure(i).inputs),modelMets);
+0091             K=ismember(upper(taskStructure(i).inputs),'ALLMETS');
+0092             L=~cellfun('isempty',strfind(upper(taskStructure(i).inputs),'ALLMETSIN'));
+0093             %Check that all metabolites are either real metabolites or
+0094             %ALLMETS/ALLMETSIN
+0095             goodMets=I|K|L;
+0096             if ~all(goodMets)
+0097                 %Not all of the inputs could be found in the small model.
+0098                 %Check if they exist in the large model
+0099                 [found, metMatch]=ismember(upper(taskStructure(i).inputs(~goodMets)),largeModelMets);
+0100                 if ~all(found)
+0101                     EM=['Could not find all inputs in "[' taskStructure(i).id '] ' taskStructure(i).description '" in either model'];
+0102                     disp(EM);
+0103                 else
+0104                     %Otherwise add them to the model
+0105                     met.metNames=refModel.metNames(metMatch);
+0106                     met.compartments=refModel.comps(refModel.metComps(metMatch));
+0107                     
+0108                     %Add the metabolite both to the base model and the
+0109                     %model used in the current task
+0110                     model=addMets(model,met);
+0111                     tModel=addMets(tModel,met);
+0112                     modelMets=[modelMets;upper(taskStructure(i).inputs(~goodMets))];
+0113                 end
+0114                 
+0115                 %By now the indexes might be getting a bit confusing, but
+0116                 %this is to update the indexes of the "real" metabolites to
+0117                 %point to the newly added ones
+0118                 I(~goodMets)=true; %All the bad ones are fixed at this stage
+0119                 J(~goodMets)=numel(modelMets)-numel(metMatch)+1:numel(modelMets);
+0120             end
+0121             if numel(J(I))~=numel(unique(J(I)))
+0122                 EM=['The constraints on some input(s) in "[' taskStructure(i).id '] ' taskStructure(i).description '" are defined more than one time'];
+0123                 dispEM(EM);
+0124             end
+0125             %If all metabolites should be added
+0126             if any(K)
+0127                 %Check if ALLMETS is the first metabolite. Otherwise print
+0128                 %a warning since it will write over any other constraints
+0129                 %that are set
+0130                 if K(1)==0
+0131                     EM=['ALLMETS is used as an input in "[' taskStructure(i).id '] ' taskStructure(i).description '" but it it not the first metabolite in the list. Constraints defined for the metabolites before it will be over-written'];
+0132                     dispEM(EM,false);
+0133                 end
+0134                 %Use the first match of ALLMETS. There should only be one,
+0135                 %but still..
+0136                 tModel.b(:,1)=taskStructure(i).UBin(find(K,1))*-1;
+0137             end
+0138             %If metabolites in a specific compartment should be used
+0139             if any(L)
+0140                 L=find(L);
+0141                 for j=1:numel(L)
+0142                     %The compartment defined
+0143                     compartment=upper(taskStructure(i).inputs{L(j)}(11:end-1));
+0144                     %Check if it exists in the model
+0145                     C=find(ismember(upper(model.comps),compartment));
+0146                     if any(C)
+0147                         %Match to metabolites
+0148                         tModel.b(model.metComps==C,1)=taskStructure(i).UBin(L(j))*-1;
+0149                     else
+0150                         EM=['The compartment defined for ALLMETSIN in "[' taskStructure(i).id '] ' taskStructure(i).description '" does not exist'];
+0151                         dispEM(EM);
+0152                     end
+0153                 end
+0154             end
+0155             %Then add the normal constraints
+0156             if any(J(I))
+0157                 tModel.b(J(I),1)=taskStructure(i).UBin(I)*-1;
+0158                 tModel.b(J(I),2)=taskStructure(i).LBin(I)*-1;
+0159             end
+0160         end
+0161         %Set the outputs
+0162         if ~isempty(taskStructure(i).outputs)
+0163             [I, J]=ismember(upper(taskStructure(i).outputs),modelMets);
+0164             K=ismember(upper(taskStructure(i).outputs),'ALLMETS');
+0165             L=~cellfun('isempty',strfind(upper(taskStructure(i).outputs),'ALLMETSIN'));
+0166             %Check that all metabolites are either real metabolites or
+0167             %ALLMETS/ALLMETSIN
+0168             goodMets=I|K|L;
+0169             if ~all(goodMets)
+0170                 %Not all of the outputs could be found in the small model.
+0171                 %Check if they exist in the large model
+0172                 [found, metMatch]=ismember(upper(taskStructure(i).outputs(~goodMets)),largeModelMets);
+0173                 if ~all(found)
+0174                     EM=['Could not find all outputs in "[' taskStructure(i).id '] ' taskStructure(i).description '" in either model'];
+0175                     dispEM(EM);
+0176                 else
+0177                     %Otherwise add them to the model
+0178                     met.metNames=refModel.metNames(metMatch);
+0179                     met.compartments=refModel.comps(refModel.metComps(metMatch));
+0180                     
+0181                     %Add the metabolite both to the base model and the
+0182                     %model used in the current task
+0183                     model=addMets(model,met);
+0184                     tModel=addMets(tModel,met);
+0185                     modelMets=[modelMets;upper(taskStructure(i).outputs(~goodMets))];
+0186                 end
+0187                 
+0188                 %By now the indexes might be getting a bit confusing, but
+0189                 %this is to update the indexes of the "real" metabolites to
+0190                 %point to the newly added ones
+0191                 I(~goodMets)=true; %All the bad ones are fixed at this stage
+0192                 J(~goodMets)=numel(modelMets)-numel(metMatch)+1:numel(modelMets);
+0193             end
+0194             if numel(J(I))~=numel(unique(J(I)))
+0195                 EM=['The constraints on some output(s) in "[' taskStructure(i).id '] ' taskStructure(i).description '" are defined more than one time'];
+0196                 dispEM(EM);
+0197             end
+0198             %If all metabolites should be added
+0199             if any(K)
+0200                 %Check if ALLMETS is the first metabolite. Otherwise print
+0201                 %a warning since it will write over any other constraints
+0202                 %that are set
+0203                 if K(1)==0
+0204                     EM=['ALLMETS is used as an output in "[' taskStructure(i).id '] ' taskStructure(i).description '" but it it not the first metabolite in the list. Constraints defined for the metabolites before it will be over-written'];
+0205                     dispEM(EM,false);
+0206                 end
+0207                 %Use the first match of ALLMETS. There should only be one,
+0208                 %but still..
+0209                 tModel.b(:,2)=taskStructure(i).UBout(find(K,1));
+0210             end
+0211             %If metabolites in a specific compartment should be used
+0212             if any(L)
+0213                 L=find(L);
+0214                 for j=1:numel(L)
+0215                     %The compartment defined
+0216                     compartment=upper(taskStructure(i).outputs{L(j)}(11:end-1));
+0217                     %Check if it exists in the model
+0218                     C=find(ismember(upper(model.comps),compartment));
+0219                     if any(C)
+0220                         %Match to metabolites
+0221                         tModel.b(model.metComps==C,2)=taskStructure(i).UBout(L(j));
+0222                     else
+0223                         EM=['The compartment defined for ALLMETSIN in "[' taskStructure(i).id '] ' taskStructure(i).description '" does not exist'];
+0224                         dispEM(EM);
+0225                     end
+0226                 end
+0227             end
+0228             %Then add the normal constraints
+0229             if any(J(I))
+0230                 %Verify that IN and OUT bounds are consistent. Cannot require
+0231                 %that a metabolite is simultaneously input AND output at some
+0232                 %nonzero flux.
+0233                 J = J(I);
+0234                 I = find(I);  % otherwise indexing becomes confusing
+0235                 nonzero_LBin = tModel.b(J,2) < 0;
+0236                 nonzero_LBout = taskStructure(i).LBout(I) > 0;
+0237                 if any(nonzero_LBin & nonzero_LBout)
+0238                     EM=['The IN LB and OUT LB in "[' taskStructure(i).id '] ' taskStructure(i).description '" cannot be nonzero for the same metabolite'];
+0239                     dispEM(EM);
+0240                 end
+0241                 tModel.b(J(nonzero_LBout),1)=taskStructure(i).LBout(I(nonzero_LBout));
+0242                 tModel.b(J,2)=taskStructure(i).UBout(I);
+0243             end
+0244         end
+0245         
+0246         %Add new rxns
+0247         if ~isempty(taskStructure(i).equations)
+0248             rxn.equations=taskStructure(i).equations;
+0249             rxn.lb=taskStructure(i).LBequ;
+0250             rxn.ub=taskStructure(i).UBequ;
+0251             rxn.rxns=strcat({'TEMPORARY_'},num2str((1:numel(taskStructure(i).equations))'));
+0252             tModel=addRxns(tModel,rxn,3);
+0253         end
+0254         %Add changed bounds
+0255         if ~isempty(taskStructure(i).changed)
+0256             tModel=setParam(tModel,'lb',taskStructure(i).changed,taskStructure(i).LBrxn);
+0257             tModel=setParam(tModel,'ub',taskStructure(i).changed,taskStructure(i).UBrxn);
+0258         end
+0259         
+0260         %Solve and print. Display a warning if the problem is not solveable
+0261         sol=solveLP(tModel);
+0262         if isempty(sol.x)
+0263             %Only do gap-filling if it cannot be solved
+0264             failed=false;
+0265             try
+0266                 [~, ~, newRxns, newModel, exitFlag]=fillGaps(tModel,refModel,false,true,supressWarnings,rxnScores);
+0267                 if exitFlag==-2
+0268                     EM=['"[' taskStructure(i).id '] ' taskStructure(i).description '" was aborted before reaching optimality.\n'];
+0269                     dispEM(EM,false);
+0270                 end
+0271             catch
+0272                 EM=['"[' taskStructure(i).id '] ' taskStructure(i).description '" could not be performed for any set of reactions\n'];
+0273                 dispEM(EM,false);
+0274                 failed=true;
+0275             end
+0276             if failed==false
+0277                 if ~isempty(newRxns)
+0278                     nAdded=nAdded+numel(newRxns);
+0279                     
+0280                     %Add the reactions to the base model. It is not correct
+0281                     %to use newModel directly, as it may contain
+0282                     %reactions/constraints that are specific to this task
+0283                     model=mergeModels({model,removeReactions(newModel,setdiff(newModel.rxns,newRxns),true,true)},'metNames',true);
+0284                     
+0285                     %Keep track of the added reactions
+0286                     addedRxns(ismember(refModel.rxns,newRxns),i)=true;
+0287                 end
+0288                 if printOutput==true
+0289                     fprintf(['[' taskStructure(i).id '] ' taskStructure(i).description ': Added ' num2str(numel(newRxns)) ' reaction(s), ' num2str(nAdded) ' reactions added in total\n']);
+0290                 end
+0291             end
+0292         else
+0293             if printOutput==true
+0294                 fprintf(['[' taskStructure(i).id '] ' taskStructure(i).description ': Added 0 reaction(s), ' num2str(nAdded) ' reactions added in total\n']);
+0295             end
+0296         end
+0297         supressWarnings=true;
+0298         
+0299         %Print the output if chosen
+0300         if taskStructure(i).printFluxes && printOutput
+0301             if ~isempty(sol.x)
+0302                 sol=solveLP(tModel,1);
+0303                 printFluxes(tModel,sol.x,false,10^-5,[],'%rxnID (%eqn):%flux\n');
+0304                 fprintf('\n');
+0305             else
+0306                 %If the problem wasn't solveable then the gap-filled model
+0307                 %should be used
+0308                 if failed==false
+0309                     sol=solveLP(newModel,1);
+0310                     printFluxes(newModel,sol.x,false,10^-5,[],'%rxnID (%eqn):%flux\n');
+0311                     fprintf('\n');
+0312                 end
+0313             end
+0314         end
+0315         
+0316         tModel=model;
+0317         %Since new mets are added by merging the new reactions and not only
+0318         %from the task sheet
+0319         modelMets=upper(strcat(model.metNames,'[',model.comps(model.metComps),']'));
+0320     else
+0321         EM=['"[' taskStructure(i).id '] ' taskStructure(i).description '" is set as SHOULD FAIL. Such tasks cannot be modelled using this approach and the task is therefore ignored\n'];
+0322         dispEM(EM,false);
+0323     end
+0324 end
+0325 model.b(:,2) = [];  % resume field b
+0326 outModel=model;
+0327 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/followChanged.html b/doc/core/followChanged.html new file mode 100644 index 000000000..0329eb544 --- /dev/null +++ b/doc/core/followChanged.html @@ -0,0 +1,170 @@ + + + + Description of followChanged + + + + + + + + + +
Home > core > followChanged.m
+ + + +

followChanged +

+ +

PURPOSE ^

+
followChanged
+ +

SYNOPSIS ^

+
function followChanged(model,fluxesA,fluxesB, cutOffChange, cutOffFlux, cutOffDiff, metaboliteList)
+ +

DESCRIPTION ^

+
 followChanged
+    Prints fluxes and reactions for each of the reactions that results in
+   different fluxes compared to the reference case.
+
+   model           a model structure
+   fluxesA         flux vector for the test case
+   fluxesB         flux vector for the reference test
+   cutOffChange    reactions where the fluxes differ by less than
+                   this many percent won't be printed (optional, default 10^-8)
+   cutOffFlux      reactions where the absolute value of both fluxes
+                   are below this value won't be printed (optional,
+                   default 10^-8)
+   cutOffDiff      reactions where the fluxes differ by less than
+                   cutOffDiff won't be printed (optional, default 10^-8)
+   metaboliteList  cell array of metabolite names. Only reactions
+                   involving any of these metabolites will be
+                   printed (optional)
+
+ Usage: followChanged(model,fluxesA,fluxesB, cutOffChange, cutOffFlux,
+           cutOffDiff, metaboliteList)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function followChanged(model,fluxesA,fluxesB, cutOffChange, cutOffFlux, cutOffDiff, metaboliteList)
+0002 % followChanged
+0003 %    Prints fluxes and reactions for each of the reactions that results in
+0004 %   different fluxes compared to the reference case.
+0005 %
+0006 %   model           a model structure
+0007 %   fluxesA         flux vector for the test case
+0008 %   fluxesB         flux vector for the reference test
+0009 %   cutOffChange    reactions where the fluxes differ by less than
+0010 %                   this many percent won't be printed (optional, default 10^-8)
+0011 %   cutOffFlux      reactions where the absolute value of both fluxes
+0012 %                   are below this value won't be printed (optional,
+0013 %                   default 10^-8)
+0014 %   cutOffDiff      reactions where the fluxes differ by less than
+0015 %                   cutOffDiff won't be printed (optional, default 10^-8)
+0016 %   metaboliteList  cell array of metabolite names. Only reactions
+0017 %                   involving any of these metabolites will be
+0018 %                   printed (optional)
+0019 %
+0020 % Usage: followChanged(model,fluxesA,fluxesB, cutOffChange, cutOffFlux,
+0021 %           cutOffDiff, metaboliteList)
+0022 
+0023 %Checks if a cut off flux has been set
+0024 if nargin<4
+0025     cutOffChange=10^-8;
+0026 end
+0027 if nargin<5
+0028     cutOffFlux=10^-8;
+0029 end
+0030 if nargin<6
+0031     cutOffDiff=10^-8;
+0032 end
+0033 if nargin<7
+0034     metaboliteList=[];
+0035 else
+0036     metaboliteList=convertCharArray(metaboliteList);
+0037 end
+0038 
+0039 %If a metabolite list is to be used, then find all the reactions involving
+0040 %any of those metabolites Finds the metabolites
+0041 if nargin>6
+0042     reactionIndexes=[];
+0043     for i=1:length(metaboliteList)
+0044         metaboliteIndex=find(strcmpi(metaboliteList(i),model.metNames)); %Should use id maybe, setting
+0045         if ~isempty(metaboliteIndex)
+0046             [~, b]=find(model.S(metaboliteIndex,:));
+0047             reactionIndexes=[reactionIndexes; b(:)];
+0048         else
+0049             fprintf('Could not find any reactions with the metabolite %s\n\n',char(metaboliteList(i)))
+0050         end
+0051     end
+0052     reactionIndexes=unique(reactionIndexes);
+0053 else
+0054     reactionIndexes=(1:length(fluxesA))';
+0055 end
+0056 
+0057 %Finds the reactions where either flux is at or above the cutOffFlux value
+0058 in1=find(abs(fluxesA(reactionIndexes))>=cutOffFlux)';
+0059 in2=find(abs(fluxesB(reactionIndexes))>=cutOffFlux)';
+0060 ineither=reactionIndexes(unique([in1 in2]));
+0061 
+0062 %Keep only those solutions where the difference is larger than or equal to
+0063 %cutOffDiff
+0064 ineither=ineither(find(abs(fluxesA(ineither)-fluxesB(ineither))>=cutOffDiff));
+0065 
+0066 %Finds the reactions where the fluxes differ more than cutOffChange percent
+0067 %First check those fluxes that are non-zero in solution1.x
+0068 nonZeroFluxes=ineither(find(fluxesA(ineither)));
+0069 quota=1+cutOffChange/100;
+0070 larger=nonZeroFluxes(find((fluxesB(nonZeroFluxes)./fluxesA(nonZeroFluxes))>=(quota)))';
+0071 smaller=nonZeroFluxes(find((fluxesB(nonZeroFluxes)./fluxesA(nonZeroFluxes))<(1/quota)))';
+0072 fluxIndexes=[larger smaller];
+0073 
+0074 %Then add those where solution1 has a zero flux
+0075 zeroFluxes=ineither(find(fluxesA(ineither)==0));
+0076 fluxIndexes=unique([fluxIndexes zeroFluxes(find(abs(fluxesB(zeroFluxes))>=cutOffFlux))']);
+0077 
+0078 formulas=constructEquations(model,model.rxns(fluxIndexes));
+0079 
+0080 if nargin>4
+0081     if nargin>5
+0082         fprintf('These reactions have flux values that differ by more than %s percent, absolute values above %s, and a total difference above %s (%s reactions)\n\n',num2str(cutOffChange),num2str(cutOffFlux),num2str(cutOffDiff),num2str(length(formulas)));
+0083     else
+0084         fprintf('These reactions have flux values that differ by more than %s percent and absolute values above %s (%s reactions)\n\n',num2str(cutOffChange),num2str(cutOffFlux),num2str(length(formulas)));
+0085     end
+0086 else
+0087     fprintf('These reactions have flux values that differ by more than %s percent (%s reactions)\n\n',num2str(cutOffChange),num2str(length(formulas)));
+0088 end
+0089 
+0090 metaboliteNames=[];
+0091 for i=1:length(metaboliteList)
+0092     metaboliteNames=[metaboliteNames char(metaboliteList(i)) ' '];
+0093 end
+0094 
+0095 if ~isempty(metaboliteNames)
+0096     fprintf('Only prints reactions involving one or more of the following metabolites:\n%s\n\n',metaboliteNames)
+0097 end
+0098 
+0099 for i=1:length(formulas)
+0100     fluxText=['Flux: ' num2str(fluxesA(fluxIndexes(i))) ' Reference flux: ' num2str(fluxesB(fluxIndexes(i))) ' Difference: ' num2str(fluxesA(fluxIndexes(i))-fluxesB(fluxIndexes(i)))];
+0101     fprintf('%s: %s\n\t%s\n\t%s\n\n', char(model.rxns(fluxIndexes(i))), char(formulas(i)),...
+0102         char(model.rxnNames(fluxIndexes(i))),fluxText);
+0103 end
+0104 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/followFluxes.html b/doc/core/followFluxes.html new file mode 100644 index 000000000..ba410833f --- /dev/null +++ b/doc/core/followFluxes.html @@ -0,0 +1,109 @@ + + + + Description of followFluxes + + + + + + + + + +
Home > core > followFluxes.m
+ + + +

followFluxes +

+ +

PURPOSE ^

+
followFluxes
+ +

SYNOPSIS ^

+
function errorFlag=followFluxes(model, fluxesA, lowerFlux, upperFlux, fluxesB)
+ +

DESCRIPTION ^

+
 followFluxes
+    Prints fluxes and reactions for each of the reactions that results in
+   fluxes in the specified interval.
+
+   model       a model structure
+   fluxesA     flux vector for the test case
+   lowerFlux    only reactions with fluxes above this cutoff
+               value are displayed
+   upperFlux   only reactions with fluxes below this cutoff
+               value are displayed (optional, default Inf)
+   fluxesB     flux vector for the reference case(optional)
+
+ Usage: errorFlag=followFluxes(model, fluxesA, lowerFlux, upperFlux,
+           fluxesB)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function errorFlag=followFluxes(model, fluxesA, lowerFlux, upperFlux, fluxesB)
+0002 % followFluxes
+0003 %    Prints fluxes and reactions for each of the reactions that results in
+0004 %   fluxes in the specified interval.
+0005 %
+0006 %   model       a model structure
+0007 %   fluxesA     flux vector for the test case
+0008 %   lowerFlux    only reactions with fluxes above this cutoff
+0009 %               value are displayed
+0010 %   upperFlux   only reactions with fluxes below this cutoff
+0011 %               value are displayed (optional, default Inf)
+0012 %   fluxesB     flux vector for the reference case(optional)
+0013 %
+0014 % Usage: errorFlag=followFluxes(model, fluxesA, lowerFlux, upperFlux,
+0015 %           fluxesB)
+0016 
+0017 %Checks that the upper flux is larger than the lower flux
+0018 if nargin>3
+0019     if upperFlux<=lowerFlux
+0020         errorFlag=1;
+0021         return;
+0022     end
+0023 end
+0024 
+0025 %Gets the fluxes for the reactions
+0026 if nargin<4
+0027     fluxIndexes=find(fluxesA>=lowerFlux);
+0028 else
+0029     fluxIndexes=find(fluxesA>=lowerFlux & fluxesA<=upperFlux);
+0030 end
+0031 
+0032 %Finds the involved reactions
+0033 formulas = constructEquations(model,model.rxns(fluxIndexes));
+0034 
+0035 if nargin>3
+0036     fprintf('These reactions have flux values between %s and %s\n\n',num2str(lowerFlux),num2str(upperFlux));
+0037 else
+0038     fprintf('These reactions have flux values above %s\n\n',num2str(lowerFlux));
+0039 end
+0040 for i=1:length(formulas)
+0041     if nargin>4
+0042         fluxText=['Flux: ' num2str(fluxesA(fluxIndexes(i))) ' Reference flux: ' num2str(fluxesB(fluxIndexes(i)))];
+0043     else
+0044         fluxText=['Flux: ' num2str(fluxesA(fluxIndexes(i)))];
+0045     end
+0046     fprintf('%s: %s\n\t%s\n\t%s\n', char(model.rxns(fluxIndexes(i))), char(formulas(i)),...
+0047         char(model.rxnNames(fluxIndexes(i))),fluxText);
+0048 end
+0049 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/gapReport.html b/doc/core/gapReport.html new file mode 100644 index 000000000..3e8e78c5e --- /dev/null +++ b/doc/core/gapReport.html @@ -0,0 +1,193 @@ + + + + Description of gapReport + + + + + + + + + +
Home > core > gapReport.m
+ + + +

gapReport +

+ +

PURPOSE ^

+
gapReport
+ +

SYNOPSIS ^

+
function [noFluxRxns, noFluxRxnsRelaxed, subGraphs, notProducedMets, minToConnect,neededForProductionMat, canProduceWithoutInput, canConsumeWithoutOutput,connectedFromTemplates, addedFromTemplates]=gapReport(model, templateModels)
+ +

DESCRIPTION ^

+
 gapReport
+   Performs a gap analysis and summarizes the results 
+
+   model                       a model structure
+   templateModels              a cell array of template models to use for
+                               gap filling (optional)
+
+   noFluxRxns                  cell array with reactions that cannot carry
+                               flux
+   noFluxRxnsRelaxed           cell array with reactions that cannot carry
+                               flux even if the mass balance constraint is 
+                               relaxed so that it is allowed to have 
+                               net production of all metabolites
+   subGraphs                   structure with the metabolites in each of
+                               the isolated sub networks
+   notProducedMets             cell array with the metabolites that
+                               couldn't have net production
+   minToConnect                structure with the minimal number of
+                               metabolites that need to be connected in 
+                               order to be able to produce all other 
+                               metabolites and which metabolites each of
+                               them connects
+   neededForProductionMat      matrix where n x m is true if metabolite n
+                               allows for production of metabolite m
+   canProduceWithoutInput      cell array with metabolites that could be
+                               produced even when there is no input to the
+                               model
+   canConsumeWithoutOutput     cell array with metabolites that could be
+                               consumed even when there is no output from
+                               the model
+   connectedFromTemplates      cell array with the reactions that could be
+                               connected using the template models
+   addedFromTemplates          structure with the reactions that were
+                               added from the template models and which 
+                               model they were added from
+
+ Usage: [noFluxRxns, noFluxRxnsRelaxed, subGraphs, notProducedMets, minToConnect,...
+    neededForProductionMat, connectedFromTemplates, addedFromTemplates]=...
+    gapReport(model, templateModels)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function [noFluxRxns, noFluxRxnsRelaxed, subGraphs, notProducedMets, minToConnect,...
+0002     neededForProductionMat, canProduceWithoutInput, canConsumeWithoutOutput, ...
+0003     connectedFromTemplates, addedFromTemplates]=gapReport(model, templateModels)
+0004 % gapReport
+0005 %   Performs a gap analysis and summarizes the results
+0006 %
+0007 %   model                       a model structure
+0008 %   templateModels              a cell array of template models to use for
+0009 %                               gap filling (optional)
+0010 %
+0011 %   noFluxRxns                  cell array with reactions that cannot carry
+0012 %                               flux
+0013 %   noFluxRxnsRelaxed           cell array with reactions that cannot carry
+0014 %                               flux even if the mass balance constraint is
+0015 %                               relaxed so that it is allowed to have
+0016 %                               net production of all metabolites
+0017 %   subGraphs                   structure with the metabolites in each of
+0018 %                               the isolated sub networks
+0019 %   notProducedMets             cell array with the metabolites that
+0020 %                               couldn't have net production
+0021 %   minToConnect                structure with the minimal number of
+0022 %                               metabolites that need to be connected in
+0023 %                               order to be able to produce all other
+0024 %                               metabolites and which metabolites each of
+0025 %                               them connects
+0026 %   neededForProductionMat      matrix where n x m is true if metabolite n
+0027 %                               allows for production of metabolite m
+0028 %   canProduceWithoutInput      cell array with metabolites that could be
+0029 %                               produced even when there is no input to the
+0030 %                               model
+0031 %   canConsumeWithoutOutput     cell array with metabolites that could be
+0032 %                               consumed even when there is no output from
+0033 %                               the model
+0034 %   connectedFromTemplates      cell array with the reactions that could be
+0035 %                               connected using the template models
+0036 %   addedFromTemplates          structure with the reactions that were
+0037 %                               added from the template models and which
+0038 %                               model they were added from
+0039 %
+0040 % Usage: [noFluxRxns, noFluxRxnsRelaxed, subGraphs, notProducedMets, minToConnect,...
+0041 %    neededForProductionMat, connectedFromTemplates, addedFromTemplates]=...
+0042 %    gapReport(model, templateModels)
+0043 
+0044 if nargin<2
+0045     templateModels=[];
+0046     connectedFromTemplates=[];
+0047     addedFromTemplates=[];
+0048 end
+0049 
+0050 fprintf(['Gap analysis for ' model.id ' - ' model.name '\n\n']);
+0051 if isfield(model,'unconstrained')
+0052     calculateINOUT=true;
+0053     closedModel=model;
+0054     model=simplifyModel(model);
+0055 else
+0056     canConsumeWithoutOutput={};
+0057     canProduceWithoutInput={};
+0058     calculateINOUT=false;
+0059 end
+0060 
+0061 model2=model;
+0062 model2.b=[model2.b inf(numel(model2.mets),1)];
+0063 I=haveFlux(model);
+0064 noFluxRxns=model.rxns(~I);
+0065 J=haveFlux(model2);
+0066 noFluxRxnsRelaxed=model2.rxns(~J);
+0067 bModel=removeReactions(model,~I,true,true);
+0068 cModel=removeReactions(model2,~J,true,true);
+0069 fprintf('***Overview\n');
+0070 fprintf([num2str(numel(model.rxns)-sum(I)) ' out of ' num2str(numel(model.rxns))...
+0071     ' reactions cannot carry flux (' num2str(numel(model.rxns)-sum(J)) ' if net production of all metabolites is allowed)\n']);
+0072 fprintf([num2str(numel(model.mets)-numel(bModel.mets)) ' out of ' num2str(numel(model.mets))...
+0073     ' metabolites are unreachable (' num2str(numel(model.mets)-numel(cModel.mets)) ' if net production of all metabolites is allowed)\n']);
+0074 
+0075 fprintf('\n***Isolated subnetworks\n');
+0076 subGraphs=getAllSubGraphs(model);
+0077 fprintf(['A total of ' num2str(size(subGraphs,2)) ' isolated sub-networks are present in the model\n']);
+0078 for i=1:size(subGraphs,2)
+0079     fprintf(['\t' num2str(i) '. ' num2str(sum(subGraphs(:,i))) ' metabolites\n']);
+0080 end
+0081 
+0082 fprintf('\n***Metabolite connectivity\n');
+0083 [notProducedMets, ~, neededForProductionMat,minToConnect]=checkProduction(model,true,model.comps,false);
+0084 fprintf(['To enable net production of all metabolites, a total of ' num2str(numel(minToConnect)) ' metabolites must be connected\n']);
+0085 fprintf('Top 10 metabolites to connect:\n');
+0086 for i=1:min(10,numel(minToConnect))
+0087     fprintf(['\t' num2str(i) '. ' minToConnect{i} '\n']);
+0088 end
+0089 
+0090 if calculateINOUT==true
+0091     fprintf('\n***Mass balancing\n');
+0092     produced=canProduce(closedModel);
+0093     canProduceWithoutInput=closedModel.mets(produced);
+0094     consumed=canConsume(closedModel);
+0095     canConsumeWithoutOutput=closedModel.mets(consumed);
+0096     fprintf([num2str(numel(canConsumeWithoutOutput)) ' metabolites could be consumed without any outputs\n' num2str(numel(canProduceWithoutInput)) ' metabolites could be produced without any inputs\n']);
+0097 end
+0098 
+0099 if ~isempty(templateModels)
+0100     fprintf('\n***Automated gap-filling\n');
+0101     [connectedFromTemplates, ~, addedFromTemplates]=fillGaps(model,templateModels);
+0102     t=templateModels{1}.id;
+0103     for i=2:numel(templateModels)
+0104         t=[t ', ' templateModels{i}.id];
+0105     end
+0106     fprintf([num2str(numel(connectedFromTemplates)) ' unconnected reactions can be connected by including ' num2str(numel(addedFromTemplates)) ' reactions from\n' t '\n']);
+0107 end
+0108 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/generateNewIds.html b/doc/core/generateNewIds.html new file mode 100644 index 000000000..557c96030 --- /dev/null +++ b/doc/core/generateNewIds.html @@ -0,0 +1,123 @@ + + + + Description of generateNewIds + + + + + + + + + +
Home > core > generateNewIds.m
+ + + +

generateNewIds +

+ +

PURPOSE ^

+
generateNewIds
+ +

SYNOPSIS ^

+
function newIds=generateNewIds(model,type,prefix,quantity,numLength)
+ +

DESCRIPTION ^

+
 generateNewIds
+   Generates a list of new metabolite or reaction ids, sequentially
+   numbered with a defined prefix. The model is queried for the highest
+   existing number of that type of id.
+
+   model       model structure
+   type        string specifying type of id, 'rxns' or 'mets'
+   prefix      string specifying prefix to be used in all ids. E.g. 's_'
+               or 'r_'.
+   quantity    number of new ids that should be generated (optional, default 1)
+   numLength   length of numerical part of id. E.g. 4 gives ids like
+               r_0001 and 6 gives ids like r_000001. If the prefix is
+               already used in the model, then the model-defined length
+               will be used instead. (optional, default 4)
+
+ Usage: newIds=generateNewIds(model,type,prefix,quantity,numLength)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function newIds=generateNewIds(model,type,prefix,quantity,numLength)
+0002 % generateNewIds
+0003 %   Generates a list of new metabolite or reaction ids, sequentially
+0004 %   numbered with a defined prefix. The model is queried for the highest
+0005 %   existing number of that type of id.
+0006 %
+0007 %   model       model structure
+0008 %   type        string specifying type of id, 'rxns' or 'mets'
+0009 %   prefix      string specifying prefix to be used in all ids. E.g. 's_'
+0010 %               or 'r_'.
+0011 %   quantity    number of new ids that should be generated (optional, default 1)
+0012 %   numLength   length of numerical part of id. E.g. 4 gives ids like
+0013 %               r_0001 and 6 gives ids like r_000001. If the prefix is
+0014 %               already used in the model, then the model-defined length
+0015 %               will be used instead. (optional, default 4)
+0016 %
+0017 % Usage: newIds=generateNewIds(model,type,prefix,quantity,numLength)
+0018 %
+0019 type=char(type);
+0020 prefix=char(prefix);
+0021 
+0022 if type=='rxns'
+0023     existingIds=model.rxns;
+0024 elseif type=='mets'
+0025     existingIds=model.mets;
+0026 else
+0027     error('type should be either ''rxns'' or ''mets''.')
+0028 end
+0029 if nargin<4
+0030     quantity=1;
+0031 end
+0032 if nargin<5
+0033     numLength=4;
+0034 end
+0035 
+0036 % Subset only existingIds that have the prefix
+0037 existingIds=existingIds(~cellfun(@isempty,regexp(existingIds,['^' prefix])));
+0038 
+0039 if ~isempty(existingIds)
+0040     existingIds=regexprep(existingIds,['^' prefix],'');
+0041     existingIds=sort(existingIds);
+0042     lastId=existingIds{end};
+0043     numLength=length(lastId);
+0044     lastId=str2double(lastId);
+0045 else
+0046     lastId=0;
+0047     fprintf(['No ' type ' ids with prefix "' prefix ...
+0048         '" currently exist in the model. The first new id will be "' ...
+0049         [prefix,num2str(1,['%0' num2str(numLength) 'd'])] '"\n'],'%s')
+0050 end
+0051 
+0052 if isnan(lastId)
+0053     lastId = 0;
+0054 end
+0055 
+0056 newIds=cell(quantity,1);
+0057 
+0058 for k=1:quantity
+0059     newIds{k}=[prefix,num2str(k+lastId,['%0' num2str(numLength) 'd'])];
+0060 end
+0061 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/getAllRxnsFromGenes.html b/doc/core/getAllRxnsFromGenes.html new file mode 100644 index 000000000..1881ccb0b --- /dev/null +++ b/doc/core/getAllRxnsFromGenes.html @@ -0,0 +1,96 @@ + + + + Description of getAllRxnsFromGenes + + + + + + + + + +
Home > core > getAllRxnsFromGenes.m
+ + + +

getAllRxnsFromGenes +

+ +

PURPOSE ^

+
getAllRxnsFromGenes
+ +

SYNOPSIS ^

+
function allRxns=getAllRxnsFromGenes(model,rxns)
+ +

DESCRIPTION ^

+
 getAllRxnsFromGenes
+   Given a list of reactions, this function finds the associated genes in
+   the template model and gives all reactions that are annotated by these
+   genes.
+
+   model       a model structure
+   rxns        either a cell array of IDs, a logical vector with the
+               same number of elements as reactions in the model, or a
+               vector of indexes
+
+   allRxns     either a cell array of IDs, a logical vector with the
+               same number of elements as reactions in the model, or a
+               vector of indexes, dependent on the format of rxns
+
+ Usage: allRxns=getAllRxnsFromGenes(model,rxns)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function allRxns=getAllRxnsFromGenes(model,rxns)
+0002 % getAllRxnsFromGenes
+0003 %   Given a list of reactions, this function finds the associated genes in
+0004 %   the template model and gives all reactions that are annotated by these
+0005 %   genes.
+0006 %
+0007 %   model       a model structure
+0008 %   rxns        either a cell array of IDs, a logical vector with the
+0009 %               same number of elements as reactions in the model, or a
+0010 %               vector of indexes
+0011 %
+0012 %   allRxns     either a cell array of IDs, a logical vector with the
+0013 %               same number of elements as reactions in the model, or a
+0014 %               vector of indexes, dependent on the format of rxns
+0015 %
+0016 % Usage: allRxns=getAllRxnsFromGenes(model,rxns)
+0017 
+0018 if ~islogical(rxns) && ~isnumeric(rxns)
+0019     rxns=convertCharArray(rxns);
+0020 end
+0021 
+0022 rxnIdx=getIndexes(model,rxns,'rxns');
+0023 [~, geneIdx]=find(model.rxnGeneMat(rxnIdx,:));
+0024 [allRxns, ~]=find(model.rxnGeneMat(:,geneIdx));
+0025 if iscell(rxns)
+0026     allRxns=unique([model.rxns(allRxns);model.rxns(rxnIdx)]);
+0027 elseif isnumeric(rxns) || islogical(rxns)
+0028     allRxns=unique([allRxns;rxnIdx]);
+0029     if islogical(rxns)
+0030         temp=false(numel(model.rxns),1);
+0031         temp(allRxns)=true;
+0032         allRxns=temp;
+0033     end
+0034 end
+0035 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/getAllSubGraphs.html b/doc/core/getAllSubGraphs.html new file mode 100644 index 000000000..80fa5200e --- /dev/null +++ b/doc/core/getAllSubGraphs.html @@ -0,0 +1,120 @@ + + + + Description of getAllSubGraphs + + + + + + + + + +
Home > core > getAllSubGraphs.m
+ + + +

getAllSubGraphs +

+ +

PURPOSE ^

+
getAllSubGraphs
+ +

SYNOPSIS ^

+
function subGraphs=getAllSubGraphs(model)
+ +

DESCRIPTION ^

+
 getAllSubGraphs
+   Get all metabolic subgraphs in a model. Two metabolites 
+   are connected if they share a reaction.
+
+   Input:
+   model         a model structure
+
+   Output:
+   subGraphs     a boolean matrix where the rows correspond to the metabolites
+                 and the columns to which subgraph they are assigned to. The
+                 columns are ordered so that larger subgraphs come first
+
+ Usage: subGraphs=getAllSubGraphs(model)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function subGraphs=getAllSubGraphs(model)
+0002 % getAllSubGraphs
+0003 %   Get all metabolic subgraphs in a model. Two metabolites
+0004 %   are connected if they share a reaction.
+0005 %
+0006 %   Input:
+0007 %   model         a model structure
+0008 %
+0009 %   Output:
+0010 %   subGraphs     a boolean matrix where the rows correspond to the metabolites
+0011 %                 and the columns to which subgraph they are assigned to. The
+0012 %                 columns are ordered so that larger subgraphs come first
+0013 %
+0014 % Usage: subGraphs=getAllSubGraphs(model)
+0015 
+0016 %Generate the connectivity graph. Metabolites are connected through
+0017 %reactions. This is not a bipartite graph with the reactions.
+0018 G=model.S*model.S';
+0019 G(G~=0)=1;
+0020 
+0021 %Keeps track of which mets have been assigned to a subgraph
+0022 isAssigned=false(numel(model.mets),1);
+0023 
+0024 %Allocate space for subgraphs, initially one graph for each met
+0025 subGraphs=false(numel(model.mets),numel(model.mets));
+0026 
+0027 %Main loop continues until all mets have been assigned to a subgraph
+0028 counter=1;
+0029 while ~all(isAssigned)
+0030     currentSG=false(numel(model.mets),1);
+0031     %Find the first non-assigned metabolite and assign it to the current SG
+0032     I=find(isAssigned==false,1);
+0033     currentSG(I)=true;
+0034     isAssigned(I)=true;
+0035     %Then iteratively add all mets that are connected to each other, until
+0036     %no more such mets can be found
+0037     while true
+0038         J=sum(G(:,currentSG),2);
+0039         
+0040         %Get the new mets for this SG. Also assign them to the current SG
+0041         newOnes=J~=0 & currentSG==false;
+0042         isAssigned(newOnes)=true;
+0043         currentSG(newOnes)=true;
+0044         
+0045         %If there are no new mets, then abort
+0046         if ~any(newOnes)
+0047             subGraphs(currentSG,counter)=true;
+0048             counter=counter+1;
+0049             break;
+0050         end
+0051     end
+0052 end
+0053 subGraphs=subGraphs(:,1:counter);
+0054 
+0055 [~, I]=sort(sum(subGraphs),'descend');
+0056 
+0057 subGraphs=subGraphs(:,I);
+0058 
+0059 %Also remove empty subgraphs (can happen when metabolites are never used)
+0060 subGraphs(:,sum(subGraphs)==0)=[];
+0061 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/getAllowedBounds.html b/doc/core/getAllowedBounds.html new file mode 100644 index 000000000..ec6855e91 --- /dev/null +++ b/doc/core/getAllowedBounds.html @@ -0,0 +1,146 @@ + + + + Description of getAllowedBounds + + + + + + + + + +
Home > core > getAllowedBounds.m
+ + + +

getAllowedBounds +

+ +

PURPOSE ^

+
getAllowedBounds
+ +

SYNOPSIS ^

+
function [minFluxes, maxFluxes, exitFlags]=getAllowedBounds(model,rxns,runParallel)
+ +

DESCRIPTION ^

+
 getAllowedBounds
+   Returns the minimal and maximal fluxes through each reaction.
+
+ Input:
+   model           a model structure
+   rxns            either a cell array of reaction IDs, a logical vector
+                   with the same number of elements as reactions in the
+                   model, or a vector of reaction indexes (optional, default
+                   model.rxns)
+   runParallel     speed up calculations by parallel processing. This is
+                   not beneficial if allowed bounds are calculated for
+                   only a few reactions, as the overhead of parallel
+                   processing will take longer. It requires MATLAB
+                   Parallel Computing Toolbox. If this is not installed,
+                   the calculations will not be parallelized, regardless
+                   what is indicated as runParallel. (optional, default true)
+
+ Output:
+   minFluxes       minimal allowed fluxes
+   maxFluxes       maximal allowed fluxes
+   exitFlags       exit flags for min/max for each of the reactions. True
+                   if it was possible to calculate a flux
+
+ In cases where no solution can be calculated, NaN is returned.
+
+ Usage: [minFluxes, maxFluxes, exitFlags] = getAllowedBounds(model, rxns, runParallel)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function [minFluxes, maxFluxes, exitFlags]=getAllowedBounds(model,rxns,runParallel)
+0002 % getAllowedBounds
+0003 %   Returns the minimal and maximal fluxes through each reaction.
+0004 %
+0005 % Input:
+0006 %   model           a model structure
+0007 %   rxns            either a cell array of reaction IDs, a logical vector
+0008 %                   with the same number of elements as reactions in the
+0009 %                   model, or a vector of reaction indexes (optional, default
+0010 %                   model.rxns)
+0011 %   runParallel     speed up calculations by parallel processing. This is
+0012 %                   not beneficial if allowed bounds are calculated for
+0013 %                   only a few reactions, as the overhead of parallel
+0014 %                   processing will take longer. It requires MATLAB
+0015 %                   Parallel Computing Toolbox. If this is not installed,
+0016 %                   the calculations will not be parallelized, regardless
+0017 %                   what is indicated as runParallel. (optional, default true)
+0018 %
+0019 % Output:
+0020 %   minFluxes       minimal allowed fluxes
+0021 %   maxFluxes       maximal allowed fluxes
+0022 %   exitFlags       exit flags for min/max for each of the reactions. True
+0023 %                   if it was possible to calculate a flux
+0024 %
+0025 % In cases where no solution can be calculated, NaN is returned.
+0026 %
+0027 % Usage: [minFluxes, maxFluxes, exitFlags] = getAllowedBounds(model, rxns, runParallel)
+0028 
+0029 if nargin<2 || isempty(rxns)
+0030     rxns = 1:numel(model.rxns);
+0031 elseif ~islogical(rxns) && ~isnumeric(rxns)
+0032     rxns = convertCharArray(rxns);
+0033     rxns = getIndexes(model,rxns, 'rxns');
+0034 end
+0035 if nargin<3
+0036     runParallel = true;
+0037 end
+0038 
+0039 [ps, oldPoolAutoCreateSetting] = parallelPoolRAVEN(runParallel);
+0040 
+0041 minFluxes = zeros(numel(rxns),1);
+0042 maxFluxes = zeros(numel(rxns),1);
+0043 exitFlags = zeros(numel(rxns),2);
+0044 c = zeros(numel(model.rxns),1);
+0045 
+0046 PB = ProgressBar2(numel(rxns),'Running getAllowedBounds','cli');
+0047 parfor i = 1:numel(rxns)
+0048     count(PB)
+0049     tmpModel = model;
+0050     tmpModel.c = c;
+0051 
+0052     % Get maximal flux
+0053     tmpModel.c(rxns(i)) = 1;
+0054     [solMax,hsSol]=solveLP(tmpModel);
+0055     if ~isempty(solMax.f)
+0056         maxFluxes(i) = solMax.x(rxns(i));
+0057     else
+0058         maxFluxes(i) = NaN;
+0059     end
+0060 
+0061     % Get minimal flux
+0062     tmpModel.c(rxns(i)) = -1;
+0063     solMin = solveLP(tmpModel,[],[],hsSol);
+0064     if ~isempty(solMin.f)
+0065         minFluxes(i) = solMin.x(rxns(i));
+0066     else
+0067         minFluxes(i) = NaN;
+0068     end
+0069     exitFlags(i,:) = [solMin.stat solMax.stat];
+0070 
+0071 end
+0072 % Reset original Parallel setting
+0073 ps.Pool.AutoCreate = oldPoolAutoCreateSetting;
+0074 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/getElementalBalance.html b/doc/core/getElementalBalance.html new file mode 100644 index 000000000..3aea2d38c --- /dev/null +++ b/doc/core/getElementalBalance.html @@ -0,0 +1,215 @@ + + + + Description of getElementalBalance + + + + + + + + + +
Home > core > getElementalBalance.m
+ + + +

getElementalBalance +

+ +

PURPOSE ^

+
getElementalBalance
+ +

SYNOPSIS ^

+
function balanceStructure=getElementalBalance(model,rxns,printUnbalanced,printUnparsable)
+ +

DESCRIPTION ^

+
 getElementalBalance
+   Checks a model to see if the reactions are elementally balanced
+
+   model             a model structure
+   rxns              either a cell array of reaction IDs, a logical vector
+                     with the same number of elements as reactions in the model,
+                     of a vector of indexes. Only these reactions will be
+                     checked (optional, default model.rxns)
+   printUnbalanced   print warnings about the reactions that were
+                     unbalanced (optional, default false)
+   printUnparsable   print warnings about the reactions that cannot be
+                     parsed (optional, default false)
+
+   balanceStructure
+       balanceStatus   1 if the reaction is balanced, 0 if it's unbalanced,
+                      -1 if it couldn't be balanced due to missing information,
+                      -2 if it couldn't be balanced due to an error
+       elements
+           abbrevs     cell array with abbreviations for all used elements
+           names       cell array with the names for all used elements
+       leftComp        MxN matrix with the sum of coefficients for each of
+                       the elements (N) for the left side of the
+                       reactions (M)
+       rightComp       the corresponding matrix for the right side
+
+ Usage: balanceStructure=getElementalBalance(model,rxns,printUnbalanced,printUnparsable)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function balanceStructure=getElementalBalance(model,rxns,printUnbalanced,printUnparsable)
+0002 % getElementalBalance
+0003 %   Checks a model to see if the reactions are elementally balanced
+0004 %
+0005 %   model             a model structure
+0006 %   rxns              either a cell array of reaction IDs, a logical vector
+0007 %                     with the same number of elements as reactions in the model,
+0008 %                     of a vector of indexes. Only these reactions will be
+0009 %                     checked (optional, default model.rxns)
+0010 %   printUnbalanced   print warnings about the reactions that were
+0011 %                     unbalanced (optional, default false)
+0012 %   printUnparsable   print warnings about the reactions that cannot be
+0013 %                     parsed (optional, default false)
+0014 %
+0015 %   balanceStructure
+0016 %       balanceStatus   1 if the reaction is balanced, 0 if it's unbalanced,
+0017 %                      -1 if it couldn't be balanced due to missing information,
+0018 %                      -2 if it couldn't be balanced due to an error
+0019 %       elements
+0020 %           abbrevs     cell array with abbreviations for all used elements
+0021 %           names       cell array with the names for all used elements
+0022 %       leftComp        MxN matrix with the sum of coefficients for each of
+0023 %                       the elements (N) for the left side of the
+0024 %                       reactions (M)
+0025 %       rightComp       the corresponding matrix for the right side
+0026 %
+0027 % Usage: balanceStructure=getElementalBalance(model,rxns,printUnbalanced,printUnparsable)
+0028 
+0029 if nargin<2
+0030     rxns=[];
+0031 elseif ~islogical(rxns) && ~isnumeric(rxns)
+0032     rxns=convertCharArray(rxns);
+0033 end
+0034 
+0035 if nargin<3
+0036     printUnbalanced=false;
+0037 end
+0038 
+0039 if nargin<4
+0040     printUnparsable=false;
+0041 end
+0042 
+0043 if ~isempty(rxns)
+0044     indexes=~getIndexes(model,rxns,'rxns',true);
+0045     model=removeReactions(model,indexes,true);
+0046 end
+0047 
+0048 balanceStructure.balanceStatus=nan(numel(model.rxns),1);
+0049 
+0050 %Get the formulas
+0051 if isfield(model,'metFormulas')
+0052     [balanceStructure.elements, useMat, exitFlag]=parseFormulas(model.metFormulas, true);
+0053 else
+0054     if isfield(model,'inchis')
+0055         [balanceStructure.elements, useMat, exitFlag]=parseFormulas(model.inchis, true,true);
+0056     else
+0057         EM='The model must contain either the "metFormulas" or the "inchis" field in order to test for elemental balancing';
+0058         dispEM(EM);
+0059     end
+0060 end
+0061 
+0062 balanceStructure.leftComp=zeros(numel(model.rxns),numel(balanceStructure.elements.names));
+0063 balanceStructure.rightComp=balanceStructure.leftComp;
+0064 
+0065 %Look at the right and left side of the reactions separately
+0066 S{1}=model.S;
+0067 S{2}=model.S;
+0068 S{1}(S{1}>0)=0; %Left side
+0069 S{2}(S{2}<0)=0; %Right side
+0070 S{1}=abs(S{1}); %Both should have positive values
+0071 
+0072 %First do it for left side and then for right
+0073 for i=1:2
+0074     for j=1:numel(model.rxns)
+0075         %Get the balance status of the involved mets
+0076         I=exitFlag(S{i}(:,j)~=0);
+0077         if any(I==-1)
+0078             balanceStructure.balanceStatus(j)=-2;
+0079         end
+0080         if any(I==0)
+0081             %Don't change a more serious error to a less serious one
+0082             balanceStructure.balanceStatus(j)=min(-1,balanceStructure.balanceStatus(j));
+0083         end
+0084         %Loop through each element
+0085         for k=1:numel(balanceStructure.elements.names)
+0086             if i==1
+0087                 balanceStructure.leftComp(j,k)=sum(S{i}(:,j).*useMat(:,k));
+0088             else
+0089                 balanceStructure.rightComp(j,k)=sum(S{i}(:,j).*useMat(:,k));
+0090             end
+0091         end
+0092     end
+0093 end
+0094 
+0095 %Now compare the left and right sides to find which are unbalanced. This is
+0096 %done even if the reaction as a whole couldn't be balanced
+0097 total=abs(balanceStructure.rightComp-balanceStructure.leftComp)>10^-8; %To deal with roundoff error
+0098 
+0099 %Get which reactions are unbalanced. Don't change an error to just
+0100 %unbalanced
+0101 balanceStructure.balanceStatus(any(total,2))=min(balanceStructure.balanceStatus(any(total,2)),0);
+0102 
+0103 %The remaining ones are all balanced
+0104 balanceStructure.balanceStatus(isnan(balanceStructure.balanceStatus))=1;
+0105 
+0106 %Print warnings
+0107 toPrint=[];
+0108 if printUnbalanced==true
+0109     toPrint=[toPrint;find(balanceStructure.balanceStatus==0)];
+0110 end
+0111 if printUnparsable==true
+0112     toPrint=[toPrint;find(balanceStructure.balanceStatus<0)];
+0113 end
+0114 
+0115 toPrint=sort(toPrint);
+0116 for i=1:numel(toPrint)
+0117     if balanceStructure.balanceStatus(toPrint(i))<0
+0118         if balanceStructure.balanceStatus(toPrint(i))==-1
+0119             EM=['The reaction ' model.rxns{toPrint(i)} ' could not be balanced due to missing information'];
+0120             dispEM(EM,false);
+0121         else
+0122             EM=['The reaction ' model.rxns{toPrint(i)} ' could not be balanced due to a parsing error'];
+0123             dispEM(EM,false);
+0124         end
+0125     else
+0126         %Find the compounds that it's not balanced for
+0127         notBalanced=find(total(toPrint(i),:));
+0128         for j=1:numel(notBalanced)
+0129             EM=['The reaction ' model.rxns{toPrint(i)} ' is not balanced with respect to ' balanceStructure.elements.names{notBalanced(j)}];
+0130             dispEM(EM,false);
+0131         end
+0132     end
+0133 end
+0134 
+0135 % Re-order the structure entries so they're consistent with the ordering of
+0136 % the input reaction indexes
+0137 if ~isempty(rxns)
+0138     rxns = getIndexes(model,rxns,'rxns');
+0139     [~,i] = sort(rxns);
+0140     balanceStructure.balanceStatus(i) = balanceStructure.balanceStatus;
+0141     balanceStructure.leftComp(i,:) = balanceStructure.leftComp;
+0142     balanceStructure.rightComp(i,:) = balanceStructure.rightComp;
+0143 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/getEssentialRxns.html b/doc/core/getEssentialRxns.html new file mode 100644 index 000000000..ba3ac4c96 --- /dev/null +++ b/doc/core/getEssentialRxns.html @@ -0,0 +1,126 @@ + + + + Description of getEssentialRxns + + + + + + + + + +
Home > core > getEssentialRxns.m
+ + + +

getEssentialRxns +

+ +

PURPOSE ^

+
getEssentialRxns
+ +

SYNOPSIS ^

+
function [essentialRxns, essentialRxnsIndexes]=getEssentialRxns(model,ignoreRxns)
+ +

DESCRIPTION ^

+
 getEssentialRxns
+   Calculate the essential reactions for a model to be solvable
+
+   model                   a model structure
+   ignoreRxns              cell array of reaction IDs which should not be
+                           checked (optional, default {})
+
+   essentialRxns           cell array with the IDs of the essential reactions
+   essentialRxnsIndexes    vector with the indexes of the essential reactions
+
+   Essential reactions are those which, when constrained to 0, result in an
+   infeasible problem.
+
+ Usage: [essentialRxns, essentialRxnsIndexes]=getEssentialRxns(model,ignoreRxns)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function [essentialRxns, essentialRxnsIndexes]=getEssentialRxns(model,ignoreRxns)
+0002 % getEssentialRxns
+0003 %   Calculate the essential reactions for a model to be solvable
+0004 %
+0005 %   model                   a model structure
+0006 %   ignoreRxns              cell array of reaction IDs which should not be
+0007 %                           checked (optional, default {})
+0008 %
+0009 %   essentialRxns           cell array with the IDs of the essential reactions
+0010 %   essentialRxnsIndexes    vector with the indexes of the essential reactions
+0011 %
+0012 %   Essential reactions are those which, when constrained to 0, result in an
+0013 %   infeasible problem.
+0014 %
+0015 % Usage: [essentialRxns, essentialRxnsIndexes]=getEssentialRxns(model,ignoreRxns)
+0016 
+0017 if nargin<2
+0018     ignoreRxns={};
+0019 else
+0020     ignoreRxns=convertCharArray(ignoreRxns);
+0021 end
+0022 
+0023 %Too make sure that it doesn't try to optimize for something
+0024 model.c=zeros(numel(model.rxns),1);
+0025 
+0026 %First check that the problem is solvable
+0027 [sol, hsSolOut]=solveLP(model,1);
+0028 
+0029 if sol.stat==-1 || isempty(sol.x)
+0030     EM='No feasible solution to the full model';
+0031     dispEM(EM);
+0032 end
+0033 
+0034 %Check which reactions have flux. Only those can be essential. This is not
+0035 %the smallest list of reactions, but it's a fast way
+0036 rxnsToCheck=setdiff(model.rxns(abs(sol.x)>10^-12),ignoreRxns);
+0037 nToCheck=numel(rxnsToCheck);
+0038 minimize=true;
+0039 while 1
+0040     if minimize==true
+0041         sol=solveLP(setParam(model,'obj',rxnsToCheck,-1));
+0042     else
+0043         sol=solveLP(setParam(model,'obj',rxnsToCheck,1));
+0044     end
+0045     rxnsToCheck=intersect(rxnsToCheck,model.rxns(abs(sol.x)>10^-8));
+0046     if numel(rxnsToCheck)>=nToCheck
+0047         if minimize==true
+0048             minimize=false;
+0049         else
+0050             break;
+0051         end
+0052     else
+0053         nToCheck=numel(rxnsToCheck);
+0054     end
+0055 end
+0056 
+0057 essentialRxns={};
+0058 for i=1:numel(rxnsToCheck)
+0059     sol=solveLP(setParam(model,'eq',rxnsToCheck(i),0),0,[],hsSolOut);
+0060     if sol.stat==-1 || isempty(sol.x)
+0061         essentialRxns=[essentialRxns;rxnsToCheck(i)];
+0062     end
+0063 end
+0064 
+0065 [~, essentialRxnsIndexes]=ismember(essentialRxns,model.rxns);
+0066 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/getExchangeRxns.html b/doc/core/getExchangeRxns.html new file mode 100644 index 000000000..09e722abe --- /dev/null +++ b/doc/core/getExchangeRxns.html @@ -0,0 +1,170 @@ + + + + Description of getExchangeRxns + + + + + + + + + +
Home > core > getExchangeRxns.m
+ + + +

getExchangeRxns +

+ +

PURPOSE ^

+
getExchangeRxns
+ +

SYNOPSIS ^

+
function [exchangeRxns, exchangeRxnsIndexes]=getExchangeRxns(model,reactionType)
+ +

DESCRIPTION ^

+
 getExchangeRxns
+   Retrieves the exchange reactions from a model. Exchange reactions are
+   identified by having either no substrates or products.
+
+ Input:
+   model               a model structure
+   reactionType        which exchange reactions should be returned
+                       'all'     all reactions, irrespective of reaction
+                                 bounds
+                       'uptake'  reactions with bounds that imply that
+                                 only uptake are allowed. Reaction
+                                 direction, upper and lower bounds are
+                                 all considered
+                       'excrete' reactions with bounds that imply that
+                                 only excretion are allowed. Reaction
+                                 direction, upper and lower bounds are
+                                 all considered
+                       'reverse' reactions with non-zero upper and lower
+                                 bounds that imply that both uptake and
+                                 excretion are allowed
+                       'blocked' reactions that have zero upper and lower
+                                 bounds, not allowing any flux
+                       'in'      reactions where the boundary metabolite
+                                 is the substrate of the reaction, a
+                                 positive flux value would imply uptake,
+                                 but reaction bounds are not considered
+                       'out'     reactions where the boundary metabolite
+                                 is the product of the reaction, a
+                                 negative flux value would imply uptake,
+                                 but reaction bounds are not considered.
+
+ Output:
+   exchangeRxns        cell array with the IDs of the exchange reactions
+   exchangeRxnsIndexes vector with the indexes of the exchange reactions
+
+ Note:
+   The union of 'in' and 'out' equals 'all'. Also, the union of 'uptake',
+   'excrete', 'reverse' and 'blocked' equals all.
+
+ Usage: [exchangeRxns,exchangeRxnsIndexes]=getExchangeRxns(model,reactionType)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function [exchangeRxns, exchangeRxnsIndexes]=getExchangeRxns(model,reactionType)
+0002 % getExchangeRxns
+0003 %   Retrieves the exchange reactions from a model. Exchange reactions are
+0004 %   identified by having either no substrates or products.
+0005 %
+0006 % Input:
+0007 %   model               a model structure
+0008 %   reactionType        which exchange reactions should be returned
+0009 %                       'all'     all reactions, irrespective of reaction
+0010 %                                 bounds
+0011 %                       'uptake'  reactions with bounds that imply that
+0012 %                                 only uptake are allowed. Reaction
+0013 %                                 direction, upper and lower bounds are
+0014 %                                 all considered
+0015 %                       'excrete' reactions with bounds that imply that
+0016 %                                 only excretion are allowed. Reaction
+0017 %                                 direction, upper and lower bounds are
+0018 %                                 all considered
+0019 %                       'reverse' reactions with non-zero upper and lower
+0020 %                                 bounds that imply that both uptake and
+0021 %                                 excretion are allowed
+0022 %                       'blocked' reactions that have zero upper and lower
+0023 %                                 bounds, not allowing any flux
+0024 %                       'in'      reactions where the boundary metabolite
+0025 %                                 is the substrate of the reaction, a
+0026 %                                 positive flux value would imply uptake,
+0027 %                                 but reaction bounds are not considered
+0028 %                       'out'     reactions where the boundary metabolite
+0029 %                                 is the product of the reaction, a
+0030 %                                 negative flux value would imply uptake,
+0031 %                                 but reaction bounds are not considered.
+0032 %
+0033 % Output:
+0034 %   exchangeRxns        cell array with the IDs of the exchange reactions
+0035 %   exchangeRxnsIndexes vector with the indexes of the exchange reactions
+0036 %
+0037 % Note:
+0038 %   The union of 'in' and 'out' equals 'all'. Also, the union of 'uptake',
+0039 %   'excrete', 'reverse' and 'blocked' equals all.
+0040 %
+0041 % Usage: [exchangeRxns,exchangeRxnsIndexes]=getExchangeRxns(model,reactionType)
+0042 
+0043 if nargin<2
+0044     reactionType='all';
+0045 else
+0046     reactionType=char(reactionType);
+0047 end
+0048 
+0049 % Find exchange reactions
+0050 if isfield(model, 'unconstrained')
+0051     [~, I]=find(model.S(model.unconstrained~=0,:)>0);
+0052     hasNoProd(I)=true;
+0053     [~, I]=find(model.S(model.unconstrained~=0,:)<0);
+0054     hasNoSubs(I)=true;
+0055 else
+0056     hasNoProd = transpose(find(sum(model.S>0)==0));
+0057     hasNoSubs = transpose(find(sum(model.S<0)==0));
+0058 end
+0059 allExch   = [hasNoProd; hasNoSubs];
+0060 
+0061 switch reactionType
+0062     case {'both','all'} % For legacy reasons, 'both' is also allowed
+0063         exchangeRxnsIndexes = allExch;
+0064     case 'in'
+0065         exchangeRxnsIndexes = hasNoSubs;
+0066     case 'out'
+0067         exchangeRxnsIndexes = hasNoProd;
+0068     case 'blocked'
+0069         exchangeRxnsIndexes = allExch(model.lb(allExch) == 0 & model.ub(allExch) == 0);
+0070     case 'reverse'
+0071         exchangeRxnsIndexes = allExch(model.lb(allExch) < 0 & model.ub(allExch) > 0);
+0072     case 'uptake'
+0073         
+0074         exchangeRxnsIndexes = allExch([(model.lb(hasNoProd) < 0 & model.ub(hasNoProd) <= 0); ...
+0075                               (model.lb(hasNoSubs) >= 0 & model.ub(hasNoSubs) > 0)]);
+0076     case 'excrete'
+0077         exchangeRxnsIndexes = allExch([(model.lb(hasNoProd) >= 0 & model.ub(hasNoProd) > 0); ...
+0078                               (model.lb(hasNoSubs) < 0 & model.ub(hasNoSubs) <= 0)]);
+0079     otherwise
+0080         error('Invalid reactionType specified')
+0081 end
+0082 exchangeRxnsIndexes = sort(exchangeRxnsIndexes);
+0083 exchangeRxns = model.rxns(exchangeRxnsIndexes);
+0084 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/getExpressionStructure.html b/doc/core/getExpressionStructure.html new file mode 100644 index 000000000..2074991b2 --- /dev/null +++ b/doc/core/getExpressionStructure.html @@ -0,0 +1,180 @@ + + + + Description of getExpressionStructure + + + + + + + + + +
Home > core > getExpressionStructure.m
+ + + +

getExpressionStructure +

+ +

PURPOSE ^

+
getExpressionStructure
+ +

SYNOPSIS ^

+
function experiment=getExpressionStructure(fileName)
+ +

DESCRIPTION ^

+
 getExpressionStructure
+   Loads a representation of an experiment from an Excel file (see
+   comments further down)
+
+   fileName            an Excel representation on an experiment
+
+   experiment          an experiment structure
+       data            matrix with expression values
+       orfs            the corresponding ORFs
+       experiments     the titles of the experiments
+       boundNames      reaction names for the bounds
+       upperBoundaries matrix with the upper bound values
+       fitNames        reaction names for the measured fluxes
+       fitTo           matrix with the measured fluxes
+
+   A very common data set when working with genome-scale metabolic models
+   is that you have measured fermentation data, gene expression data,
+   and some different 'bounds' (for example different carbon sources
+   or genes that are knocked out) in a number of conditions. This function
+   reads an Excel representation of such an experiment.
+   The Excel file must contain three sheets, 'EXPRESSION', 'BOUNDS',
+   'FITTING'. Below are some examples to show how they should be
+   formatted:
+
+   -EXPRESSION
+       ORF    dsm_paa    wisc_paa
+       Pc00e00030    79.80942723    78.14755338
+   Shows the expression of the gene Pc00e00030 under two different
+   conditions (in this case a DSM strain and a Wisconsin strain of P.
+   chrysogenum with PSS in the media)
+
+   -BOUNDS
+       Fixed Upper    dsm_paa    wisc_paa
+       paaIN    0.1    0.2
+   The upper bound for the reaction paaIN should be 0.1 for the first
+   condition and 0.2 for the second
+
+   -FITTING
+       Fit to    dsm_paa    wisc_paa
+       co2OUT    2.85    3.05
+       glcIN   1.2     0.9
+   The measured fluxes for CO2 production and glucose uptake for the two
+   conditions. The model(s) can later be fitted to match these values as
+   good as possible.
+
+ Usage: experiment=getExpressionStructure(fileName)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function experiment=getExpressionStructure(fileName)
+0002 % getExpressionStructure
+0003 %   Loads a representation of an experiment from an Excel file (see
+0004 %   comments further down)
+0005 %
+0006 %   fileName            an Excel representation on an experiment
+0007 %
+0008 %   experiment          an experiment structure
+0009 %       data            matrix with expression values
+0010 %       orfs            the corresponding ORFs
+0011 %       experiments     the titles of the experiments
+0012 %       boundNames      reaction names for the bounds
+0013 %       upperBoundaries matrix with the upper bound values
+0014 %       fitNames        reaction names for the measured fluxes
+0015 %       fitTo           matrix with the measured fluxes
+0016 %
+0017 %   A very common data set when working with genome-scale metabolic models
+0018 %   is that you have measured fermentation data, gene expression data,
+0019 %   and some different 'bounds' (for example different carbon sources
+0020 %   or genes that are knocked out) in a number of conditions. This function
+0021 %   reads an Excel representation of such an experiment.
+0022 %   The Excel file must contain three sheets, 'EXPRESSION', 'BOUNDS',
+0023 %   'FITTING'. Below are some examples to show how they should be
+0024 %   formatted:
+0025 %
+0026 %   -EXPRESSION
+0027 %       ORF    dsm_paa    wisc_paa
+0028 %       Pc00e00030    79.80942723    78.14755338
+0029 %   Shows the expression of the gene Pc00e00030 under two different
+0030 %   conditions (in this case a DSM strain and a Wisconsin strain of P.
+0031 %   chrysogenum with PSS in the media)
+0032 %
+0033 %   -BOUNDS
+0034 %       Fixed Upper    dsm_paa    wisc_paa
+0035 %       paaIN    0.1    0.2
+0036 %   The upper bound for the reaction paaIN should be 0.1 for the first
+0037 %   condition and 0.2 for the second
+0038 %
+0039 %   -FITTING
+0040 %       Fit to    dsm_paa    wisc_paa
+0041 %       co2OUT    2.85    3.05
+0042 %       glcIN   1.2     0.9
+0043 %   The measured fluxes for CO2 production and glucose uptake for the two
+0044 %   conditions. The model(s) can later be fitted to match these values as
+0045 %   good as possible.
+0046 %
+0047 % Usage: experiment=getExpressionStructure(fileName)
+0048 
+0049 [type, sheets]=xlsfinfo(fileName);
+0050 
+0051 %Check if the file is a Microsoft Excel Spreadsheet
+0052 if ~strcmp(type,'Microsoft Excel Spreadsheet')
+0053     EM='The file is not a Microsoft Excel Spreadsheet';
+0054     dispEM(EM);
+0055 end
+0056 
+0057 %Check that all sheets are present and saves the index of each
+0058 exprSheet=find(strcmp('EXPRESSION', sheets));
+0059 boundSheet=find(strcmp('BOUNDS', sheets));
+0060 fitSheet=find(strcmp('FITTING', sheets));
+0061 
+0062 if length(exprSheet)~=1 || length(boundSheet)~=1 || length(fitSheet)~=1
+0063     EM='Not all required spreadsheets are present in the file';
+0064     dispEM(EM);
+0065 end
+0066 
+0067 %Load the expression data
+0068 [discard,dataSheet]=xlsread(fileName,exprSheet);
+0069 experiment.data=discard;
+0070 experiment.orfs=dataSheet(2:size(dataSheet,1),1);
+0071 experiment.experiments=dataSheet(1,2:size(dataSheet,2));
+0072 
+0073 %Loads the maximal boundaries
+0074 [discard,dataSheet]=xlsread(fileName,boundSheet);
+0075 experiment.boundNames=dataSheet(2:size(dataSheet,1),1);
+0076 experiment.upperBoundaries=discard;
+0077 
+0078 %Loads the experimental data to fit to
+0079 [discard,dataSheet]=xlsread(fileName,fitSheet);
+0080 experiment.fitNames=dataSheet(2:size(dataSheet,1),1);
+0081 experiment.fitTo=discard;
+0082 
+0083 %Check to see that the dimensions are correct
+0084 if length(experiment.orfs)~=size(experiment.data,1) || (length(experiment.experiments)~=size(experiment.data,2) && ~isempty(experiment.data))
+0085     EM='The expression data does not seem to be formated in the expected manner';
+0086     dispEM(EM);
+0087 end
+0088 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/getFluxZ.html b/doc/core/getFluxZ.html new file mode 100644 index 000000000..066e68497 --- /dev/null +++ b/doc/core/getFluxZ.html @@ -0,0 +1,120 @@ + + + + Description of getFluxZ + + + + + + + + + +
Home > core > getFluxZ.m
+ + + +

getFluxZ +

+ +

PURPOSE ^

+
getFluxZ
+ +

SYNOPSIS ^

+
function Z=getFluxZ(solutionsA, solutionsB)
+ +

DESCRIPTION ^

+
 getFluxZ
+   Calculates the Z scores between two sets of random flux distributions.
+
+   solutionsA      random solutions for the reference condition (as
+                   generated by randomSampling)
+   solutionsB      random solutions for the test condition (as generated
+                   by randomSampling)
+
+   Z               a vector with Z-scores that tells you for each reaction
+                   how likely it is for its flux to have increased (positive sign)
+                   or decreased (negative sign) in the second condition with
+                   respect to the first.
+
+ Usage: Z=getFluxZ(solutionsA, solutionsB)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function Z=getFluxZ(solutionsA, solutionsB)
+0002 % getFluxZ
+0003 %   Calculates the Z scores between two sets of random flux distributions.
+0004 %
+0005 %   solutionsA      random solutions for the reference condition (as
+0006 %                   generated by randomSampling)
+0007 %   solutionsB      random solutions for the test condition (as generated
+0008 %                   by randomSampling)
+0009 %
+0010 %   Z               a vector with Z-scores that tells you for each reaction
+0011 %                   how likely it is for its flux to have increased (positive sign)
+0012 %                   or decreased (negative sign) in the second condition with
+0013 %                   respect to the first.
+0014 %
+0015 % Usage: Z=getFluxZ(solutionsA, solutionsB)
+0016 
+0017 nRxns=size(solutionsA,1);
+0018 
+0019 %Check that the number of reactions is the same in both cases
+0020 if nRxns~=size(solutionsB,1)
+0021     EM='The number of reactions must be the same in solutionsA as in solutionsB';
+0022     dispEM(EM);
+0023 end
+0024 
+0025 Z=zeros(nRxns,1);
+0026 
+0027 %Calculate the mean and standard deviation for the two cases
+0028 mA=mean(solutionsA,2);
+0029 mB=mean(solutionsB,2);
+0030 
+0031 %This can lead to OUT OF MEMORY, so do it in segments of 500 reactions
+0032 varA=zeros(size(solutionsA,1),1);
+0033 for i=1:500:size(solutionsA,1)
+0034     varA(i:min(i+499,size(solutionsA,1)))=var(solutionsA(i:min(i+499,size(solutionsA,1)),:),0,2);
+0035 end
+0036 varB=zeros(size(solutionsB,1),1);
+0037 for i=1:500:size(solutionsB,1)
+0038     varB(i:min(i+499,size(solutionsB,1)))=var(solutionsB(i:min(i+499,size(solutionsB,1)),:),0,2);
+0039 end
+0040 
+0041 %If the mean of both solutions are the same then the Z-score is zero
+0042 toCheck=mA~=mB;
+0043 
+0044 %If the variance is zero in both cases, then put a very large or very small
+0045 %Z-score for the corresponding reactions
+0046 I=find(varA==0 & varB==0 & toCheck==true);
+0047 toCheck(I)=false;
+0048 J=mA(I)>mB(I);
+0049 Z(I(J))=100;
+0050 Z(I(~J))=-100;
+0051 toCheck=find(toCheck);
+0052 
+0053 for i=1:numel(toCheck)
+0054     Z(toCheck(i))=(mB(toCheck(i))-mA(toCheck(i)))/sqrt(varA(toCheck(i))+varB(toCheck(i)));
+0055 end
+0056 
+0057 %Shrink very large values
+0058 Z=min(Z,100);
+0059 Z=max(Z,-100);
+0060 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/getGenesFromGrRules.html b/doc/core/getGenesFromGrRules.html new file mode 100644 index 000000000..011069b86 --- /dev/null +++ b/doc/core/getGenesFromGrRules.html @@ -0,0 +1,141 @@ + + + + Description of getGenesFromGrRules + + + + + + + + + +
Home > core > getGenesFromGrRules.m
+ + + +

getGenesFromGrRules +

+ +

PURPOSE ^

+
getGenesFromGrRules Extract gene list and rxnGeneMat from grRules array.
+ +

SYNOPSIS ^

+
function [genes,rxnGeneMat] = getGenesFromGrRules(grRules, originalGenes)
+ +

DESCRIPTION ^

+
getGenesFromGrRules  Extract gene list and rxnGeneMat from grRules array.
+
+ USAGE:
+
+   [genes,rxnGeneMat] = getGenesFromGrRules(grRules, originalGenes);
+
+ INPUTS:
+
+   grRules     A cell array of model grRules, from which a list of genes
+               are to be extracted.
+               NOTE: Boolean operators can be text ("and", "or") or
+                     symbolic ("&", "|"), but there must be a space
+                     between operators and gene names/IDs.
+   originalGenes     The original gene list from the model as reference
+
+ OUTPUTS:
+
+   genes       A unique list of all gene IDs that appear in grRules.
+
+   rxnGeneMat  (Optional) A binary matrix indicating which genes
+               participate in each reaction, where rows correspond to
+               reactions (entries in grRules) and columns correspond to
+               genes.
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function [genes,rxnGeneMat] = getGenesFromGrRules(grRules, originalGenes)
+0002 %getGenesFromGrRules  Extract gene list and rxnGeneMat from grRules array.
+0003 %
+0004 % USAGE:
+0005 %
+0006 %   [genes,rxnGeneMat] = getGenesFromGrRules(grRules, originalGenes);
+0007 %
+0008 % INPUTS:
+0009 %
+0010 %   grRules     A cell array of model grRules, from which a list of genes
+0011 %               are to be extracted.
+0012 %               NOTE: Boolean operators can be text ("and", "or") or
+0013 %                     symbolic ("&", "|"), but there must be a space
+0014 %                     between operators and gene names/IDs.
+0015 %   originalGenes     The original gene list from the model as reference
+0016 %
+0017 % OUTPUTS:
+0018 %
+0019 %   genes       A unique list of all gene IDs that appear in grRules.
+0020 %
+0021 %   rxnGeneMat  (Optional) A binary matrix indicating which genes
+0022 %               participate in each reaction, where rows correspond to
+0023 %               reactions (entries in grRules) and columns correspond to
+0024 %               genes.
+0025 %
+0026 
+0027 
+0028 % handle input arguments
+0029 if nargin < 2
+0030     originalGenes = [];
+0031 end
+0032 
+0033 % check if the grRules use written or symbolic boolean operators
+0034 if any(contains(grRules,{' & ',' | '}))
+0035     % fix some potential missing spaces between parentheses and &/|
+0036     grRules = regexprep(grRules,'\)&',') &');   % ")&"  ->  ") &"
+0037     grRules = regexprep(grRules,'&\(','& (');   % "&("  ->  "& ("
+0038     grRules = regexprep(grRules,'\)\|',') |');  % ")|"  ->  ") |"
+0039     grRules = regexprep(grRules,'\|\(','| (');  % "|("  ->  "| ("
+0040 else
+0041     % fix some potential missing spaces between parentheses and AND/OR
+0042     grRules = regexprep(grRules,'\)and',') and');  % ")and" ->  ") and"
+0043     grRules = regexprep(grRules,'and\(','and (');  % "and(" ->  "and ("
+0044     grRules = regexprep(grRules,'\)or',') or');    % ")or"  ->  ") or"
+0045     grRules = regexprep(grRules,'or\(','or (');    % "or("  ->  "or ("
+0046     
+0047     % convert "and" to "&" and "or" to "|" (easier to work with symbols)
+0048     grRules = regexprep(grRules, ' or ', ' | ');
+0049     grRules = regexprep(grRules, ' and ', ' & ');
+0050 end
+0051 
+0052 % extract list of genes from each reaction
+0053 rxnGenes = cellfun(@(r) regexprep(unique(strsplit(r,{' | ',' & '})),'[\(\) ]+',''),grRules,'UniformOutput',false);
+0054 
+0055 % construct new gene list
+0056 nonEmpty = ~cellfun(@isempty,rxnGenes);
+0057 genes = unique(transpose([rxnGenes{nonEmpty}]));
+0058 genes(cellfun(@isempty,genes)) = [];
+0059 
+0060 if ~isempty(originalGenes)
+0061     if ~isequal(sort(originalGenes), sort(genes))
+0062         error('The grRules and original gene list are inconsistent!');
+0063     else
+0064         genes = originalGenes;
+0065     end
+0066 end
+0067 
+0068 % construct new rxnGeneMat (if requested)
+0069 if nargout > 1
+0070     rxnGeneCell = cellfun(@(rg) ismember(genes,rg),rxnGenes,'UniformOutput',false);
+0071     rxnGeneMat = sparse(double(horzcat(rxnGeneCell{:})'));
+0072 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/getIndexes.html b/doc/core/getIndexes.html new file mode 100644 index 000000000..ba86441e3 --- /dev/null +++ b/doc/core/getIndexes.html @@ -0,0 +1,201 @@ + + + + Description of getIndexes + + + + + + + + + +
Home > core > getIndexes.m
+ + + +

getIndexes +

+ +

PURPOSE ^

+
getIndexes
+ +

SYNOPSIS ^

+
function indexes=getIndexes(model, objects, type, returnLogical)
+ +

DESCRIPTION ^

+
 getIndexes
+   Retrieves the indexes for a list of reactions or metabolites
+
+ Input:
+   model           a model structure
+   objects         either a cell array of IDs, a logical vector with the
+                   same number of elements as metabolites in the model,
+                   of a vector of indexes
+   type            'rxns', 'mets', or 'genes' depending on what to retrieve
+                   'metnames' queries metabolite names, while 'metcomps'
+                   allows to provide specific metabolites and their
+                   compartments in the format metaboliteName[comp]. If a
+                   model.ec structure exists (GECKO 3), then also
+                   'ecenzymes', 'ecrxns' and 'ecgenes' are allowed
+   returnLogical   Sets whether to return a logical array or an array with
+                   the indexes (optional, default false)
+
+ Output:
+   indexes         can be a logical array or a double array depending on
+                   the value of returnLogical
+
+ Note: If 'ecenzymes', 'ecrxns' or 'ecgenes' are used with a GECKO 3
+ model, then the indexes are from the model.ec.enzymes, model.ec.rxns or
+ model.ec.genes fields, respectively.
+ 
+ Usage: indexes=getIndexes(model, objects, type, returnLogical)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function indexes=getIndexes(model, objects, type, returnLogical)
+0002 % getIndexes
+0003 %   Retrieves the indexes for a list of reactions or metabolites
+0004 %
+0005 % Input:
+0006 %   model           a model structure
+0007 %   objects         either a cell array of IDs, a logical vector with the
+0008 %                   same number of elements as metabolites in the model,
+0009 %                   of a vector of indexes
+0010 %   type            'rxns', 'mets', or 'genes' depending on what to retrieve
+0011 %                   'metnames' queries metabolite names, while 'metcomps'
+0012 %                   allows to provide specific metabolites and their
+0013 %                   compartments in the format metaboliteName[comp]. If a
+0014 %                   model.ec structure exists (GECKO 3), then also
+0015 %                   'ecenzymes', 'ecrxns' and 'ecgenes' are allowed
+0016 %   returnLogical   Sets whether to return a logical array or an array with
+0017 %                   the indexes (optional, default false)
+0018 %
+0019 % Output:
+0020 %   indexes         can be a logical array or a double array depending on
+0021 %                   the value of returnLogical
+0022 %
+0023 % Note: If 'ecenzymes', 'ecrxns' or 'ecgenes' are used with a GECKO 3
+0024 % model, then the indexes are from the model.ec.enzymes, model.ec.rxns or
+0025 % model.ec.genes fields, respectively.
+0026 %
+0027 % Usage: indexes=getIndexes(model, objects, type, returnLogical)
+0028 
+0029 if nargin<4
+0030     returnLogical=false;
+0031 end
+0032 
+0033 if ~islogical(objects) && ~isnumeric(objects)
+0034     objects=convertCharArray(objects);
+0035 end
+0036 type=char(type);
+0037 
+0038 indexes=[];
+0039 
+0040 switch type
+0041     case 'rxns'
+0042         searchIn=model.rxns;
+0043     case 'mets'
+0044         searchIn=model.mets;
+0045     case 'genes'
+0046         searchIn=model.genes;
+0047     case 'metnames'
+0048         searchIn=model.metNames;
+0049     case 'metcomps'
+0050         % If provided as metaboliteName[comp], then index search is quite
+0051         % different from general approach, and therefore coded separately.
+0052         mets=regexprep(objects,'(^.+)\[(.+)\]$','$1');
+0053         comps=regexprep(objects,'(^.+)\[(.+)\]$','$2');
+0054         indexes=zeros(1,numel(objects));
+0055         for i=1:numel(objects)
+0056             index=find(strcmp(mets(i),model.metNames));
+0057             index=index(strcmp(comps(i),model.comps(model.metComps(index))));
+0058             if ~isempty(index)
+0059                 indexes(i)=index;
+0060             else
+0061                 error(['Could not find object ' objects{i} ' in the model']);
+0062             end
+0063         end
+0064         indexes=indexes(:);
+0065         if returnLogical==true
+0066             tempIndexes=false(numel(model.mets),1);
+0067             tempIndexes(indexes)=true;
+0068             indexes=tempIndexes;
+0069         end
+0070         return %None of the remaining function needs to run if metcomps
+0071     case 'ecrxns'
+0072         if ~isfield(model,'ec')
+0073             error('Type %s cannot be used if no model.ec structure is present.',type)
+0074         end
+0075         searchIn=model.ec.rxns;
+0076     case 'ecenzymes'
+0077         if ~isfield(model,'ec')
+0078             error('Type %s cannot be used if no model.ec structure is present.',type)
+0079         end
+0080         searchIn=model.ec.enzymes;
+0081     case 'ecgenes'
+0082         if ~isfield(model,'ec')
+0083             error('Type %s cannot be used if no model.ec structure is present.',type)
+0084         end
+0085         searchIn=model.ec.genes;
+0086     otherwise
+0087         if contains(objects,{'rxns','mets','metnames','metcomps','genes','ecgenes','ecenzymes','ecrxns'})
+0088             error('The second and third parameter provided to run getIndexes are likely switched. Note that the second parameter is the object to find the index for, while the third parameter is the object type (''rxns'', ''mets'', ''metnames'', ''metcomps'', ''genes'', ''ecgenes'', ''ecenzymes'' or ''ecrxns'').')
+0089         else
+0090             error('Incorrect value of the ''type'' parameter. Allowed values are ''rxns'', ''mets'', ''metnames'', ''metcomps'', ''genes'', ''ecgenes'', ''ecenzymes'' or ''ecrxns''.');
+0091        end
+0092 end
+0093 
+0094 if iscell(objects)
+0095     for i=1:numel(objects)
+0096         index=find(strcmp(objects(i),searchIn));
+0097         if strcmpi(type,'metnames')
+0098             indexes{i}=index;
+0099         elseif ~isempty(index)
+0100             if length(index) > 1
+0101                 error('There are multiple instances of object "%s" in the model, while "%s" type should be unique', objects{i}, type)
+0102             end
+0103             indexes(i)=index;
+0104         else
+0105             error(['Could not find object ''' objects{i} ''' in the model']);
+0106         end
+0107     end
+0108 else
+0109     %Now it's either a logical (or 0/1) array or an array with indexes. We
+0110     %want it to be an array with indexes.
+0111     if all(objects)
+0112         %This gets weird if it's all 1
+0113         indexes=objects;
+0114     else
+0115         indexes=find(objects);
+0116     end
+0117 end
+0118 
+0119 if returnLogical==true
+0120     tempIndexes=false(numel(searchIn),1);
+0121     tempIndexes(indexes)=true;
+0122     indexes=tempIndexes;
+0123 end
+0124 
+0125 indexes=indexes(:);
+0126 if iscell(indexes) && length(indexes)==1
+0127     indexes=indexes{1};
+0128 end
+0129 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/getMetsInComp.html b/doc/core/getMetsInComp.html new file mode 100644 index 000000000..be4480152 --- /dev/null +++ b/doc/core/getMetsInComp.html @@ -0,0 +1,80 @@ + + + + Description of getMetsInComp + + + + + + + + + +
Home > core > getMetsInComp.m
+ + + +

getMetsInComp +

+ +

PURPOSE ^

+
getMetsInComp
+ +

SYNOPSIS ^

+
function [I, metNames]=getMetsInComp(model,comp)
+ +

DESCRIPTION ^

+
 getMetsInComp
+   Gets the metabolites in a specified compartment
+
+   model       a model structure
+   comp        string with the compartment id
+
+   I           boolean vector of the metabolites
+   metNames    the names of the metabolites
+
+ Usage: [I, metNames]=getMetsInComp(model,comp)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function [I, metNames]=getMetsInComp(model,comp)
+0002 % getMetsInComp
+0003 %   Gets the metabolites in a specified compartment
+0004 %
+0005 %   model       a model structure
+0006 %   comp        string with the compartment id
+0007 %
+0008 %   I           boolean vector of the metabolites
+0009 %   metNames    the names of the metabolites
+0010 %
+0011 % Usage: [I, metNames]=getMetsInComp(model,comp)
+0012 
+0013 comp=char(comp);
+0014 
+0015 J=find(ismember(upper(model.comps),upper(comp)));
+0016 
+0017 if numel(J)~=1
+0018     EM=['No unique match to compartment "' comp{1} '"'];
+0019     dispEM(EM);
+0020 end
+0021 
+0022 I=model.metComps==J;
+0023 metNames=model.metNames(I);
+0024 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/getMinNrFluxes.html b/doc/core/getMinNrFluxes.html new file mode 100644 index 000000000..62a6847d9 --- /dev/null +++ b/doc/core/getMinNrFluxes.html @@ -0,0 +1,237 @@ + + + + Description of getMinNrFluxes + + + + + + + + + +
Home > core > getMinNrFluxes.m
+ + + +

getMinNrFluxes +

+ +

PURPOSE ^

+
getMinNrFluxes
+ +

SYNOPSIS ^

+
function [x,I,exitFlag]=getMinNrFluxes(model, toMinimize, params,scores)
+ +

DESCRIPTION ^

+
 getMinNrFluxes
+   Returns the minimal set of fluxes that satisfy the model using
+   mixed integer linear programming.
+
+    model         a model structure
+   toMinimize    either a cell array of reaction IDs, a logical vector
+                 with the same number of elements as reactions in the model,
+                 of a vector of indexes for the reactions that should be
+                 minimized (optional, default model.rxns)
+   params        *obsolete option*
+   scores        vector of weights for the reactions. Negative scores
+                 should not have flux. Positive scores are not possible in this
+                 implementation, and they are changed to max(scores(scores<0)).
+                 Must have the same dimension as toMinimize (find(toMinimize)
+                 if it is a logical vector) (optional, default -1 for all reactions)
+
+   x             the corresponding fluxes for the full model
+   I             the indexes of the reactions in toMinimize that were used
+                 in the solution
+   exitFlag      1: optimal solution found
+                -1: no feasible solution found
+                -2: optimization time out
+
+   NOTE: Uses 1000 mmol/gDW/h as an arbitary large flux. Could possibly
+   cause problems if the fluxes in the model are larger than that.
+
+ Usage: [x,I,exitFlag]=getMinNrFluxes(model, toMinimize, params, scores)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function [x,I,exitFlag]=getMinNrFluxes(model, toMinimize, params,scores)
+0002 % getMinNrFluxes
+0003 %   Returns the minimal set of fluxes that satisfy the model using
+0004 %   mixed integer linear programming.
+0005 %
+0006 %    model         a model structure
+0007 %   toMinimize    either a cell array of reaction IDs, a logical vector
+0008 %                 with the same number of elements as reactions in the model,
+0009 %                 of a vector of indexes for the reactions that should be
+0010 %                 minimized (optional, default model.rxns)
+0011 %   params        *obsolete option*
+0012 %   scores        vector of weights for the reactions. Negative scores
+0013 %                 should not have flux. Positive scores are not possible in this
+0014 %                 implementation, and they are changed to max(scores(scores<0)).
+0015 %                 Must have the same dimension as toMinimize (find(toMinimize)
+0016 %                 if it is a logical vector) (optional, default -1 for all reactions)
+0017 %
+0018 %   x             the corresponding fluxes for the full model
+0019 %   I             the indexes of the reactions in toMinimize that were used
+0020 %                 in the solution
+0021 %   exitFlag      1: optimal solution found
+0022 %                -1: no feasible solution found
+0023 %                -2: optimization time out
+0024 %
+0025 %   NOTE: Uses 1000 mmol/gDW/h as an arbitary large flux. Could possibly
+0026 %   cause problems if the fluxes in the model are larger than that.
+0027 %
+0028 % Usage: [x,I,exitFlag]=getMinNrFluxes(model, toMinimize, params, scores)
+0029 
+0030 exitFlag=1;
+0031 
+0032 if nargin<2
+0033     toMinimize=model.rxns;
+0034 elseif ~islogical(toMinimize) && ~isnumeric(toMinimize)
+0035     toMinimize=convertCharArray(toMinimize);
+0036 else
+0037     toMinimize=model.rxns(toMinimize);
+0038 end
+0039 
+0040 %For passing parameters to the solver
+0041 if nargin<3
+0042     params=struct();
+0043 end
+0044 
+0045 if nargin<4
+0046     %It says that the default is -1, but that is to fit with other code
+0047     scores=ones(numel(toMinimize),1)*1;
+0048 else
+0049     if numel(scores)~=numel(toMinimize)
+0050         EM='The number of scores must be the same as the number of reactions to minimize';
+0051         dispEM(EM);
+0052     end
+0053     
+0054     %Change positive scores to have a small negative weight. This is a
+0055     %temporary solution.
+0056     scores(scores>=0)=max(scores(scores<0));
+0057     
+0058     %It says that the default is -1, but that is to fit with other code
+0059     scores=scores*-1;
+0060 end
+0061 
+0062 %Check if the model is in irreversible format
+0063 if any(model.rev)
+0064     %Convert the model to irreversible format
+0065     irrevModel=convertToIrrev(model);
+0066     
+0067     %Find the indexes for the reactions in toMinimize
+0068     [indexes, I]=ismember(strrep(irrevModel.rxns,'_REV',''),toMinimize);
+0069 else
+0070     irrevModel=model;
+0071     
+0072     %Find the indexes for the reactions in toMinimize
+0073     [indexes, I]=ismember(irrevModel.rxns,toMinimize);
+0074 end
+0075 
+0076 indexes=find(indexes);
+0077 %Adjust scores to fit with reversible
+0078 scores=scores(I(indexes));
+0079 
+0080 %Add binary constraints in the following manner: -  Add one unique
+0081 %"metabolite" for each integer reaction as a substrate.
+0082 %   These metabolites can have net production
+0083 %-  Add reactions for the production of each of those metabolites. The
+0084 %   amount produced in one reaction unit must be larger than the largest
+0085 %   possible flux in the model (but not too large to avoid bad scaling)
+0086 
+0087 %Calculate a solution to the problem without any constraints. This is to
+0088 %get an estimate about the magnitude of fluxes in the model and to get a
+0089 %feasible start solution.
+0090 sol=solveLP(irrevModel,1);
+0091 
+0092 %Return an empty solution if the non-constrained problem couldn't be solved
+0093 if isempty(sol.x)
+0094     x=[];
+0095     I=[];
+0096     exitFlag=-1;
+0097     return;
+0098 end
+0099 
+0100 %Take the maximal times 5 to have a safe margin. If it's smaller than 1000,
+0101 %then use 1000 instead.
+0102 maxFlux=max(max(sol.x)*5,1000);
+0103 
+0104 intArray=speye(numel(irrevModel.rxns))*-1;
+0105 intArray=intArray(indexes,:);
+0106 prob.a=[irrevModel.S;intArray];
+0107 a=[sparse(numel(irrevModel.mets),numel(indexes));speye(numel(indexes))*maxFlux];
+0108 prob.a=[prob.a a];
+0109 prob.ints.sub=numel(irrevModel.rxns)+1:numel(irrevModel.rxns)+numel(indexes);
+0110 
+0111 prob.c=[zeros(numel(irrevModel.rxns),1);scores(:);zeros(size(prob.a,1),1)]; %Minimize the number of fluxes
+0112 prob.A=[prob.a -speye(size(prob.a,1))];
+0113 prob.blc=[irrevModel.b(:,1);zeros(numel(indexes),1)];
+0114 if size(irrevModel.b,2)==2
+0115     prob.buc=[irrevModel.b(:,2);inf(numel(indexes),1)];
+0116 else
+0117     prob.buc=[irrevModel.b(:,1);inf(numel(indexes),1)];
+0118 end
+0119 prob.blx=[irrevModel.lb;zeros(numel(indexes),1)];
+0120 prob.bux=[irrevModel.ub;ones(numel(indexes),1)];
+0121 prob.lb = [prob.blx; prob.blc];
+0122 prob.ub = [prob.bux; prob.buc];
+0123 prob.osense=1;
+0124 prob.csense=repmat('E', 1, size(prob.a,1),1);
+0125 prob.b=zeros(size(prob.a,1), 1);
+0126 
+0127 %Use the output from the linear solution as starting point. Only the values
+0128 %for the integer variables will be used, but all are supplied.
+0129 prob.sol.int.xx=zeros(numel(prob.c),1);
+0130 prob.sol.int.xx(prob.ints.sub(sol.x(indexes)>10^-12))=1;
+0131 prob.x0=[];
+0132 prob.vartype=repmat('C', size(prob.A,2), 1);
+0133 prob.vartype(prob.ints.sub) = 'I'; % with .lb = 0 and .ub = 1, they are binary
+0134 % integers (glpk in octave only allows 'continuous' or '', not 'binary')
+0135 prob=rmfield(prob,{'blx','bux','blc','buc'});
+0136 
+0137 % Optimize the problem
+0138 res = optimizeProb(prob,params,false);
+0139 isFeasible=checkSolution(res);
+0140 
+0141 if ~isFeasible
+0142     x=[];
+0143     I=[];
+0144     exitFlag=-1;
+0145     return;
+0146 end
+0147 
+0148 xx=res.full(1:numel(irrevModel.rxns));
+0149 I=res.full(numel(xx)+1:end);
+0150 
+0151 %Check if Mosek aborted because it reached the time limit
+0152 %TODO: modify for cobra/gurobi
+0153 % if strcmp('MSK_RES_TRM_MAX_TIME',res.rcode)
+0154 %     exitFlag=-2;
+0155 % end
+0156 
+0157 %Map back to original model from irrevModel
+0158 x=xx(1:numel(model.rxns));
+0159 if numel(irrevModel.rxns)>numel(model.rxns)
+0160     x(model.rev~=0)=x(model.rev~=0)-xx(numel(model.rxns)+1:end);
+0161 end
+0162 
+0163 I=ismember(toMinimize,strrep(irrevModel.rxns(indexes(I>10^-12)),'_REV',''));
+0164 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/getModelFromHomology.html b/doc/core/getModelFromHomology.html new file mode 100644 index 000000000..5291424f9 --- /dev/null +++ b/doc/core/getModelFromHomology.html @@ -0,0 +1,663 @@ + + + + Description of getModelFromHomology + + + + + + + + + +
Home > core > getModelFromHomology.m
+ + + +

getModelFromHomology +

+ +

PURPOSE ^

+
getModelFromHomology
+ +

SYNOPSIS ^

+
function [draftModel, hitGenes]=getModelFromHomology(models,blastStructure,getModelFor,preferredOrder,strictness,onlyGenesInModels,maxE,minLen,minIde,mapNewGenesToOld)
+ +

DESCRIPTION ^

+
 getModelFromHomology
+   Constructs a new model from a set of existing models and gene homology
+   information.
+
+   models            a cell array of model structures to build the model
+                     from. These models must be sorted by importance in
+                     decreasing order
+   blastStructure    a blastStructure as produced by getBlast or
+                     getBlastFromExcel
+   getModelFor       a three-four letter abbreviation of the organism to
+                     build a model for. Must have BLASTP hits in both
+                     directions to the organisms in 'models'
+   preferredOrder    the order in which reactions should be added from the
+                     models. If not supplied, reactions will be included
+                     from all models, otherwise one gene will only result
+                     in reactions from one model (optional, default {})
+   strictness        integer that specifies which reactions should be
+                     included:
+                     1: Map new genes to old for all pairs, which have
+                     acceptable BLASTP results in both directions
+                     2: Map new genes to old for all pairs, which have
+                     acceptable BLASTP results in correspondent direction
+                     (mapping can be done in the opposite direction, see
+                     mapNewGenesToOld below)
+                     3: Check all BLASTP results and retain only the best
+                     results by E-value for all gene pairs in each
+                     direction separately. Then map new genes to old for
+                     all pairs, which have acceptable BLASTP results in
+                     both directions (optional, default 1).
+   onlyGenesInModels consider BLASTP results only for genes that exist in
+                     the models. This tends to import a larger fraction
+                     from the existing models but may give less reliable
+                     results. Has effect only if strictness=3 (optional,
+                     default false)
+   maxE              only look at genes with E-values <= this value (optional,
+                     default 10^-30)
+   minLen            only look at genes with alignment length >= this
+                     value (optional, default 200)
+   minIde            only look at genes with identity >= this value
+                     (optional, default 40 (%))
+   mapNewGenesToOld  determines how to match genes if not looking at only
+                     1-1 orthologs. Either map the new genes to the old or
+                     old genes to new. The default is to map the new genes
+                     (optional, default true)
+
+   draftModel        a model structure for the new organism
+   hitGenes          collect the old and new genes
+
+   The models in the 'models' structure should have named the metabolites
+   in the same manner, have their reversible reactions in the same
+   direction (run sortModel), and use the same compartment names. To avoid
+   keeping unneccesary old genes, the models should not have
+   'or'-relations in their grRules (use expandModel).
+
+   The resulting draft model contains only reactions associated with
+   orthologous genes. The old (original) genes involved in 'and'
+   relations in grRules without any orthologs are still included in
+   the draft model as OLD_MODELID_geneName.
+
+   NOTE: "to" and "from" means relative to the new organism
+
+ Usage: draftModel=getModelFromHomology(models,blastStructure,...
+    getModelFor,preferredOrder,strictness,onlyGenesInModels,maxE,...
+    minLen,minIde,mapNewGenesToOld)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function [draftModel, hitGenes]=getModelFromHomology(models,blastStructure,...
+0002     getModelFor,preferredOrder,strictness,onlyGenesInModels,maxE,...
+0003     minLen,minIde,mapNewGenesToOld)
+0004 % getModelFromHomology
+0005 %   Constructs a new model from a set of existing models and gene homology
+0006 %   information.
+0007 %
+0008 %   models            a cell array of model structures to build the model
+0009 %                     from. These models must be sorted by importance in
+0010 %                     decreasing order
+0011 %   blastStructure    a blastStructure as produced by getBlast or
+0012 %                     getBlastFromExcel
+0013 %   getModelFor       a three-four letter abbreviation of the organism to
+0014 %                     build a model for. Must have BLASTP hits in both
+0015 %                     directions to the organisms in 'models'
+0016 %   preferredOrder    the order in which reactions should be added from the
+0017 %                     models. If not supplied, reactions will be included
+0018 %                     from all models, otherwise one gene will only result
+0019 %                     in reactions from one model (optional, default {})
+0020 %   strictness        integer that specifies which reactions should be
+0021 %                     included:
+0022 %                     1: Map new genes to old for all pairs, which have
+0023 %                     acceptable BLASTP results in both directions
+0024 %                     2: Map new genes to old for all pairs, which have
+0025 %                     acceptable BLASTP results in correspondent direction
+0026 %                     (mapping can be done in the opposite direction, see
+0027 %                     mapNewGenesToOld below)
+0028 %                     3: Check all BLASTP results and retain only the best
+0029 %                     results by E-value for all gene pairs in each
+0030 %                     direction separately. Then map new genes to old for
+0031 %                     all pairs, which have acceptable BLASTP results in
+0032 %                     both directions (optional, default 1).
+0033 %   onlyGenesInModels consider BLASTP results only for genes that exist in
+0034 %                     the models. This tends to import a larger fraction
+0035 %                     from the existing models but may give less reliable
+0036 %                     results. Has effect only if strictness=3 (optional,
+0037 %                     default false)
+0038 %   maxE              only look at genes with E-values <= this value (optional,
+0039 %                     default 10^-30)
+0040 %   minLen            only look at genes with alignment length >= this
+0041 %                     value (optional, default 200)
+0042 %   minIde            only look at genes with identity >= this value
+0043 %                     (optional, default 40 (%))
+0044 %   mapNewGenesToOld  determines how to match genes if not looking at only
+0045 %                     1-1 orthologs. Either map the new genes to the old or
+0046 %                     old genes to new. The default is to map the new genes
+0047 %                     (optional, default true)
+0048 %
+0049 %   draftModel        a model structure for the new organism
+0050 %   hitGenes          collect the old and new genes
+0051 %
+0052 %   The models in the 'models' structure should have named the metabolites
+0053 %   in the same manner, have their reversible reactions in the same
+0054 %   direction (run sortModel), and use the same compartment names. To avoid
+0055 %   keeping unneccesary old genes, the models should not have
+0056 %   'or'-relations in their grRules (use expandModel).
+0057 %
+0058 %   The resulting draft model contains only reactions associated with
+0059 %   orthologous genes. The old (original) genes involved in 'and'
+0060 %   relations in grRules without any orthologs are still included in
+0061 %   the draft model as OLD_MODELID_geneName.
+0062 %
+0063 %   NOTE: "to" and "from" means relative to the new organism
+0064 %
+0065 % Usage: draftModel=getModelFromHomology(models,blastStructure,...
+0066 %    getModelFor,preferredOrder,strictness,onlyGenesInModels,maxE,...
+0067 %    minLen,minIde,mapNewGenesToOld)
+0068 
+0069 hitGenes.oldGenes = [];  % collect the old genes from the template model (organism)
+0070 hitGenes.newGenes = [];  % collect the new genes of the draft model (target organism)
+0071 
+0072 getModelFor=char(getModelFor);
+0073 
+0074 if nargin<4
+0075     preferredOrder=[];
+0076 else
+0077     preferredOrder=convertCharArray(preferredOrder);
+0078     [row,col]=size(preferredOrder);
+0079     if col>row
+0080         preferredOrder=transpose(preferredOrder);
+0081     end
+0082 end
+0083 if nargin<5
+0084     strictness=1;
+0085 end
+0086 if nargin<6
+0087     onlyGenesInModels=false;
+0088 end
+0089 if nargin<7
+0090     maxE=10^-30;
+0091 end
+0092 if nargin<8
+0093     minLen=200;
+0094 end
+0095 if nargin<9
+0096     minIde=40;
+0097 end
+0098 if nargin<10
+0099     mapNewGenesToOld=true;
+0100 end
+0101 
+0102 if isfield(models,'S')
+0103     models={models};
+0104 end
+0105     
+0106 %Check that all the information is in the blast structure
+0107 modelNames=cell(numel(models),1);
+0108 for i=1:numel(models)
+0109     modelNames{i}=models{i}.id;
+0110     %Gene short names, geneMiriams and proteins are often different
+0111     %between species, safer not to include them
+0112     if isfield(models{i},'geneShortNames')
+0113         models{i}=rmfield(models{i},'geneShortNames');
+0114     end
+0115     if isfield(models{i},'geneMiriams')
+0116         models{i}=rmfield(models{i},'geneMiriams');
+0117     end
+0118     if isfield(models{i},'proteins')
+0119         models{i}=rmfield(models{i},'proteins');
+0120     end
+0121     %The geneFrom field also loses meaning if the genes are replaced by
+0122     %orthologs
+0123     if isfield(models{i},'geneFrom')
+0124         models{i}=rmfield(models{i},'geneFrom');
+0125     end
+0126 end
+0127 
+0128 %Check that genes do not begin with ( or end with ), as this makes problematic grRules
+0129 for i=1:numel(blastStructure)
+0130     problemGenes = startsWith(blastStructure(i).fromGenes,'(') | endsWith(blastStructure(i).fromGenes,')');
+0131     if any(problemGenes)
+0132         error(['One or multiple gene identifiers from ' blastStructure(i).fromId ...
+0133                ' starts with ''('' and/or ends with '')'', which is not allowed'])
+0134     end
+0135 end
+0136 
+0137 %Assume for now that all information is there and that it's correct. This
+0138 %is important to fix since no further checks are being made!
+0139 
+0140 %Check whether provided fasta files use the same gene identifiers as
+0141 %provided template models
+0142 for i=1:numel(blastStructure)
+0143     if ~strcmp(blastStructure(i).fromId,getModelFor)
+0144         j=strcmpi(blastStructure(i).fromId,modelNames);
+0145         if j==0
+0146             error(['While the blastStructure contains sequences from '...
+0147                 'organismID "%s" (as\nprovided in getBlast), none of '...
+0148                 'template models have this id (as model.id)'],...
+0149                 string(blastStructure(i).fromId));
+0150         end
+0151         k=sum(ismember(blastStructure(i).fromGenes,models{j}.genes));
+0152         if k<(numel(models{j}.genes)*0.05)
+0153             error(['Less than 5%% of the genes in the template model '...
+0154                 'with model.id "%s"\ncan be found in the blastStructure. '...
+0155                 'Ensure that the protein FASTA\nused in getBlast and '...
+0156                 'the template model used in getModelFromHomology\nuse '...
+0157                 'the same style of gene identifiers'],models{j}.id)
+0158         end
+0159     end
+0160 end
+0161 
+0162 %Standardize grRules of template models
+0163 for i=1:length(models)
+0164     fprintf('\nStandardizing grRules of template model with ID "%s" ...',models{i}.id);
+0165     [models{i}.grRules,models{i}.rxnGeneMat]=standardizeGrRules(models{i},false);
+0166 end
+0167 fprintf(' done\n');
+0168 
+0169 %Remove all gene matches that are below the cutoffs
+0170 for i=1:numel(blastStructure)
+0171     indexes=blastStructure(i).evalue<maxE & blastStructure(i).aligLen>=minLen & blastStructure(i).identity>=minIde; %Do it in this direction to lose NaNs
+0172     blastStructure(i).fromGenes(~indexes)=[];
+0173     blastStructure(i).toGenes(~indexes)=[];
+0174     blastStructure(i).evalue(~indexes)=[];
+0175     blastStructure(i).identity(~indexes)=[];
+0176     blastStructure(i).aligLen(~indexes)=[];
+0177     blastStructure(i).bitscore(~indexes)=[];
+0178     blastStructure(i).ppos(~indexes)=[];
+0179 end
+0180 
+0181 %Remove all reactions from the models that have no genes encoding for them.
+0182 %Also remove all genes that encode for no reactions. There shouldn't be any
+0183 %but there might be mistakes
+0184 for i=1:numel(models)
+0185     [hasGenes, ~]=find(models{i}.rxnGeneMat);
+0186     hasNoGenes=1:numel(models{i}.rxns);
+0187     hasNoGenes(hasGenes)=[];
+0188     models{i}=removeReactions(models{i},hasNoGenes,true,true);
+0189 end
+0190 
+0191 %Create a structure that contains all genes used in the blasts in any
+0192 %direction for each of the models in 'models' and for the new organism. The
+0193 %first cell is for the new organism and then according to the preferred
+0194 %order. If no such order is supplied, then according to the order in
+0195 %'models'
+0196 allGenes=cell(numel(models)+1,1);
+0197 if isempty(preferredOrder)
+0198     useOrder=modelNames;
+0199 else
+0200     useOrder=preferredOrder;
+0201 end
+0202 
+0203 %Get the corresponding indexes for those models in the 'models' structure
+0204 useOrderIndexes=zeros(numel(models),1);
+0205 for i=1:numel(models)
+0206     [~, index]=ismember(models{i}.id,useOrder);
+0207     useOrderIndexes(index)=i;
+0208 end
+0209 
+0210 %Remove all genes from the blast structure that have no genes in the models
+0211 if onlyGenesInModels==true
+0212     modelGenes={};
+0213     for i=1:numel(models)
+0214         modelGenes=[modelGenes;models{i}.genes];
+0215     end
+0216     for i=1:numel(blastStructure)
+0217         %Check to see if it should match the toId or fromId
+0218         if strcmpi(blastStructure(i).fromId,getModelFor)
+0219             I=ismember(blastStructure(i).toGenes,modelGenes);
+0220         else
+0221             I=ismember(blastStructure(i).fromGenes,modelGenes);
+0222         end
+0223         blastStructure(i).fromGenes(~I)=[];
+0224         blastStructure(i).toGenes(~I)=[];
+0225         blastStructure(i).evalue(~I)=[];
+0226         blastStructure(i).identity(~I)=[];
+0227         blastStructure(i).aligLen(~I)=[];
+0228         blastStructure(i).bitscore(~I)=[];
+0229         blastStructure(i).ppos(~I)=[];
+0230         
+0231         %Check that no matching in blastStructure is empty. This happens if
+0232         %no genes in the models are present in the corresponding sheet
+0233         if isempty(blastStructure(i).fromGenes)
+0234             EM=['No genes in matching from ' blastStructure(i).fromId ' to ' blastStructure(i).toId ' are present in the corresponding model'];
+0235             dispEM(EM);
+0236         end
+0237     end
+0238 end
+0239 
+0240 %If only best orthologs are to be used then all other measurements are
+0241 %deleted from the blastStructure. All code after this stays the same. This
+0242 %means that preferred order can still matter. The best ortholog scoring is
+0243 %based only on the E-value
+0244 if strictness==3
+0245     for i=1:numel(blastStructure)
+0246         keep=false(numel(blastStructure(i).toGenes),1);
+0247         [allFromGenes, ~, I]=unique(blastStructure(i).fromGenes);
+0248         
+0249         %It would be nice to get rid of this loop
+0250         for j=1:numel(allFromGenes)
+0251             allMatches=find(I==j);
+0252             bestMatches=allMatches(blastStructure(i).evalue(allMatches)==min(blastStructure(i).evalue(allMatches)));
+0253             
+0254             %Keep the best matches
+0255             keep(bestMatches)=true;
+0256         end
+0257         
+0258         %Delete all matches that were not best matches
+0259         blastStructure(i).fromGenes(~keep)=[];
+0260         blastStructure(i).toGenes(~keep)=[];
+0261         blastStructure(i).evalue(~keep)=[];
+0262         blastStructure(i).identity(~keep)=[];
+0263         blastStructure(i).aligLen(~keep)=[];
+0264         blastStructure(i).bitscore(~keep)=[];
+0265         blastStructure(i).ppos(~keep)=[];
+0266     end
+0267 end
+0268 
+0269 useOrder=[{getModelFor};useOrder];
+0270 
+0271 for i=1:numel(blastStructure)
+0272     [~, toIndex]=ismember(blastStructure(i).toId,useOrder);
+0273     [~, fromIndex]=ismember(blastStructure(i).fromId,useOrder);
+0274     
+0275     %Add all genes to the corresponding list in allGenes
+0276     allGenes{toIndex}=[allGenes{toIndex};blastStructure(i).toGenes];
+0277     allGenes{fromIndex}=[allGenes{fromIndex};blastStructure(i).fromGenes];
+0278 end
+0279 
+0280 %Keep only the unique gene names
+0281 maxOtherGeneNr=0; %Determines the dimension of the connectivity matrixes
+0282 for i=1:numel(allGenes)
+0283     allGenes{i}=unique(allGenes{i});
+0284     if i>1
+0285         if numel(allGenes{i})>maxOtherGeneNr
+0286             maxOtherGeneNr=numel(allGenes{i});
+0287         end
+0288     end
+0289 end
+0290 
+0291 %Generate a cell array of matrixes that describes how the genes in the new
+0292 %organism map to the models. Each cell matches to the corresponding model
+0293 %in useOrder (starting at 2 of course). First dimension is gene in new
+0294 %organism, second which gene it is in the other organism. The second matrix
+0295 %describes how they map back.
+0296 
+0297 %As it is now, a significant match is indicated by a 1. This could be
+0298 %expanded to contain some kind of significance level. The first dimension
+0299 %is still the genes in the new model.
+0300 
+0301 allTo=cell(numel(useOrder)-1,1);
+0302 allFrom=cell(numel(useOrder)-1,1);
+0303 
+0304 for i=1:numel(useOrder)-1
+0305     allTo{i}=sparse(numel(allGenes{1}),numel(allGenes{i+1}));
+0306     allFrom{i}=sparse(numel(allGenes{1}),numel(allGenes{i+1}));
+0307 end
+0308 
+0309 %Fill the matches to other species
+0310 for i=1:numel(blastStructure)
+0311     if strcmp(blastStructure(i).toId,getModelFor)
+0312         %This was 'to' the new organism. They should all match so no checks
+0313         %are being made
+0314         [~, a]=ismember(blastStructure(i).toGenes,allGenes{1});
+0315         [~, fromModel]=ismember(blastStructure(i).fromId,useOrder);
+0316         [~, b]=ismember(blastStructure(i).fromGenes,allGenes{fromModel});
+0317         idx = sub2ind(size(allTo{fromModel-1}), a, b);
+0318         allTo{fromModel-1}(idx)=1;
+0319     else
+0320         %This was 'from' the new organism
+0321         [~, a]=ismember(blastStructure(i).fromGenes,allGenes{1});
+0322         [~, toModel]=ismember(blastStructure(i).toId,useOrder);
+0323         [~, b]=ismember(blastStructure(i).toGenes,allGenes{toModel});
+0324         idx = sub2ind(size(allFrom{toModel-1}), a, b);
+0325         allFrom{toModel-1}(idx)=1;
+0326     end
+0327 end
+0328 
+0329 %Now we have all the gene matches in a convenient way. For all the genes in
+0330 %the new organism get the genes that should be included from other
+0331 %organisms. If all genes should be included this simply means keep the
+0332 %allFrom matrix as it is. If only orthologs which could be mapped in both
+0333 %BLAST directions are to be included then only those elements are kept.
+0334 
+0335 finalMappings=cell(numel(useOrder)-1,1);
+0336 if strictness==1 || strictness==3
+0337     for j=1:numel(allFrom)
+0338         finalMappings{j}=allTo{j}~=0 & allFrom{j}~=0;
+0339     end
+0340 else
+0341     if mapNewGenesToOld==true
+0342         finalMappings=allFrom;
+0343     else
+0344         finalMappings=allTo;
+0345     end
+0346 end
+0347 
+0348 %Remove all genes from the mapping that are not in the models. This doesn't
+0349 %do much if only genes in the models were used for the original mapping.
+0350 %Also simplify the finalMapping and allGenes structures so that they only
+0351 %contain mappings that exist
+0352 usedNewGenes=false(numel(allGenes{1}),1);
+0353 
+0354 for i=1:numel(allGenes)-1
+0355     %First remove mappings for those genes that are not in the model
+0356     if onlyGenesInModels==false
+0357         a=ismember(allGenes{i+1},models{useOrderIndexes(i)}.genes);
+0358         finalMappings{i}(:,~a)=false;
+0359     end
+0360     
+0361     %Then remove unused ones and simplify
+0362     [a, b]=find(finalMappings{i});
+0363     usedGenes=false(numel(allGenes{i+1}),1);
+0364     usedNewGenes(a)=true;
+0365     usedGenes(b)=true;
+0366     finalMappings{i}=finalMappings{i}(:,usedGenes);
+0367     allGenes{i+1}=allGenes{i+1}(usedGenes);
+0368 end
+0369 
+0370 %Remove all new genes that have not been mapped to anything
+0371 allGenes{1}=allGenes{1}(usedNewGenes);
+0372 for i=1:numel(finalMappings)
+0373     finalMappings{i}=finalMappings{i}(usedNewGenes,:);
+0374 end
+0375 
+0376 %Now is it time to choose which reactions should be included from which
+0377 %models. If there is a preferred order specified then each gene can only
+0378 %result in reactions from one model, otherwise they should all be included
+0379 
+0380 %Start by simplifying the models by removing genes/reactions that are not
+0381 %used. This is where it gets weird with complexes, especially "or"
+0382 %complexes. In this step only reactions which are encoded by one single
+0383 %gene, or where all genes should be deleted, are deleted. The info on the
+0384 %full complex is still present in the grRules
+0385 
+0386 for i=1:numel(models)
+0387     a=ismember(models{useOrderIndexes(i)}.genes,allGenes{i+1});
+0388     
+0389     %Remove reactions that are not associated to any of the genes in
+0390     %allGenes, thereby also keeping complexes where only for one of the
+0391     %genes was matched
+0392     [rxnsToKeep,~] = find(models{useOrderIndexes(i)}.rxnGeneMat(:,a));
+0393     rxnsToRemove = repmat(1,numel(models{useOrderIndexes(i)}.rxns),1);
+0394     rxnsToRemove(rxnsToKeep) = 0;
+0395     rxnsToRemove = find(rxnsToRemove);
+0396     models{useOrderIndexes(i)}=removeReactions(models{useOrderIndexes(i)},rxnsToRemove,true,true,true);
+0397 end
+0398 
+0399 %Since mergeModels function will be used in the end, the models are
+0400 %simplified further by deleting genes/reactions in the order specified by
+0401 %preferredOrder. This means that the last model will only contain reactions
+0402 %for genes that mapped only to that model
+0403 
+0404 allUsedGenes=false(numel(allGenes{1}),1);
+0405 
+0406 if ~isempty(preferredOrder) && numel(models)>1
+0407     [usedGenes, ~]=find(finalMappings{1}); %All that are used in the first model in preferredOrder
+0408     allUsedGenes(usedGenes)=true;
+0409     for i=2:numel(finalMappings)
+0410         [usedGenes, ~]=find(finalMappings{i});
+0411         usedGenes=unique(usedGenes);
+0412         a=ismember(usedGenes,find(allUsedGenes));
+0413         
+0414         [~, genesToDelete]=find(finalMappings{i}(usedGenes(a),:)); %IMPORTANT! IS it really correct to remove all genes that map?
+0415         genesToDelete=unique(genesToDelete); %Maybe not needed, but for clarity if nothing else
+0416         
+0417         %Remove all the genes that were already found and add the other
+0418         %ones to allUsedGenes
+0419         models{useOrderIndexes(i)}=removeGenes(models{useOrderIndexes(i)},allGenes{i+1}(genesToDelete),true,true,false);
+0420         allUsedGenes(usedGenes)=true;
+0421         
+0422         %Remove the deleted genes from finalMappings and allGenes.
+0423         finalMappings{i}(:,genesToDelete)=[];
+0424         allGenes{i+1}(genesToDelete)=[];
+0425     end
+0426 end
+0427 
+0428 %Now loop through the models and update the gene associations. Genes not
+0429 %belonging to the new organism will be renamed as 'OLD_MODELID_gene'
+0430 for i=1:numel(models)
+0431     %Find all the new genes that should be used for this model
+0432     [newGenes, oldGenes]=find(finalMappings{i});
+0433     
+0434     %Create a new gene list with the genes from the new organism and those
+0435     %genes that could not be removed
+0436     replaceableGenes=allGenes{i+1}(unique(oldGenes));
+0437     nonReplaceableGenes=setdiff(models{useOrderIndexes(i)}.genes,replaceableGenes);
+0438     fullGeneList=[allGenes{1}(unique(newGenes));nonReplaceableGenes];
+0439     
+0440     %Just to save some indexing later. This is the LAST index of
+0441     %replaceable ones
+0442     nonRepStartIndex=numel(unique(newGenes));
+0443     
+0444     %Construct a new rxnGeneMat
+0445     newRxnGeneMat=sparse(numel(models{useOrderIndexes(i)}.rxns),numel(fullGeneList));
+0446     
+0447     %Now update the rxnGeneMat. This is a little tricky and could
+0448     %probably be done in a more efficient way, but I just loop through the
+0449     %reactions and add them one by one
+0450     for j=1:numel(models{useOrderIndexes(i)}.rxns)
+0451         %Get the old genes encoding for this reaction
+0452         [~, oldGeneIds]=find(models{useOrderIndexes(i)}.rxnGeneMat(j,:));
+0453         
+0454         %Update the matrix for each gene. This includes replacing one gene
+0455         %with several new ones if there were several matches
+0456         for k=1:numel(oldGeneIds)
+0457             %Match the gene to one in the gene list. This is done as a text
+0458             %match. Could probably be done better, but I'm a little lost in
+0459             %the indexing
+0460             
+0461             geneName=models{useOrderIndexes(i)}.genes(oldGeneIds(k));
+0462             
+0463             %First search in the mappable genes
+0464             mapIndex=find(ismember(allGenes{i+1},geneName));
+0465             
+0466             if ~isempty(mapIndex)
+0467                 % add the old genes
+0468                 hitGenes.oldGenes = [hitGenes.oldGenes, {geneName}];
+0469                 
+0470                 %Get the new genes for that gene
+0471                 a=find(finalMappings{i}(:,mapIndex));
+0472                 
+0473                 %Find the positions of these genes in the final gene list
+0474                 [~, b]=ismember(allGenes{1}(a),fullGeneList);
+0475                 
+0476                 %Update the matrix
+0477                 newRxnGeneMat(j,b)=1;
+0478                 
+0479                 %Update the grRules string. This is tricky, but I hope that
+0480                 %it's ok to replace the old gene name with the new one and
+0481                 %add ') or (' if there were several matches. Be sure of
+0482                 %this!
+0483                 repString=fullGeneList{b(1)};
+0484                 if numel(b)>1
+0485                     for l=2:numel(b)
+0486                         repString=[repString ' or ' fullGeneList{b(l)}];
+0487                     end
+0488                     repString=['(' repString ')'];
+0489                 end
+0490                 
+0491                 % add the new matched genes
+0492                 hitGenes.newGenes = [hitGenes.newGenes, {repString}];
+0493                 
+0494                 %Use regexprep instead of strrep to prevent partial matches
+0495                 models{useOrderIndexes(i)}.grRules{j}=regexprep(models{useOrderIndexes(i)}.grRules{j},['(^|\s|\()' geneName{1} '($|\s|\))'],['$1' repString '$2']);
+0496             else
+0497                 %Then search in the non-replaceable genes. There could only
+0498                 %be one match here
+0499                 index=find(ismember(nonReplaceableGenes,geneName));
+0500                 
+0501                 %Update the matrix
+0502                 newRxnGeneMat(j,nonRepStartIndex+index)=1;
+0503                 
+0504                 models{useOrderIndexes(i)}.grRules{j}=strrep(models{useOrderIndexes(i)}.grRules{j},geneName{1},strcat('OLD_',models{useOrderIndexes(i)}.id,'_',geneName{1}));
+0505             end
+0506         end
+0507     end
+0508     
+0509     %Add the new list of genes
+0510     models{useOrderIndexes(i)}.rxnGeneMat=newRxnGeneMat;
+0511     if ~isempty(nonReplaceableGenes)
+0512         models{useOrderIndexes(i)}.genes=[allGenes{1}(unique(newGenes));strcat('OLD_',models{useOrderIndexes(i)}.id,'_',nonReplaceableGenes)];
+0513     else
+0514         models{useOrderIndexes(i)}.genes=allGenes{1}(unique(newGenes));
+0515     end
+0516     if isfield(models{useOrderIndexes(i)},'geneComps')
+0517         geneComps=models{useOrderIndexes(i)}.geneComps(1);
+0518         models{useOrderIndexes(i)}.geneComps=zeros(numel(models{useOrderIndexes(i)}.genes),1);
+0519         %Assume that all genes are in the same compartment, and this
+0520         %compartment is specified for the first gene
+0521         models{useOrderIndexes(i)}.geneComps(:)=geneComps;
+0522     end
+0523 end
+0524 
+0525 %Now merge the models. All information should be correct except for 'or'
+0526 %complexes
+0527 draftModel=mergeModels(models,'metNames');
+0528 
+0529 %Remove unnecessary OLD_ genes, that were added with OR relationships
+0530 regexStr=['OLD_(', strjoin(modelNames(:),'|'),')_(\S^\))+'];
+0531 draftModel.grRules=regexprep(draftModel.grRules,[' or ' regexStr],'');
+0532 draftModel.grRules=regexprep(draftModel.grRules,[regexStr ' or '],'');
+0533 
+0534 %Change name of the resulting model
+0535 draftModel.id=getModelFor;
+0536 name='Generated by getModelFromHomology using ';
+0537 for i=1:numel(models)
+0538     if i<numel(models)
+0539         name=[name models{i}.id ', '];
+0540     else
+0541         name=[name models{i}.id];
+0542     end
+0543 end
+0544 draftModel.name=name;
+0545 draftModel.rxnNotes=cell(length(draftModel.rxns),1);
+0546 draftModel.rxnNotes(:)={'Included by getModelFromHomology'};
+0547 draftModel.rxnConfidenceScores=NaN(length(draftModel.rxns),1);
+0548 draftModel.rxnConfidenceScores(:)=2;
+0549 draftModel=deleteUnusedGenes(draftModel,0);
+0550 %Standardize grRules and notify if problematic grRules are found
+0551 [draftModel.grRules,draftModel.rxnGeneMat]=standardizeGrRules(draftModel,false);
+0552 draftModel=deleteUnusedGenes(draftModel,false);
+0553 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/getRxnsInComp.html b/doc/core/getRxnsInComp.html new file mode 100644 index 000000000..5de7d1f1b --- /dev/null +++ b/doc/core/getRxnsInComp.html @@ -0,0 +1,100 @@ + + + + Description of getRxnsInComp + + + + + + + + + +
Home > core > getRxnsInComp.m
+ + + +

getRxnsInComp +

+ +

PURPOSE ^

+
getRxnsInComp
+ +

SYNOPSIS ^

+
function [I, rxnNames]=getRxnsInComp(model,comp,includePartial)
+ +

DESCRIPTION ^

+
 getRxnsInComp
+   Gets the reactions in a specified compartment
+
+   model           a model structure
+   comp            string with the compartment id
+   includePartial  true if reactions with metabolites in several
+                   compartments (normally transport reactions) should
+                   be included (optional, default false)
+
+   I               boolean vector of the reactions
+   rxnNames        the names of the reactions
+
+ Usage: [I, rxnNames]=getRxnsInComp(model,comp,includePartial)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function [I, rxnNames]=getRxnsInComp(model,comp,includePartial)
+0002 % getRxnsInComp
+0003 %   Gets the reactions in a specified compartment
+0004 %
+0005 %   model           a model structure
+0006 %   comp            string with the compartment id
+0007 %   includePartial  true if reactions with metabolites in several
+0008 %                   compartments (normally transport reactions) should
+0009 %                   be included (optional, default false)
+0010 %
+0011 %   I               boolean vector of the reactions
+0012 %   rxnNames        the names of the reactions
+0013 %
+0014 % Usage: [I, rxnNames]=getRxnsInComp(model,comp,includePartial)
+0015 
+0016 comp=char(comp);
+0017 if nargin<3
+0018     includePartial=false;
+0019 end
+0020 
+0021 J=find(ismember(upper(model.comps),upper(comp)));
+0022 
+0023 if numel(J)~=1
+0024     EM=['No unique match to compartment "' comp{1} '"'];
+0025     dispEM(EM);
+0026 end
+0027 
+0028 K=model.metComps==J; %Get all metabolites in the compartment
+0029 
+0030 S=model.S~=0;
+0031 
+0032 %Find the reactions which involve any of the mets
+0033 [~, I]=find(S(K,:));
+0034 I=unique(I);
+0035 
+0036 %Then remove the ones which also include metabolites in other comps
+0037 if includePartial==false
+0038     I=I(sum(S(:,I))==sum(S(K,I)));
+0039 end
+0040 rxnNames=model.rxnNames(I);
+0041 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/getTransportRxns.html b/doc/core/getTransportRxns.html new file mode 100644 index 000000000..32a04c6e7 --- /dev/null +++ b/doc/core/getTransportRxns.html @@ -0,0 +1,80 @@ + + + + Description of getTransportRxns + + + + + + + + + +
Home > core > getTransportRxns.m
+ + + +

getTransportRxns +

+ +

PURPOSE ^

+
getTransportRxns
+ +

SYNOPSIS ^

+
function transportRxns=getTransportRxns(model)
+ +

DESCRIPTION ^

+
 getTransportRxns
+   Retrieves the transport reactions from a model
+
+   model           a model structure
+
+   transportRxns   logical array with true if the corresponding 
+                   reaction is a transport reaction
+
+   Transport reactions are defined as reactions involving (at least) one
+   metabolite name in more than one compartment.
+
+ Usage: transportRxns=getTransportRxns(model)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function transportRxns=getTransportRxns(model)
+0002 % getTransportRxns
+0003 %   Retrieves the transport reactions from a model
+0004 %
+0005 %   model           a model structure
+0006 %
+0007 %   transportRxns   logical array with true if the corresponding
+0008 %                   reaction is a transport reaction
+0009 %
+0010 %   Transport reactions are defined as reactions involving (at least) one
+0011 %   metabolite name in more than one compartment.
+0012 %
+0013 % Usage: transportRxns=getTransportRxns(model)
+0014 
+0015 transportRxns=false(numel(model.rxns),1);
+0016 
+0017 for i=1:numel(model.rxns)
+0018     %Get the involved metabolites in each reaction
+0019     mets=model.metNames(model.S(:,i)~=0);
+0020     transportRxns(i)=numel(mets)~=numel(unique(mets));
+0021 end
+0022 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/guessComposition.html b/doc/core/guessComposition.html new file mode 100644 index 000000000..95b9c0f65 --- /dev/null +++ b/doc/core/guessComposition.html @@ -0,0 +1,247 @@ + + + + Description of guessComposition + + + + + + + + + +
Home > core > guessComposition.m
+ + + +

guessComposition +

+ +

PURPOSE ^

+
guessComposition
+ +

SYNOPSIS ^

+
function [model, guessedFor, couldNotGuess]=guessComposition(model, printResults)
+ +

DESCRIPTION ^

+
 guessComposition
+   Attempts to guess the composition of metabolites without information
+   about elemental composition
+
+   model               a model structure
+   printResults        true if the output should be printed (optional, default true)
+
+   model               a model structure with information about elemental
+                       composition added
+   guessedFor          indexes for the metabolites for which a composition
+                       could be guessed
+   couldNotGuess       indexes for the metabolites for which no
+                       composition could be assigned
+
+   This function works in a rather straight forward manner:
+
+   1. Get the metabolites which lack composition and participates in
+   at least one reaction where all other metabolites have composition information
+   2. Loop through them and calculate their composition based on the rest
+   of the involved metabolites. If there are any inconsistencies, so that
+   a given metabolite should have different composition in different
+   equations, then throw an error
+   3. Go to 1
+
+   This simple approach requires that the rest of the metabolites have
+   correct composition information, and that the involved reactions are
+   correct. The function will exit with an error on any inconsistencies,
+   which means that it could also be used as a way of checking the model
+   for errors. Note that just because this exits sucessfully, the
+   calculated compositions could still be wrong (in case that the existing
+   compositions were wrong)
+
+ Usage: [newModel, guessedFor, couldNotGuess]=guessComposition(model, printResults)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 function [model, guessedFor, couldNotGuess]=guessComposition(model, printResults)
+0002 % guessComposition
+0003 %   Attempts to guess the composition of metabolites without information
+0004 %   about elemental composition
+0005 %
+0006 %   model               a model structure
+0007 %   printResults        true if the output should be printed (optional, default true)
+0008 %
+0009 %   model               a model structure with information about elemental
+0010 %                       composition added
+0011 %   guessedFor          indexes for the metabolites for which a composition
+0012 %                       could be guessed
+0013 %   couldNotGuess       indexes for the metabolites for which no
+0014 %                       composition could be assigned
+0015 %
+0016 %   This function works in a rather straight forward manner:
+0017 %
+0018 %   1. Get the metabolites which lack composition and participates in
+0019 %   at least one reaction where all other metabolites have composition information
+0020 %   2. Loop through them and calculate their composition based on the rest
+0021 %   of the involved metabolites. If there are any inconsistencies, so that
+0022 %   a given metabolite should have different composition in different
+0023 %   equations, then throw an error
+0024 %   3. Go to 1
+0025 %
+0026 %   This simple approach requires that the rest of the metabolites have
+0027 %   correct composition information, and that the involved reactions are
+0028 %   correct. The function will exit with an error on any inconsistencies,
+0029 %   which means that it could also be used as a way of checking the model
+0030 %   for errors. Note that just because this exits sucessfully, the
+0031 %   calculated compositions could still be wrong (in case that the existing
+0032 %   compositions were wrong)
+0033 %
+0034 % Usage: [newModel, guessedFor, couldNotGuess]=guessComposition(model, printResults)
+0035 
+0036 if nargin<2
+0037     printResults=true;
+0038 end
+0039 
+0040 %The metabolites for which there is no elemental composition
+0041 originalMissing=unique(model.metNames(cellfun(@isempty,model.metFormulas)));
+0042 guessedFor={};
+0043 
+0044 %This is to keep track of if new metabolite compositions were predicted
+0045 predicted=true;
+0046 while predicted==true
+0047     predicted=false;
+0048     
+0049     %Get the unique names (composition should be independent of
+0050     %compartment) for the metabolites without composition
+0051     metNames=unique(model.metNames(cellfun(@isempty,model.metFormulas)));
+0052     
+0053     %Parse the formulas in the model
+0054     [elements, useMat, exitFlag]=parseFormulas(model.metFormulas, true,false);
+0055     
+0056     for i=1:numel(metNames)
+0057         %Get the metabolites with this name. Not so neat, but this is a
+0058         %fast function anyways
+0059         mets=find(ismember(model.metNames,metNames(i)));
+0060         
+0061         currentComp=[];
+0062         
+0063         %Loop through the metabolites -1: Could not assign due to missing
+0064         %info. -2: Could not assign due to contradiction 1: Composition
+0065         %assigned
+0066         metStatus=-1;
+0067         for j=1:numel(mets)
+0068             %Get the reactions that the metabolite participates in
+0069             [~, I]=find(model.S(mets(j),:));
+0070             if any(I)
+0071                 for k=1:numel(I)
+0072                     %Loop through the reactions and check if all other mets
+0073                     %in them have known composition
+0074                     eqn=model.S(:,I(k));
+0075                     eqn(mets(j))=0;
+0076                     if all(exitFlag(eqn~=0)==1)
+0077                         %This means that all other mets had composition.
+0078                         %Calculate the resulting composition for the
+0079                         %unknown one
+0080                         comp=useMat'*eqn;
+0081                         
+0082                         %This can result in round off errors if there are
+0083                         %stoichiometries with many decimals. Ignore values
+0084                         %below 10^-12
+0085                         comp(abs(comp)<10^-12)=0;
+0086                         
+0087                         %Check if the composition consist of both negative
+0088                         %and positive values. If so, throw an error
+0089                         if all(comp<=0) || all(comp>=0)
+0090                             comp=abs(comp);
+0091                             if isempty(currentComp)
+0092                                 currentComp=comp;
+0093                             end
+0094                             %Also to deal with round off errors
+0095                             if all(abs(currentComp-comp)<10^-10)
+0096                                 metStatus=1;
+0097                             else
+0098                                 metStatus=-2;
+0099                                 break;
+0100                                 
+0101                                 %%Check if there is an inconcistency
+0102                                 %if any(currentComp~=comp)
+0103                                 %    dispEM(['Could not predict composition
+0104                                 %    of ' model.metNames{mets(i)} ],false);
+0105                                 %end
+0106                             end
+0107                         else
+0108                             %Check if there is an inconcistency if
+0109                             %any(currentComp~=comp)
+0110                             %    dispEM(['Could not predict composition of
+0111                             %    ' model.metNames{loopThrough(i)} ],false);
+0112                             %end
+0113                             metStatus=-2;
+0114                             break;
+0115                         end
+0116                     end
+0117                 end
+0118                 %If there was contradictions in one compartment, then abort
+0119                 %for all compartments
+0120                 if metStatus==-2
+0121                     break;
+0122                 end
+0123             else
+0124                 %The metabolite doesn't participate, no composition can be
+0125                 %calculated
+0126                 metStatus=-1;
+0127             end
+0128         end
+0129         %Check status of the metabolite
+0130         switch metStatus
+0131             case -2
+0132                 EM=['Could not predict composition for "' metNames{i} '" due to inconsistencies'];
+0133                 dispEM(EM,false);
+0134             case 1
+0135                 %Calculate and add the composition
+0136                 str=getCompString(elements,comp);
+0137                 model.metFormulas(mets)={str};
+0138                 if printResults==true
+0139                     fprintf(['Predicted composition for "' metNames{i} '" to be ' str '\n']);
+0140                 end
+0141                 
+0142                 %Keep track
+0143                 guessedFor=[guessedFor;metNames(i)];
+0144                 
+0145                 predicted=true; %To loop again
+0146         end
+0147     end
+0148 end
+0149 
+0150 couldNotGuess=setdiff(originalMissing,guessedFor);
+0151 end
+0152 
+0153 %Helper function for getting the composition string
+0154 function str=getCompString(elements,comp)
+0155 str='';
+0156 
+0157 for i=1:numel(comp)
+0158     if comp(i)~=0
+0159         if comp(i)==1
+0160             str=[str elements.abbrevs{i}];
+0161         else
+0162             str=[str elements.abbrevs{i} num2str(comp(i))];
+0163         end
+0164     end
+0165 end
+0166 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/haveFlux.html b/doc/core/haveFlux.html new file mode 100644 index 000000000..4f10e9bc2 --- /dev/null +++ b/doc/core/haveFlux.html @@ -0,0 +1,148 @@ + + + + Description of haveFlux + + + + + + + + + +
Home > core > haveFlux.m
+ + + +

haveFlux +

+ +

PURPOSE ^

+
haveFlux
+ +

SYNOPSIS ^

+
function I=haveFlux(model,cutOff,rxns)
+ +

DESCRIPTION ^

+
 haveFlux
+   Checks which reactions can carry a (positive or negative) flux. Is used
+   as a faster version of getAllowedBounds if it is only interesting
+   whether the reactions can carry a flux or not
+
+ Input:
+   model       a model structure
+   cutOff      the flux value that a reaction has to carry to be
+               identified as positive (optional, default 10^-8)
+   rxns        either a cell array of IDs, a logical vector with the
+               same number of elements as metabolites in the model, or a
+               vector of indexes (optional, default model.rxns)
+
+ Output:
+   I           logical array with true if the corresponding reaction can
+               carry a flux
+
+ If a model has +/- Inf bounds then those are replaced with an arbitary
+ large value of +/- 10000 prior to solving
+
+ Usage: I = haveFlux(model, cutOff, rxns)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function I=haveFlux(model,cutOff,rxns)
+0002 % haveFlux
+0003 %   Checks which reactions can carry a (positive or negative) flux. Is used
+0004 %   as a faster version of getAllowedBounds if it is only interesting
+0005 %   whether the reactions can carry a flux or not
+0006 %
+0007 % Input:
+0008 %   model       a model structure
+0009 %   cutOff      the flux value that a reaction has to carry to be
+0010 %               identified as positive (optional, default 10^-8)
+0011 %   rxns        either a cell array of IDs, a logical vector with the
+0012 %               same number of elements as metabolites in the model, or a
+0013 %               vector of indexes (optional, default model.rxns)
+0014 %
+0015 % Output:
+0016 %   I           logical array with true if the corresponding reaction can
+0017 %               carry a flux
+0018 %
+0019 % If a model has +/- Inf bounds then those are replaced with an arbitary
+0020 % large value of +/- 10000 prior to solving
+0021 %
+0022 % Usage: I = haveFlux(model, cutOff, rxns)
+0023 
+0024 if nargin<2
+0025     cutOff=10^-6;
+0026 end
+0027 if isempty(cutOff)
+0028     cutOff=10^-6;
+0029 end
+0030 if nargin<3
+0031     rxns=model.rxns;
+0032 elseif ~islogical(rxns) && ~isnumeric(rxns)
+0033     rxns=convertCharArray(rxns);
+0034 end
+0035 
+0036 %This is since we're maximizing for the sum of fluxes, which isn't possible
+0037 %when there are infinite bounds
+0038 model.lb(model.lb==-inf)=-10000;
+0039 model.ub(model.ub==inf)=10000;
+0040 
+0041 %Get the reaction IDs. A bit of an awkward way, but fine.
+0042 indexes=getIndexes(model,rxns,'rxns');
+0043 rxns=model.rxns(indexes);
+0044 
+0045 %First remove all dead-end reactions
+0046 smallModel=simplifyModel(model,false,false,true,true);
+0047 
+0048 %Get the indexes of the reactions in the connected model
+0049 indexes=getIndexes(smallModel,intersect(smallModel.rxns,rxns),'rxns');
+0050 J=false(numel(indexes),1);
+0051 mixIndexes=indexes(randperm(numel(indexes)));
+0052 
+0053 %Maximize for all fluxes first in order to get fewer rxns to test
+0054 smallModel.c=ones(numel(smallModel.c),1);
+0055 sol=solveLP(smallModel);
+0056 if ~isempty(sol.x)
+0057     J(abs(sol.x(mixIndexes))>cutOff)=true;
+0058 end
+0059 
+0060 %Loop through and maximize then minimize each rxn if it does not already
+0061 %have a flux
+0062 Z=zeros(numel(smallModel.c),1);
+0063 hsSolOut=[];
+0064 for i=[1 -1]
+0065     for j=1:numel(J)
+0066         if J(j)==false
+0067             %Only minimize for reversible reactions
+0068             if i==1 || smallModel.rev(mixIndexes(j))~=0
+0069                 smallModel.c=Z;
+0070                 smallModel.c(mixIndexes(j))=i;
+0071                 [sol, hsSolOut]=solveLP(smallModel,0,[],hsSolOut);
+0072                 if any(sol.x)
+0073                     J(abs(sol.x(mixIndexes))>cutOff)=true;
+0074                 end
+0075             end
+0076         end
+0077     end
+0078 end
+0079 
+0080 I=ismember(rxns,smallModel.rxns(mixIndexes(J)));
+0081 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/index.html b/doc/core/index.html new file mode 100644 index 000000000..f8ca81dd5 --- /dev/null +++ b/doc/core/index.html @@ -0,0 +1,29 @@ + + + + Index for Directory core + + + + + + + + + + +
< Master indexIndex for core >
+ +

Index for core

+ +

Matlab files in this directory:

+ +
 FSEOFFSEOF
 addExchangeRxnsaddExchangeRxns
 addGenesRavenaddGenesRaven
 addMetsaddMets
 addRxnsaddRxns
 addRxnsGenesMetsaddRxnsGenesMets
 addTransportaddTransport
 analyzeSamplinganalyzeSampling
 buildEquationbuildEquation
 canConsumecanConsume
 canProducecanProduce
 changeGrRuleschangeGrRules
 changeRxnschangeRxns
 checkModelStructcheckModelStruct
 checkProductioncheckProduction
 checkRxncheckRxn
 checkTaskscheckTasks
 compareMultipleModelscompareMultipleModels
 compareRxnsGenesMetsCompscompareRxnsGenesMetsComps
 constructEquationsconstructEquations
 constructSconstructS
 consumeSomethingconsumeSomething
 contractModelcontractModel
 convertCharArrayconvertCharArray
 convertToIrrevconvertToIrrev
 copyToCompscopyToComps
 deleteUnusedGenesdeleteUnusedGenes
 dispEMdispEM
 expandModelexpandModel
 fillGapsfillGaps
 findGeneDeletionsfindGeneDeletions
 findRAVENrootfindRAVENroot
 fitParametersfitParameters
 fitTasksfitTasks
 followChangedfollowChanged
 followFluxesfollowFluxes
 gapReportgapReport
 generateNewIdsgenerateNewIds
 getAllRxnsFromGenesgetAllRxnsFromGenes
 getAllSubGraphsgetAllSubGraphs
 getAllowedBoundsgetAllowedBounds
 getElementalBalancegetElementalBalance
 getEssentialRxnsgetEssentialRxns
 getExchangeRxnsgetExchangeRxns
 getExpressionStructuregetExpressionStructure
 getFluxZgetFluxZ
 getGenesFromGrRulesgetGenesFromGrRules Extract gene list and rxnGeneMat from grRules array.
 getIndexesgetIndexes
 getMetsInCompgetMetsInComp
 getMinNrFluxesgetMinNrFluxes
 getModelFromHomologygetModelFromHomology
 getRxnsInCompgetRxnsInComp
 getTransportRxnsgetTransportRxns
 guessCompositionguessComposition
 haveFluxhaveFlux
 makeSomethingmakeSomething
 mapCompartmentsmapCompartments
 mergeCompartmentsmergeCompartments
 mergeModelsmergeModels
 parallelPoolRAVENhandleParallelRAVEN
 parseFormulasparseFormulas
 parseRxnEquparseRxnEqu
 parseTaskListparseTaskList
 permuteModelpermuteModel
 predictLocalizationpredictLocalization
 printFluxesprintFluxes
 printModelprintModel
 printModelStatsprintModelStats
 printOrangeprintOrange
 randomSamplingrandomSampling
 removeBadRxnsremoveBadRxns
 removeGenesremoveGenes
 removeMetsremoveMets
 removeReactionsremoveReactions
 replaceMetsreplaceMets
 reporterMetabolitesreporterMetabolites
 runDynamicFBArunDynamicFBA
 runPhenotypePhasePlanerunPhenotypePhasePlane
 runProductionEnveloperunProductionEnvelope
 runRobustnessAnalysisrunRobustnessAnalysis
 runSimpleOptKnockrunSimpleOptKnock
 setExchangeBoundssetExchangeBounds
 setParamsetParam
 simplifyModelsimplifyModel
 sortModelsortModel
 standardizeGrRulesstandardizeGrRules
+ + + + +
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/makeSomething.html b/doc/core/makeSomething.html new file mode 100644 index 000000000..bbf9b56e4 --- /dev/null +++ b/doc/core/makeSomething.html @@ -0,0 +1,275 @@ + + + + Description of makeSomething + + + + + + + + + +
Home > core > makeSomething.m
+ + + +

makeSomething +

+ +

PURPOSE ^

+
makeSomething
+ +

SYNOPSIS ^

+
function [solution, metabolite]=makeSomething(model,ignoreMets,isNames,minNrFluxes,allowExcretion,params,ignoreIntBounds)
+ +

DESCRIPTION ^

+
 makeSomething
+   Tries to excrete any metabolite using as few reactions as possible.
+   The intended use is when you want to make sure that you model cannot
+   synthesize anything from nothing. It is then a faster way than to use
+   checkProduction or canProduce
+
+   model           a model structure
+   ignoreMets      either a cell array of metabolite IDs, a logical vector
+                   with the same number of elements as metabolites in the model,
+                   of a vector of indexes for metabolites to exclude from
+                   this analysis (optional, default [])
+   isNames         true if the supplied mets represent metabolite names
+                   (as opposed to IDs). This is a way to delete
+                   metabolites in several compartments at once without
+                   knowing the exact IDs. This only works if ignoreMets
+                   is a cell array (optional, default false)
+   minNrFluxes     solves the MILP problem of minimizing the number of
+                   fluxes instead of the sum. Slower, but can be
+                   used if the sum gives too many fluxes (optional, default
+                   false)
+   allowExcretion  allow for excretion of all other metabolites (optional,
+                   default true)
+   params          *obsolete option*
+   ignoreIntBounds    true if internal bounds (including reversibility)
+                   should be ignored. Exchange reactions are not affected.
+                   This can be used to find unbalanced solutions which are
+                   not possible using the default constraints (optional,
+                   default false)
+
+   solution        flux vector for the solution
+   metabolite      the index of the metabolite(s) which was excreted. If
+                   possible only one metabolite is reported, but there are
+                   situations where metabolites can only be excreted in
+                   pairs (or more)
+
+   NOTE: This works by forcing at least 1 unit of "any metabolites" to be
+   produced and then minimize for the sum of fluxes. If more than one
+   metabolite is produced, it picks one of them to be produced and then
+   minimizes for the sum of fluxes.
+
+ Usage: [solution, metabolite]=makeSomething(model,ignoreMets,isNames,...
+           minNrFluxes,allowExcretion,params,ignoreIntBounds)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function [solution, metabolite]=makeSomething(model,ignoreMets,isNames,minNrFluxes,allowExcretion,params,ignoreIntBounds)
+0002 % makeSomething
+0003 %   Tries to excrete any metabolite using as few reactions as possible.
+0004 %   The intended use is when you want to make sure that you model cannot
+0005 %   synthesize anything from nothing. It is then a faster way than to use
+0006 %   checkProduction or canProduce
+0007 %
+0008 %   model           a model structure
+0009 %   ignoreMets      either a cell array of metabolite IDs, a logical vector
+0010 %                   with the same number of elements as metabolites in the model,
+0011 %                   of a vector of indexes for metabolites to exclude from
+0012 %                   this analysis (optional, default [])
+0013 %   isNames         true if the supplied mets represent metabolite names
+0014 %                   (as opposed to IDs). This is a way to delete
+0015 %                   metabolites in several compartments at once without
+0016 %                   knowing the exact IDs. This only works if ignoreMets
+0017 %                   is a cell array (optional, default false)
+0018 %   minNrFluxes     solves the MILP problem of minimizing the number of
+0019 %                   fluxes instead of the sum. Slower, but can be
+0020 %                   used if the sum gives too many fluxes (optional, default
+0021 %                   false)
+0022 %   allowExcretion  allow for excretion of all other metabolites (optional,
+0023 %                   default true)
+0024 %   params          *obsolete option*
+0025 %   ignoreIntBounds    true if internal bounds (including reversibility)
+0026 %                   should be ignored. Exchange reactions are not affected.
+0027 %                   This can be used to find unbalanced solutions which are
+0028 %                   not possible using the default constraints (optional,
+0029 %                   default false)
+0030 %
+0031 %   solution        flux vector for the solution
+0032 %   metabolite      the index of the metabolite(s) which was excreted. If
+0033 %                   possible only one metabolite is reported, but there are
+0034 %                   situations where metabolites can only be excreted in
+0035 %                   pairs (or more)
+0036 %
+0037 %   NOTE: This works by forcing at least 1 unit of "any metabolites" to be
+0038 %   produced and then minimize for the sum of fluxes. If more than one
+0039 %   metabolite is produced, it picks one of them to be produced and then
+0040 %   minimizes for the sum of fluxes.
+0041 %
+0042 % Usage: [solution, metabolite]=makeSomething(model,ignoreMets,isNames,...
+0043 %           minNrFluxes,allowExcretion,params,ignoreIntBounds)
+0044 
+0045 if nargin<2
+0046     ignoreMets=[];
+0047 elseif ~islogical(ignoreMets) && ~isnumeric(ignoreMets)
+0048     ignoreMets=convertCharArray(ignoreMets);
+0049 end
+0050 if nargin<3
+0051     isNames=false;
+0052 end
+0053 if nargin<4
+0054     minNrFluxes=false;
+0055 end
+0056 if nargin<5
+0057     allowExcretion=true;
+0058 end
+0059 if nargin<6
+0060     params.relGap=0.8;
+0061 end
+0062 if nargin<7
+0063     ignoreIntBounds=false;
+0064 end
+0065 
+0066 if isNames==true && ~isempty(ignoreMets)
+0067     %Check that metsToRemove is a cell array
+0068     if iscellstr(ignoreMets)==false
+0069         EM='Must supply a cell array of strings if isNames=true';
+0070         dispEM(EM);
+0071     end
+0072 end
+0073 
+0074 if isNames==false
+0075     indexesToIgnore=getIndexes(model,ignoreMets,'mets');
+0076 else
+0077     indexesToIgnore=[];
+0078     for i=1:numel(ignoreMets)
+0079         indexesToIgnore=[indexesToIgnore;find(strcmp(ignoreMets(i),model.metNames))];
+0080     end
+0081 end
+0082 
+0083 %Allow for excretion of all metabolites
+0084 if allowExcretion==true
+0085     model.b=[model.b(:,1) inf(numel(model.mets),1)];
+0086 end
+0087 
+0088 %Change all internal reactions to be unbounded in both directions
+0089 if ignoreIntBounds==true
+0090     [~, I]=getExchangeRxns(model);
+0091     nonExc=true(numel(model.rxns),1);
+0092     nonExc(I)=false;
+0093     model=setParam(model,'lb',nonExc,-1000);
+0094     model=setParam(model,'ub',nonExc,1000);
+0095     model=setParam(model,'rev',nonExc,1);
+0096 end
+0097 
+0098 solution=[];
+0099 metabolite=[];
+0100 
+0101 nRxns=numel(model.rxns);
+0102 nMets=numel(model.mets);
+0103 
+0104 %Add excretion reactions for all metabolites
+0105 model.S=[model.S speye(nMets)*-1];
+0106 
+0107 %Add so that they all produce a fake metabolite
+0108 model.S=[model.S;[sparse(1,nRxns) ones(1,nMets)]];
+0109 
+0110 %Change so that the ignoreMets have a coefficient 0 in their reactions.
+0111 %Does not remove the actual reaction to make mapping easier later
+0112 model.S(:,indexesToIgnore+nRxns)=0;
+0113 
+0114 %Add an excretion reaction for this last fake metabolite
+0115 model.S(size(model.S,1),size(model.S,2)+1)=-1;
+0116 model.b=[model.b;zeros(1,size(model.b,2))];
+0117 model.lb=[model.lb;zeros(nMets,1);1];
+0118 model.ub=[model.ub;inf(nMets+1,1)];
+0119 model.rev=[model.rev;zeros(nMets+1,1)];
+0120 model.c=zeros(size(model.S,2),1);
+0121 
+0122 %Add padding to the reaction annotation to prevent an error in solveLP
+0123 padding=1:numel(model.rev);
+0124 padding=num2cell(padding)';
+0125 padding=cellfun(@num2str,padding,'uniformoutput',false);
+0126 model.rxns=padding;
+0127 model.rxnNames=padding;
+0128 model.eccodes=padding;
+0129 model.rxnMiriams=padding;
+0130 model.grRules=padding;
+0131 if isfield(model,'genes')
+0132     model.rxnGeneMat=sparse(numel(model.rev),numel(model.genes));
+0133 end
+0134 model.subSystems=padding;
+0135 model.rxnFrom=padding;
+0136 model.rxnComps=ones(numel(model.rev),1);
+0137 model.rxnNotes=padding;
+0138 model.rxnReferences=padding;
+0139 model.rxnConfidenceScores=NaN(numel(model.rev),1);
+0140 
+0141 sol=solveLP(model,1);
+0142 if any(sol.x)
+0143     %It could be that several metabolites were produced in order to get the
+0144     %best solution. The setdiff is to avoid including the last fake
+0145     %metabolite
+0146     I=setdiff(find(sol.x(nRxns+1:end)>0.1),size(model.S,1));
+0147     
+0148     if any(I) %This should always be true
+0149         %Change the coefficients so that only the first is produced. This
+0150         %is not always possible, but it is tested for since it it results
+0151         %in more easily interpretable results
+0152         
+0153         oldS=model.S;
+0154         foundSingle=false;
+0155         %Test if any of the metabolites could be produced on their own
+0156         for i=1:numel(I)
+0157             model.S=oldS;
+0158             J=nRxns+1:numel(model.lb)-1;
+0159             J(I(i))=[];
+0160             model.S(:,J)=0;
+0161             sol=solveLP(model);
+0162             if any(sol.x)
+0163                 foundSingle=true;
+0164                 break;
+0165             end
+0166         end
+0167         %This means that there was no metabolite which could be produced on
+0168         %its own. Then let all the produceable metabolites be produced.
+0169         if foundSingle==false
+0170             model.S=oldS;
+0171         end
+0172         if minNrFluxes==true
+0173             %Has to add names for the rxns to prevent an error in
+0174             %minNrFluxes
+0175             model.rxns=cell(numel(model.lb),1);
+0176             model.rxns(:)=sprintfc('tmp_%d',1:numel(model.lb));
+0177             model.mets=cell(size(model.b,1),1);
+0178             model.mets(:)={'TEMP'};
+0179             sol=solveLP(model,3,params);
+0180         else
+0181             sol=solveLP(model,1);
+0182         end
+0183         solution=sol.x(1:nRxns);
+0184         metabolite=find(sol.x(nRxns+1:end-1)>0.1);
+0185     end
+0186 end
+0187 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/mapCompartments.html b/doc/core/mapCompartments.html new file mode 100644 index 000000000..1af9de4d3 --- /dev/null +++ b/doc/core/mapCompartments.html @@ -0,0 +1,214 @@ + + + + Description of mapCompartments + + + + + + + + + +
Home > core > mapCompartments.m
+ + + +

mapCompartments +

+ +

PURPOSE ^

+
mapCompartments
+ +

SYNOPSIS ^

+
function geneScoreStructure=mapCompartments(geneScoreStructure,varargin)
+ +

DESCRIPTION ^

+
 mapCompartments
+   Maps compartments in the geneScoreStructure. This is used if you do not
+   want a models that uses all of the compartment from the predictor. This
+   function will then let you define rules on how the compartments should
+   be merged.
+
+   Any number of rules could be defined as consecutive strings or in a cell array.
+   'comp1'             comp1 should be kept in the structure
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function geneScoreStructure=mapCompartments(geneScoreStructure,varargin)
+0002 % mapCompartments
+0003 %   Maps compartments in the geneScoreStructure. This is used if you do not
+0004 %   want a models that uses all of the compartment from the predictor. This
+0005 %   function will then let you define rules on how the compartments should
+0006 %   be merged.
+0007 %
+0008 %   Any number of rules could be defined as consecutive strings or in a cell array.
+0009 %   'comp1'             comp1 should be kept in the structure
+0010 
+0011 %   'comp1=comp2'       The scores in comp2 are merged to comp1 and comp2 is
+0012 %                       removed from the structure. This automatically
+0013 %                       keeps comp1 in the structure
+0014 
+0015 %   'comp1=comp2 comp3' The scores in comp2 and comp3 are merged to comp1
+0016 %                       and comp2 & comp2 are removed from the structure.
+0017 %                       This automatically keeps comp1 in the structure
+0018 
+0019 %   'comp1 comp2=comp3' The scores in comp3 are split between comp1 and
+0020 %                       comp2. This automatically keeps comp1 and comp2 in
+0021 %                       the structure
+0022 
+0023 %   'comp1=other'       The scores in any compartment not included are
+0024 %                       merged to comp1. This is applied after all other
+0025 %                       rules.
+0026 %
+0027 %   When one compartment is merged to another the resulting scores will be
+0028 %   the best for each gene in either of the compartments. In the case where
+0029 %   one compartment is split among several, the scores for the compartment
+0030 %   to be merged is weighted with the number of compartments to split to.
+0031 %
+0032 %   Example: The predictor you use give prediction for Extracellular,
+0033 %   Cytosol, Nucleus, Peroxisome, Mitochondria, ER, and Lysosome. You want to
+0034 %   have a model with Extracellular, Cytosol, Mitochondria, and Peroxisome
+0035 %   where Lysosome is merged with Peroxisome and all other compartments
+0036 %   are merged to the Cytosol.
+0037 %
+0038 %   GSS=mapCompartments(GSS,'Extracellular','Mitochondria','Peroxisome=Lyso
+0039 %   some','Cytosol=other');
+0040 %
+0041 %   geneScoreStructure  a structure to be used in predictLocalization
+0042 %
+0043 % Usage: geneScoreStructure=mapCompartments(geneScoreStructure,varargin)
+0044 
+0045 varargin=upper(varargin);
+0046 
+0047 %First find the compartment that will end up in the final structure. They
+0048 %are the ones that stand alone or are to the left of some '='
+0049 toKeep={};
+0050 toMerge={};
+0051 I=regexp(varargin,'=','split');
+0052 for i=1:numel(varargin)
+0053     if numel(I{i})==1
+0054         toKeep=[toKeep;I{i}];
+0055     else
+0056         J=regexp(I{i}(1),' ','split');
+0057         K=regexp(I{i}(2),' ','split');
+0058         toKeep=[toKeep;J{1}(:)];
+0059         toMerge=[toMerge;K{1}(:)];
+0060     end
+0061 end
+0062 
+0063 %Check that there are no compartment that should both be merged and kept
+0064 if ~isempty(intersect(toKeep,toMerge))
+0065     EM='There are inconsistencies where one or more compartment(s) should be both kept and merged to another';
+0066     dispEM(EM);
+0067 end
+0068 
+0069 %Check that there are no compartments in the rules that are not in the
+0070 %geneScoreStructure.
+0071 uComps=upper(geneScoreStructure.compartments);
+0072 J=[uComps,{'OTHER'}];
+0073 
+0074 if ~isempty(setdiff([toKeep;toMerge],J))
+0075     EM='There are compartment in the rules that are not in geneScoreStructure.compartments';
+0076     dispEM(EM);
+0077 end
+0078 
+0079 %Loop through it again and do the mapping
+0080 otherIndex=[]; %This stores the rule which maps 'other'.
+0081 
+0082 for i=1:numel(I)
+0083     if numel(I{i})>1
+0084         %Get the compartment indexes that should be mapped
+0085         J=regexp(I{i}(2),' ','split');
+0086         if strcmpi(J{1},'other')
+0087             otherIndex=i;
+0088             continue;
+0089         end
+0090         [k, K]=ismember(J{1},uComps);
+0091         
+0092         %And to where they should be mapped
+0093         J=regexp(I{i}(1),' ','split');
+0094         [l, L]=ismember(J{1},uComps);
+0095         
+0096         %It's not allowed to have rules like A B=C D
+0097         if numel(K)>1 && numel(L)>1
+0098             EM='It is not allowed to have rules like "A B=C D" (map more than one compartment to more than one compartment)';
+0099             dispEM(EM);
+0100         end
+0101         
+0102         if ~all(k) || ~all(l)
+0103             EM='Error in mapping. This most likely means that some compartment(s) are mapped to different compartments in different rules. Use A B=C if you want to map C to several compartments';
+0104             dispEM(EM);
+0105         end
+0106         
+0107         %Get the sum of the scores for the compartments that should be
+0108         %merged to something else
+0109         S=max(geneScoreStructure.scores(:,K),[],2);
+0110         for j=1:numel(L)
+0111             %If the scores are mapped to several different compartments
+0112             %then split the scores between them
+0113             geneScoreStructure.scores(:,L(j))=max(geneScoreStructure.scores(:,L(j)),S./numel(L));
+0114         end
+0115         
+0116         %Remove the comparement that were merged
+0117         geneScoreStructure.compartments(K)=[];
+0118         geneScoreStructure.scores(:,K)=[];
+0119         uComps(K)=[];
+0120     end
+0121 end
+0122 
+0123 %Then check if there are remaining compartments that should be removed or
+0124 %mapped as 'other'
+0125 J=find(~ismember(uComps,toKeep));
+0126 if any(J)
+0127     if any(otherIndex)
+0128         K=regexp(I{otherIndex}(1),' ','split');
+0129         [l, L]=ismember(K{1},uComps);
+0130         if l==1 && numel(l)==1
+0131             S=max(geneScoreStructure.scores(:,J),[],2);
+0132             geneScoreStructure.scores(:,L)=max(geneScoreStructure.scores(:,L),S);
+0133         else
+0134             EM='Could not map "other" to more than one compartment';
+0135             dispEM(EM);
+0136         end
+0137     else
+0138         EM='There are compartments that are not defined if they should be kept or removed. Use "A=other" or define more rules if you do not want them to be deleted';
+0139         dispEM(EM,false);
+0140     end
+0141     
+0142     %Remove the comparement that were merged
+0143     geneScoreStructure.compartments(J)=[];
+0144     geneScoreStructure.scores(:,J)=[];
+0145 end
+0146 
+0147 %Renormalize
+0148 I=max(geneScoreStructure.scores,[],2);
+0149 geneScoreStructure.scores=bsxfun(@times, geneScoreStructure.scores, 1./I);
+0150 
+0151 %If there are genes that have score 0 in all compartments, remove them and
+0152 %print a warning.
+0153 I=find(isnan(geneScoreStructure.scores(:,1))); %Only looks a the first colum as it will be the same for the other ones
+0154 if any(I)
+0155     EM='The following genes had score 0.0 in all compartments. They have been removed from the structure. Consider using more rules or "A=other" in order to prevent this:';
+0156     dispEM(EM,false,geneScoreStructure.genes(I));
+0157     geneScoreStructure.scores(I,:)=[];
+0158     geneScoreStructure.genes(I)=[];
+0159 end
+0160 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/mergeCompartments.html b/doc/core/mergeCompartments.html new file mode 100644 index 000000000..5754bdbdc --- /dev/null +++ b/doc/core/mergeCompartments.html @@ -0,0 +1,209 @@ + + + + Description of mergeCompartments + + + + + + + + + +
Home > core > mergeCompartments.m
+ + + +

mergeCompartments +

+ +

PURPOSE ^

+
mergeCompartments
+ +

SYNOPSIS ^

+
function [model, deletedRxns, duplicateRxns]=mergeCompartments(model,keepUnconstrained,deleteRxnsWithOneMet,distReverse)
+ +

DESCRIPTION ^

+
 mergeCompartments
+   Merge all compartments in a model
+
+   model                 a model structure
+   keepUnconstrained     keep metabolites that are unconstrained in a
+                         'unconstrained' compartment. If these are merged the
+                         exchange reactions will most often be deleted (optional,
+                         default false)
+   deleteRxnsWithOneMet  delete reactions with only one metabolite. These
+                         reactions come from reactions such as A[c] + B[c]
+                         => A[m]. In some models hydrogen is balanced around
+                         each membrane with reactions like this (optional,
+                         default false)
+   distReverse           distinguish reactions with same metabolites but
+                         different reversibility as different reactions
+                         (optional, default true)
+
+   model                 a model with all reactions located to one compartment
+   deletedRxns           reactions that were deleted because of only
+                         having one metabolite after merging
+   duplicateRxns         identical reactions that occurred in different
+                         compartments and were deleted because they turned
+                         to be duplicated after merging
+
+   Merges all compartments into one 's' compartment (for 'System'). This can
+   be useful for example to ensure that there are metabolic capabilities to
+   synthesize all metabolites.
+
+   NOTE: If the metabolite IDs reflect the compartment that they are in
+   the IDs may no longer be representative.
+
+ Usage: [model, deletedRxns, duplicateRxns]=mergeCompartments(model,keepUnconstrained,deleteRxnsWithOneMet,distReverse)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function [model, deletedRxns, duplicateRxns]=mergeCompartments(model,keepUnconstrained,deleteRxnsWithOneMet,distReverse)
+0002 % mergeCompartments
+0003 %   Merge all compartments in a model
+0004 %
+0005 %   model                 a model structure
+0006 %   keepUnconstrained     keep metabolites that are unconstrained in a
+0007 %                         'unconstrained' compartment. If these are merged the
+0008 %                         exchange reactions will most often be deleted (optional,
+0009 %                         default false)
+0010 %   deleteRxnsWithOneMet  delete reactions with only one metabolite. These
+0011 %                         reactions come from reactions such as A[c] + B[c]
+0012 %                         => A[m]. In some models hydrogen is balanced around
+0013 %                         each membrane with reactions like this (optional,
+0014 %                         default false)
+0015 %   distReverse           distinguish reactions with same metabolites but
+0016 %                         different reversibility as different reactions
+0017 %                         (optional, default true)
+0018 %
+0019 %   model                 a model with all reactions located to one compartment
+0020 %   deletedRxns           reactions that were deleted because of only
+0021 %                         having one metabolite after merging
+0022 %   duplicateRxns         identical reactions that occurred in different
+0023 %                         compartments and were deleted because they turned
+0024 %                         to be duplicated after merging
+0025 %
+0026 %   Merges all compartments into one 's' compartment (for 'System'). This can
+0027 %   be useful for example to ensure that there are metabolic capabilities to
+0028 %   synthesize all metabolites.
+0029 %
+0030 %   NOTE: If the metabolite IDs reflect the compartment that they are in
+0031 %   the IDs may no longer be representative.
+0032 %
+0033 % Usage: [model, deletedRxns, duplicateRxns]=mergeCompartments(model,keepUnconstrained,deleteRxnsWithOneMet,distReverse)
+0034 
+0035 if nargin<2
+0036     keepUnconstrained=false;
+0037 end
+0038 if nargin<3
+0039     deleteRxnsWithOneMet=false;
+0040 end
+0041 if nargin<4
+0042     distReverse=true;
+0043 end
+0044 
+0045 if ~isfield(model,'unconstrained')
+0046     keepUnconstrained=false;
+0047 end
+0048 
+0049 %Keep track of which reactions only contained one metabolite before the
+0050 %merging as they are probable exchange reactions.
+0051 if deleteRxnsWithOneMet==true
+0052     reservedRxns=model.rxns(sum(model.S~=0)==1);
+0053     if ~isempty(reservedRxns) && isfield(model,'unconstrained')
+0054         %If there is no unconstrained field these reactions are probably
+0055         %exchange reactions and shall be kept. If not then print a warning
+0056         EM='There are reactions with only one metabolite. Cannot determine whether they are exchange reactions since there is no unconstrained field';
+0057         dispEM(EM,false);
+0058     end
+0059 end
+0060 
+0061 %Loop through each metabolite, and if it is not unconstrained then change
+0062 %the S matrix to use the metabolite with the lowest index in model.comps
+0063 %instead
+0064 uNames=unique(model.metNames);
+0065 for i=1:numel(uNames)
+0066     %Find all metabolites with this name..
+0067     I=ismember(model.metNames,uNames(i));
+0068     
+0069     %Find the first of those that is not unconstrained. This is the one
+0070     %that the other "un-unconstrained" should be changed to.
+0071     if keepUnconstrained==true
+0072         mergeTo=find(I & model.unconstrained==false,1);
+0073         
+0074         %This could happen if there is only one metabolite and it is
+0075         %unconstrained
+0076         if isempty(mergeTo)
+0077             continue;
+0078         end
+0079     else
+0080         mergeTo=find(I,1);
+0081     end
+0082     I(mergeTo)=false; %Do not do anything for itself
+0083     I=find(I);
+0084     
+0085     %Go through each of the metabolites with this name and update them to
+0086     %mergeTo
+0087     for j=1:numel(I)
+0088         if keepUnconstrained==true && model.unconstrained(I(j))==true
+0089             continue;
+0090         end
+0091         %Update the S matrix
+0092         model.S(mergeTo,:)=model.S(mergeTo,:)+model.S(I(j),:);
+0093         model.S(I(j),:)=0;
+0094     end
+0095 end
+0096 
+0097 %Remove all metabolites that are no longer used (with a bit of a trick)
+0098 model=removeReactions(model,{},true);
+0099 
+0100 %Update all mets so that they are in compartment "s" with id "1"
+0101 model.compNames={'System'};
+0102 model.comps={'s'};
+0103 model.compOutside={''};
+0104 model.metComps=ones(numel(model.mets),1);
+0105 
+0106 %Add exchange mets to another compartment "b" with id "2"
+0107 if keepUnconstrained==true
+0108     model.compNames=[model.compNames; {'Unconstrained'}];
+0109     model.comps=[model.comps; {'b'}];
+0110     model.compOutside=[model.compOutside; {'s'}];
+0111     model.metComps(model.unconstrained~=0)=2;
+0112 end
+0113 
+0114 %Transport reactions on the form A <=> B will have been deleted by the
+0115 %merging. Remove those reactions
+0116 model=removeMets(model,{},false,true,true);
+0117 
+0118 if deleteRxnsWithOneMet==true
+0119     I=model.rxns(sum(model.S~=0)==1);
+0120     
+0121     %Delete the reactions that contain only one metabolite after the
+0122     %merging but not before
+0123     deletedRxns=setdiff(I,reservedRxns);
+0124     model=removeReactions(model,deletedRxns,true,true);
+0125 else
+0126     deletedRxns={};
+0127 end
+0128 
+0129 %And then finally merge the identical reactions
+0130 [model, ~, duplicateRxns]=contractModel(model,distReverse);
+0131 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/mergeModels.html b/doc/core/mergeModels.html new file mode 100644 index 000000000..577f82d32 --- /dev/null +++ b/doc/core/mergeModels.html @@ -0,0 +1,720 @@ + + + + Description of mergeModels + + + + + + + + + +
Home > core > mergeModels.m
+ + + +

mergeModels +

+ +

PURPOSE ^

+
mergeModels
+ +

SYNOPSIS ^

+
function model=mergeModels(models,metParam,supressWarnings,copyToComps)
+ +

DESCRIPTION ^

+
 mergeModels
+   Merges models into one model structure. Reactions are added without any
+   checks, so duplicate reactions might appear. Metabolites are matched by
+   their name and compartment (metaboliteName[comp]), while genes are
+   matched by their name.
+
+ Input:
+   models          a cell array with model structures
+   metParam        string metabolite name ('metNames') or ID ('mets') are
+                   used for matching (optional, default 'metNames')
+   supressWarnings logical whether warnings should be supressed (optional,
+                   default false)
+   copyToComps     logical whether mergeModels is run via copyToComps
+                   (optional, default false)
+
+ Output:
+   model           a model structure with the merged model. Follows the
+                   structure of normal models but also has 'rxnFrom/
+                   metFrom/geneFrom' fields to indicate from which model
+                   each reaction/metabolite/gene was taken. If the model
+                   already has 'rxnFrom/metFrom/geneFrom' fields, then
+                   these fields are not modified.
+
+ Usage: model=mergeModels(models)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function model=mergeModels(models,metParam,supressWarnings,copyToComps)
+0002 % mergeModels
+0003 %   Merges models into one model structure. Reactions are added without any
+0004 %   checks, so duplicate reactions might appear. Metabolites are matched by
+0005 %   their name and compartment (metaboliteName[comp]), while genes are
+0006 %   matched by their name.
+0007 %
+0008 % Input:
+0009 %   models          a cell array with model structures
+0010 %   metParam        string metabolite name ('metNames') or ID ('mets') are
+0011 %                   used for matching (optional, default 'metNames')
+0012 %   supressWarnings logical whether warnings should be supressed (optional,
+0013 %                   default false)
+0014 %   copyToComps     logical whether mergeModels is run via copyToComps
+0015 %                   (optional, default false)
+0016 %
+0017 % Output:
+0018 %   model           a model structure with the merged model. Follows the
+0019 %                   structure of normal models but also has 'rxnFrom/
+0020 %                   metFrom/geneFrom' fields to indicate from which model
+0021 %                   each reaction/metabolite/gene was taken. If the model
+0022 %                   already has 'rxnFrom/metFrom/geneFrom' fields, then
+0023 %                   these fields are not modified.
+0024 %
+0025 % Usage: model=mergeModels(models)
+0026 
+0027 arguments
+0028     models;
+0029     metParam {emptyOrTextScalar} = "metNames"
+0030     supressWarnings {emptyOrLogicalScalar} = false
+0031     copyToComps {emptyOrLogicalScalar} = false
+0032 end
+0033 
+0034 metParam = char(metParam);
+0035 
+0036 %Just return the model
+0037 if numel(models)<=1
+0038     model=models{1};
+0039     return;
+0040 end
+0041 
+0042 hasMetFrom  = cellfun(@(s) isfield(s,'metFrom'), models);
+0043 hasGeneFrom = cellfun(@(s) isfield(s,'geneFrom'), models);
+0044 hasRxnFrom  = cellfun(@(s) isfield(s,'rxnFrom'), models);
+0045 
+0046 for i = 1:numel(models)
+0047     if copyToComps
+0048         if hasMetFrom(1)
+0049             models{2}.metFrom = repmat({''},numel(models{i}.mets),1);
+0050         end
+0051     elseif ~any(hasMetFrom)
+0052         models{i}.metFrom = repmat({models{i}.id},numel(models{i}.mets),1);
+0053     elseif ~hasMetFrom(i)
+0054         models{i}.metFrom = repmat({''},numel(models{i}.mets),1);
+0055     end
+0056     if copyToComps
+0057         if hasRxnFrom(1)
+0058             models{2}.rxnFrom = repmat({''},numel(models{i}.rxns),1);
+0059         end
+0060     elseif ~any(hasRxnFrom)
+0061         models{i}.rxnFrom = repmat({models{i}.id},numel(models{i}.rxns),1);
+0062     elseif ~hasRxnFrom(i)
+0063         models{i}.rxnFrom = repmat({''},numel(models{i}.rxns),1);
+0064     end
+0065     if copyToComps
+0066         if hasGeneFrom(1)
+0067             models{2}.geneFrom = repmat({''},numel(models{i}.genes),1);
+0068         end
+0069     elseif ~any(hasGeneFrom) && any(cellfun(@(s) isfield(s,'genes'), models))
+0070         models{i}.geneFrom = repmat({models{i}.id},numel(models{i}.genes),1);
+0071     elseif ~hasGeneFrom(i)
+0072         models{i}.geneFrom = repmat({''},numel(models{i}.genes),1);
+0073     end
+0074 end
+0075 
+0076 %Add new functionality in the order specified in models
+0077 model=models{1};
+0078 model.id='MERGED';
+0079 model.name='';
+0080 
+0081 if isfield(model,'equations')
+0082     model=rmfield(model,'equations');
+0083 end
+0084 
+0085 for i=1:numel(models)
+0086     if isfield(models{i},'subSystems')
+0087         models{i}.subSystems = cellfun(@(x) {x}, models{i}.subSystems, 'uni', 0);
+0088     end
+0089 end
+0090 for i=2:numel(models)
+0091     %Add the model id to the rxn id id it already exists in the model (id
+0092     %have to be unique) This is because it makes a '[]' string if no new
+0093     %reactions
+0094     if ~isempty(models{i}.rxns)
+0095         I=ismember(models{i}.rxns,model.rxns);
+0096         models{i}.rxns(I)=strcat(models{i}.rxns(I),['_' models{i}.id]);
+0097     end
+0098     
+0099     %Make sure that there are no conflicting reaction ids
+0100     [~, ~, conflicting]=intersect(model.rxns,models{i}.rxns);
+0101     
+0102     if ~isempty(conflicting)
+0103         printString=cell(numel(conflicting),1);
+0104         for j=1:numel(conflicting)
+0105             printString{j}=['Old: ' models{i}.rxns{conflicting(j)} ' New: ' models{i}.rxns{conflicting(j)} '_' models{i}.id];
+0106             models{i}.rxns{conflicting(j)}=[models{i}.rxns{conflicting(j)} '_' models{i}.id];
+0107         end
+0108         if supressWarnings==false
+0109             EM=['The following reaction IDs in ' models{i}.id ' are already present in the model and were renamed:'];
+0110             dispEM(EM,false,printString);
+0111             fprintf('\n');
+0112         end
+0113     end
+0114     
+0115     %Add all static stuff
+0116     if any(hasRxnFrom) || (~copyToComps && ~any(hasRxnFrom))
+0117         model.rxnFrom  = [model.rxnFrom;  models{i}.rxnFrom];
+0118     end
+0119     model.rxns     = [model.rxns;     models{i}.rxns];
+0120     model.rxnNames = [model.rxnNames; models{i}.rxnNames];
+0121     model.lb       = [model.lb;       models{i}.lb];
+0122     model.ub       = [model.ub;       models{i}.ub];
+0123     model.c        = [model.c;        models{i}.c];
+0124     model.rev      = [model.rev;      models{i}.rev];
+0125     
+0126     if isfield(models{i},'subSystems')
+0127         if isfield(model,'subSystems')
+0128             model.subSystems=[model.subSystems;models{i}.subSystems];
+0129         else
+0130             emptySubSystem=cell(numel(model.rxns)-numel(models{i}.rxns),1);
+0131             emptySubSystem(:)={''};
+0132             emptySubSystem=cellfun(@(x) cell(0,0),emptySubSystem,'UniformOutput',false);
+0133             model.subSystems=[emptySubSystem;models{i}.subSystems];
+0134         end
+0135     else
+0136         if isfield(model,'subSystems')
+0137             emptySubSystem=cell(numel(models{i}.rxns),1);
+0138             emptySubSystem(:)={''};
+0139             emptySubSystem=cellfun(@(x) cell(0,0),emptySubSystem,'UniformOutput',false);
+0140             model.subSystems=[model.subSystems;emptySubSystem];
+0141         end
+0142     end
+0143     
+0144     if isfield(models{i},'eccodes')
+0145         if isfield(model,'eccodes')
+0146             model.eccodes=[model.eccodes;models{i}.eccodes];
+0147         else
+0148             emptyEC=cell(numel(model.rxns)-numel(models{i}.rxns),1);
+0149             emptyEC(:)={''};
+0150             model.eccodes=[emptyEC;models{i}.eccodes];
+0151         end
+0152     else
+0153         if isfield(model,'eccodes')
+0154             emptyEC=cell(numel(models{i}.rxns),1);
+0155             emptyEC(:)={''};
+0156             model.eccodes=[model.eccodes;emptyEC];
+0157         end
+0158     end
+0159     
+0160     if isfield(models{i},'rxnMiriams')
+0161         if isfield(model,'rxnMiriams')
+0162             model.rxnMiriams=[model.rxnMiriams;models{i}.rxnMiriams];
+0163         else
+0164             model.rxnMiriams=[cell(numel(model.rxns)-numel(models{i}.rxns),1);models{i}.rxnMiriams];
+0165         end
+0166     else
+0167         if isfield(model,'rxnMiriams')
+0168             model.rxnMiriams=[model.rxnMiriams;cell(numel(models{i}.rxns),1)];
+0169         end
+0170     end
+0171     
+0172     if isfield(models{i},'rxnNotes')
+0173         if isfield(model,'rxnNotes')
+0174             model.rxnNotes=[model.rxnNotes;models{i}.rxnNotes];
+0175         else
+0176             emptyNotes=cell(numel(model.rxns)-numel(models{i}.rxns),1);
+0177             emptyNotes(:)={''};
+0178             model.rxnNotes=[emptyNotes;models{i}.rxnNotes];
+0179         end
+0180     else
+0181         if isfield(model,'rxnNotes')
+0182             emptyNotes=cell(numel(models{i}.rxns),1);
+0183             emptyNotes(:)={''};
+0184             model.rxnNotes=[model.rxnNotes;emptyNotes];
+0185         end
+0186     end
+0187     
+0188     if isfield(models{i},'rxnReferences')
+0189         if isfield(model,'rxnReferences')
+0190             model.rxnReferences=[model.rxnReferences;models{i}.rxnReferences];
+0191         else
+0192             emptyReferences=cell(numel(model.rxns)-numel(models{i}.rxns),1);
+0193             emptyReferences(:)={''};
+0194             model.rxnReferences=[emptyReferences;models{i}.rxnReferences];
+0195         end
+0196     else
+0197         if isfield(model,'rxnReferences')
+0198             emptyReferences=cell(numel(models{i}.rxns),1);
+0199             emptyReferences(:)={''};
+0200             model.rxnReferences=[model.rxnReferences;emptyReferences];
+0201         end
+0202     end
+0203     
+0204     if isfield(models{i},'rxnConfidenceScores')
+0205         if isfield(model,'rxnConfidenceScores')
+0206             model.rxnConfidenceScores=[model.rxnConfidenceScores;models{i}.rxnConfidenceScores];
+0207         else
+0208             model.rxnConfidenceScores=[NaN(numel(model.rxns)-numel(models{i}.rxns),1);models{i}.rxnConfidenceScores];
+0209         end
+0210     else
+0211         if isfield(model,'rxnConfidenceScores')
+0212             model.rxnConfidenceScores=[model.rxnConfidenceScores;NaN(numel(models{i}.rxns),1)];
+0213         end
+0214     end
+0215 
+0216     if isfield(models{i},'rxnDeltaG')
+0217         if isfield(model,'rxnDeltaG')
+0218             model.rxnDeltaG=[model.rxnDeltaG;models{i}.rxnDeltaG];
+0219         else
+0220             model.rxnDeltaG=[NaN(numel(model.rxns)-numel(models{i}.rxns),1);models{i}.rxnDeltaG];
+0221         end
+0222     else
+0223         if isfield(model,'rxnDeltaG')
+0224             model.rxnDeltaG=[model.rxnDeltaG;NaN(numel(models{i}.rxns),1)];
+0225         end
+0226     end
+0227     
+0228     if isfield(models{i},'rxnComps')
+0229         if isfield(model,'rxnComps')
+0230             model.rxnComps=[model.rxnComps;models{i}.rxnComps];
+0231         else
+0232             model.rxnComps=[ones(numel(model.rxns)-numel(models{i}.rxns),1);models{i}.rxnComps];
+0233             fprintf('NOTE: One of the models does not contain compartment information for its reactions. All reactions in that model has been assigned to the first compartment\n');
+0234         end
+0235     else
+0236         if isfield(model,'rxnComps')
+0237             model.rxnComps=[model.rxnComps;ones(numel(models{i}.rxns),1)];
+0238             fprintf('NOTE: One of the models does not contain compartment information for its reactions. All reactions in that model has been assigned to the first compartment\n');
+0239         end
+0240     end
+0241     
+0242     if isfield(models{i},'rxnScores')
+0243         if isfield(model,'rxnScores')
+0244             model.rxnScores=[model.rxnScores;models{i}.rxnScores];
+0245         else
+0246             emptyRS=zeros(numel(model.rxns)-numel(models{i}.rxns),1);
+0247             model.rxnScores=[emptyRS;models{i}.rxnScores];
+0248         end
+0249     else
+0250         if isfield(model,'rxnScores')
+0251             emptyRS=zeros(numel(models{i}.rxns),1);
+0252             model.rxnScores=[model.rxnScores;emptyRS];
+0253         end
+0254     end
+0255     
+0256     if isfield(models{i},'pwys')
+0257         if isfield(model,'pwys')
+0258             model.pwys=[model.pwys;models{i}.pwys];
+0259         else
+0260             model.pwys=[cell(numel(model.rxns)-numel(models{i}.rxns),1);models{i}.pwys];
+0261         end
+0262     else
+0263         if isfield(model,'pwys')
+0264             model.pwys=[model.pwys;cell(numel(models{i}.rxns),1)];
+0265         end
+0266     end
+0267 
+0268     if strcmpi(metParam,'metNames')
+0269     %Get the new metabolites from matching the models. Metabolites are said
+0270     %to be the same if they share name and compartment id. This means that
+0271     %metabolite IDs are not taken into account.
+0272         
+0273         oldMetComps=model.comps(model.metComps);
+0274         oldMets=strcat(model.metNames,'[',oldMetComps,']');
+0275         %This is because it makes a '[]' string if no new metabolites
+0276         if ~isempty(models{i}.metNames)
+0277             newMetComps=models{i}.comps(models{i}.metComps);
+0278             newMets=strcat(models{i}.metNames,'[',newMetComps,']');
+0279         else
+0280             newMets={};
+0281             newMetComps={};
+0282         end
+0283         tf=ismember(newMets,oldMets);
+0284         metsToAdd=find(~tf);
+0285 
+0286     end
+0287 
+0288     if strcmpi(metParam,'mets')
+0289     %Get the new metabolites from matching the models. Metabolites are matched by metabolite ID (model.mets).
+0290 
+0291         oldMets=model.mets;
+0292     
+0293         if ~isempty(models{i}.mets)
+0294             newMetComps=models{i}.comps(models{i}.metComps);
+0295             newMets=models{i}.mets;
+0296         else
+0297             newMets={};
+0298             newMetComps={};
+0299         end
+0300         tf=ismember(newMets,oldMets);
+0301         metsToAdd=find(~tf);
+0302 
+0303     end
+0304     
+0305     %First add the new metabolites Make sure that there are no conflicting
+0306     %metabolite ids
+0307     conflicting=ismember(models{i}.mets(metsToAdd),model.mets);
+0308     
+0309     conflicting=find(conflicting);
+0310     
+0311     if ~isempty(conflicting)
+0312         printString=cell(numel(conflicting),1);
+0313         for j=1:numel(conflicting)
+0314             printString{j}=['Old: ' models{i}.mets{metsToAdd(conflicting(j))} ' New: ' models{i}.mets{metsToAdd(conflicting(j))} '_' models{i}.id];
+0315             models{i}.mets{metsToAdd(conflicting(j))}=[models{i}.mets{metsToAdd(conflicting(j))} '_' models{i}.id];
+0316         end
+0317         if supressWarnings==false
+0318             EM=['The following metabolite IDs in ' models{i}.id ' are already present in the model and were renamed:'];
+0319             dispEM(EM,false,printString);
+0320         end
+0321     end
+0322     
+0323     %Add static info on the metabolites
+0324     if any(hasMetFrom) || (~copyToComps && ~any(hasMetFrom))
+0325         model.metFrom  = [model.metFrom;  models{i}.metFrom(metsToAdd)];
+0326     end
+0327     model.mets     = [model.mets;     models{i}.mets(metsToAdd)];
+0328     model.metNames = [model.metNames; models{i}.metNames(metsToAdd)];
+0329     model.b        = [model.b;        zeros(numel(metsToAdd),size(model.b,2))];
+0330     
+0331     if isfield(model,'unconstrained')
+0332         if isfield(models{i},'unconstrained')
+0333             model.unconstrained=[model.unconstrained;models{i}.unconstrained(metsToAdd)];
+0334         else
+0335             model.unconstrained=[model.unconstrained;zeros(numel(metsToAdd),1)];
+0336         end
+0337     else
+0338         if isfield(models{i},'unconstrained')
+0339             model.unconstrained=[zeros(numel(model.mets),1);models{i}.unconstrained(metsToAdd)];
+0340         end
+0341     end
+0342     
+0343     %Only add extra info on new metabolites since it's a little tricky to
+0344     %chose what to keep otherwise. Should change in the future
+0345 
+0346     if ~isempty(metsToAdd)
+0347         if isfield(models{i},'inchis')
+0348             if isfield(model,'inchis')
+0349                 model.inchis=[model.inchis;models{i}.inchis(metsToAdd)];
+0350             else
+0351                 emptyInchi=cell(numel(model.mets)-numel(metsToAdd),1);
+0352                 emptyInchi(:)={''};
+0353                 model.inchis=[emptyInchi;models{i}.inchis(metsToAdd)];
+0354             end
+0355         else
+0356             if isfield(model,'inchis')
+0357                 emptyInchi=cell(numel(metsToAdd),1);
+0358                 emptyInchi(:)={''};
+0359                 model.inchis=[model.inchis;emptyInchi];
+0360             end
+0361         end
+0362 
+0363         if isfield(models{i},'metSmiles')
+0364             if isfield(model,'metSmiles')
+0365                 model.metSmiles=[model.metSmiles;models{i}.metSmiles(metsToAdd)];
+0366             else
+0367                 emptyInchi=cell(numel(model.mets)-numel(metsToAdd),1);
+0368                 emptyInchi(:)={''};
+0369                 model.metSmiles=[emptyInchi;models{i}.metSmiles(metsToAdd)];
+0370             end
+0371         else
+0372             if isfield(model,'metSmiles')
+0373                 emptyInchi=cell(numel(metsToAdd),1);
+0374                 emptyInchi(:)={''};
+0375                 model.metSmiles=[model.metSmiles;emptyInchi];
+0376             end
+0377         end
+0378         
+0379         if isfield(models{i},'metFormulas')
+0380             if isfield(model,'metFormulas')
+0381                 model.metFormulas=[model.metFormulas;models{i}.metFormulas(metsToAdd)];
+0382             else
+0383                 emptyMetFormulas=cell(numel(model.mets)-numel(metsToAdd),1);
+0384                 emptyMetFormulas(:)={''};
+0385                 model.metFormulas=[emptyMetFormulas;models{i}.metFormulas(metsToAdd)];
+0386             end
+0387         else
+0388             if isfield(model,'metFormulas')
+0389                 emptyMetFormulas=cell(numel(metsToAdd),1);
+0390                 emptyMetFormulas(:)={''};
+0391                 model.metFormulas=[model.metFormulas;emptyMetFormulas];
+0392             end
+0393         end
+0394         
+0395         if isfield(models{i},'metCharges')
+0396             if isfield(model,'metCharges')
+0397                 model.metCharges=[model.metCharges;models{i}.metCharges(metsToAdd)];
+0398             else
+0399                 emptyMetCharge=nan(numel(model.mets)-numel(metsToAdd),1);
+0400                 model.metCharges=[emptyMetCharge;models{i}.metCharges(metsToAdd)];
+0401             end
+0402         else
+0403             if isfield(model,'metCharges')
+0404                 emptyMetCharge=nan(numel(metsToAdd),1);
+0405                 model.metCharges=[model.metCharges;emptyMetCharge];
+0406             end
+0407         end
+0408 
+0409         if isfield(models{i},'metDeltaG')
+0410             if isfield(model,'metDeltaG')
+0411                 model.metDeltaG=[model.metDeltaG;models{i}.metDeltaG(metsToAdd)];
+0412             else
+0413                 emptyMetCharge=nan(numel(model.mets)-numel(metsToAdd),1);
+0414                 model.metDeltaG=[emptyMetCharge;models{i}.metDeltaG(metsToAdd)];
+0415             end
+0416         else
+0417             if isfield(model,'metDeltaG')
+0418                 emptyMetCharge=nan(numel(metsToAdd),1);
+0419                 model.metDeltaG=[model.metDeltaG;emptyMetCharge];
+0420             end
+0421         end
+0422         
+0423         if isfield(models{i},'metMiriams')
+0424             if isfield(model,'metMiriams')
+0425                 model.metMiriams=[model.metMiriams;models{i}.metMiriams(metsToAdd)];
+0426             else
+0427                 emptyMetMiriam=cell(numel(model.mets)-numel(metsToAdd),1);
+0428                 model.metMiriams=[emptyMetMiriam;models{i}.metMiriams(metsToAdd)];
+0429             end
+0430         else
+0431             if isfield(model,'metMiriams')
+0432                 emptyMetMiriam=cell(numel(metsToAdd),1);
+0433                 model.metMiriams=[model.metMiriams;emptyMetMiriam];
+0434             end
+0435         end
+0436     end
+0437     
+0438     %Add if there are any new compartments and add those. This can change
+0439     %the order of compartments and the corresponding indexes in
+0440     %model.metComps.
+0441     
+0442     %Find overlapping and new compartments
+0443     [overlap, oldIDs]=ismember(models{i}.comps,model.comps);
+0444     overlap=find(overlap);
+0445     
+0446     %Add the new compartments if any
+0447     if numel(overlap)~=numel(models{i}.compNames)
+0448         compIndexes=oldIDs==0;
+0449         
+0450         %Make sure that there are no conflicting compartment ids
+0451         [~, conflicting]=ismember(models{i}.compNames(compIndexes),model.compNames);
+0452         if any(conflicting)
+0453             EM=['The following compartment IDs in ' models{i}.id ' are already present in the model but with another name. They have to be renamed'];
+0454             dispEM(EM,true,model.comps(conflicting));
+0455         end
+0456         
+0457         %It's ok to add duplicate name, but not duplicate IDs
+0458         model.compNames=[model.compNames; models{i}.compNames(compIndexes)];
+0459         model.comps=[model.comps; models{i}.comps(compIndexes)];
+0460         if isfield(model,'compOutside')
+0461             if isfield(models{i},'compOutside')
+0462                 model.compOutside=[model.compOutside; models{i}.compOutside(compIndexes)];
+0463             else
+0464                 %This is if not all models have the field
+0465                 padding=cell(sum(compIndexes),1);
+0466                 padding(:)={''};
+0467                 model.compOutside=[model.compOutside;padding];
+0468             end
+0469         end
+0470         if isfield(model,'compMiriams')
+0471             if isfield(models{i},'compMiriams')
+0472                 model.compMiriams=[model.compMiriams; models{i}.compMiriams(compIndexes)];
+0473             else
+0474                 %This is if not all models have the field
+0475                 model.compMiriams=[model.compMiriams;cell(sum(compIndexes),1)];
+0476             end
+0477         end
+0478     end
+0479     
+0480     %Only add new comp info on the un-matched metabolites since the old
+0481     %ones will be mapped to the existing list anyways
+0482     [I, J]=ismember(newMetComps(metsToAdd),model.comps);
+0483     %Just a check
+0484     if ~all(I)
+0485         EM='There was an unexpected error in matching compartments';
+0486         dispEM(EM);
+0487     end
+0488     model.metComps=[model.metComps;J];
+0489      
+0490     %Create the new stoichiometric matrix
+0491     model.S=[model.S;sparse(numel(metsToAdd),size(model.S,2))];
+0492     
+0493 
+0494     if strcmpi(metParam,'metNames')
+0495         %Rematch metabolite names. Not the most clever way to do it maybe
+0496         allMets=strcat(model.metNames,'[',model.comps(model.metComps),']');
+0497         [~, J]=ismember(newMets,allMets);
+0498     end
+0499 
+0500     if strcmpi(metParam,'mets')
+0501         %Rematch metabolite by IDs and add unique new metabolites
+0502         allMets=model.mets;
+0503         uniqueNewMets = setdiff(newMets,oldMets);
+0504         allMets(end+1:end+numel(uniqueNewMets)) = uniqueNewMets;
+0505         [~, J]=ismember(newMets,allMets);
+0506     end
+0507 
+0508     %Update the stoichiometric matrix for the model to add
+0509     newS=sparse(numel(model.mets),numel(models{i}.rxns));
+0510     newS(J,:)=models{i}.S;
+0511     model.S=[model.S newS];
+0512 
+0513     
+0514     %Now add new genes
+0515     if isfield(models{i},'genes')
+0516         if ~isfield(model,'genes')
+0517             %If there was no gene info before
+0518             model.genes      = models{i}.genes;
+0519             model.rxnGeneMat = [sparse(numel(model.rxns),numel(models{i}.genes));models{i}.rxnGeneMat];
+0520             emptyGene        = repmat({''},numel(model.rxns),1);
+0521             model.grRules    = [emptyGene;models{i}.grRules];
+0522             if any(hasGeneFrom) || (~copyToComps && ~any(hasGeneFrom))
+0523                 model.geneFrom   = models{i}.geneFrom;
+0524             end
+0525             
+0526             if isfield(models{i},'geneShortNames')
+0527                 model.geneShortNames=models{i}.geneShortNames;
+0528             end
+0529 
+0530             if isfield(models{i},'proteins')
+0531                 model.proteins=models{i}.proteins;
+0532             end
+0533 
+0534             if isfield(models{i},'geneMiriams')
+0535                 model.geneMiriams=models{i}.geneMiriams;
+0536             end
+0537             
+0538             if isfield(models{i},'geneComps')
+0539                 model.geneComps=models{i}.geneComps;
+0540             end
+0541         else
+0542             %If gene info should be merged
+0543             a=ismember(models{i}.genes,model.genes);
+0544             
+0545             genesToAdd=find(~a);
+0546             
+0547             %Only add extra gene info on new genes. This might not be
+0548             %correct and should be changed later...
+0549             if ~isempty(genesToAdd)
+0550                 model.genes      = [model.genes;        models{i}.genes(genesToAdd)];
+0551                 model.geneFrom   = [model.geneFrom;     models{i}.geneFrom(genesToAdd)];
+0552                 model.rxnGeneMat = [model.rxnGeneMat    sparse(size(model.rxnGeneMat,1),numel(genesToAdd))];
+0553                 
+0554                 if isfield(models{i},'geneShortNames')
+0555                     if isfield(model,'geneShortNames')
+0556                         model.geneShortNames=[model.geneShortNames;models{i}.geneShortNames(genesToAdd)];
+0557                     else
+0558                         emptyGeneSN=cell(numel(model.genes)-numel(genesToAdd),1);
+0559                         emptyGeneSN(:)={''};
+0560                         model.geneShortNames=[emptyGeneSN;models{i}.geneShortNames(genesToAdd)];
+0561                     end
+0562                 else
+0563                     if isfield(model,'geneShortNames')
+0564                         emptyGeneSN=cell(numel(genesToAdd),1);
+0565                         emptyGeneSN(:)={''};
+0566                         model.geneShortNames=[model.geneShortNames;emptyGeneSN];
+0567                     end
+0568                 end
+0569 
+0570                 if isfield(models{i},'proteins')
+0571                     if isfield(model,'proteins')
+0572                         model.proteins=[model.proteins;models{i}.proteins(genesToAdd)];
+0573                     else
+0574                         emptyGeneSN=cell(numel(model.genes)-numel(genesToAdd),1);
+0575                         emptyGeneSN(:)={''};
+0576                         model.proteins=[emptyGeneSN;models{i}.proteins(genesToAdd)];
+0577                     end
+0578                 else
+0579                     if isfield(model,'proteins')
+0580                         emptyGeneSN=cell(numel(genesToAdd),1);
+0581                         emptyGeneSN(:)={''};
+0582                         model.proteins=[model.proteins;emptyGeneSN];
+0583                     end
+0584                 end
+0585 
+0586                 if isfield(models{i},'geneMiriams')
+0587                     if isfield(model,'geneMiriams')
+0588                         model.geneMiriams=[model.geneMiriams;models{i}.geneMiriams(genesToAdd)];
+0589                     else
+0590                         emptyGeneMir=cell(numel(model.genes)-numel(genesToAdd),1);
+0591                         model.geneMiriams=[emptyGeneMir;models{i}.geneMiriams(genesToAdd)];
+0592                     end
+0593                 else
+0594                     if isfield(model,'geneMiriams')
+0595                         emptyGeneMir=cell(numel(genesToAdd),1);
+0596                         model.geneMiriams=[model.geneMiriams;emptyGeneMir];
+0597                     end
+0598                 end
+0599                 
+0600                 if isfield(models{i},'geneComps')
+0601                     if isfield(model,'geneComps')
+0602                         model.geneComps=[model.geneComps;models{i}.geneComps(genesToAdd)];
+0603                     else
+0604                         emptyGeneMir=ones(numel(model.genes)-numel(genesToAdd),1);
+0605                         model.geneComps=[emptyGeneMir;models{i}.geneComps(genesToAdd)];
+0606                         EM='Adding genes with compartment information to a model without such information. All existing genes will be assigned to the first compartment';
+0607                         dispEM(EM,false);
+0608                     end
+0609                 else
+0610                     if isfield(model,'geneComps')
+0611                         emptyGeneMir=ones(numel(genesToAdd),1);
+0612                         model.geneComps=[model.geneComps;emptyGeneMir];
+0613                         EM='Adding genes with compartment information to a model without such information. All existing genes will be assigned to the first compartment';
+0614                         dispEM(EM,false);
+0615                     end
+0616                 end
+0617             end
+0618             
+0619             %Remap the genes from the new model. The same thing as with
+0620             %mets; this is a wasteful way to do it but I do not care right
+0621             %now
+0622             a = ismember(models{i}.genes,model.genes);
+0623             
+0624             %Just a check
+0625             if ~all(a)
+0626                 EM='There was an unexpected error in matching genes';
+0627                 dispEM(EM);
+0628             end
+0629             model.grRules=[model.grRules;models{i}.grRules];
+0630         end
+0631     else
+0632         %Add empty gene associations
+0633         if isfield(model,'genes')
+0634             emptyGene=cell(numel(models{i}.rxns),1);
+0635             emptyGene(:)={''};
+0636             model.grRules=[model.grRules;emptyGene];
+0637         end
+0638     end
+0639 end
+0640 %Fix grRules and reconstruct rxnGeneMat
+0641 [grRules,rxnGeneMat] = standardizeGrRules(model,true);
+0642 model.grRules = grRules;
+0643 model.rxnGeneMat = rxnGeneMat;
+0644 %Flatten subSystems if possible
+0645 if isfield(model,'subSystems')
+0646     if all(cellfun(@(x) iscell(x) && isscalar(x), model.subSystems))
+0647         model.subSystems = transpose([model.subSystems{:}]);
+0648     end
+0649 end
+0650 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/parallelPoolRAVEN.html b/doc/core/parallelPoolRAVEN.html new file mode 100644 index 000000000..be878bab6 --- /dev/null +++ b/doc/core/parallelPoolRAVEN.html @@ -0,0 +1,123 @@ + + + + Description of parallelPoolRAVEN + + + + + + + + + +
Home > core > parallelPoolRAVEN.m
+ + + +

parallelPoolRAVEN +

+ +

PURPOSE ^

+
handleParallelRAVEN
+ +

SYNOPSIS ^

+
function [ps, oldPoolAutoCreate] = parallelPoolRAVEN(runParallel)
+ +

DESCRIPTION ^

+
 handleParallelRAVEN
+   Called by RAVEN functions that support parallel processing, to confirm
+   whether the MATLAB Parallel Computing Toolbox is installed.
+   - The toolbox is installed, and runParallel == true, ==> a parallel
+     pool is started.
+   - The toolbox is installed, but runParallel == false, ==> the auto-
+     creation of a parallel pool is disabled, to prevent "parfor" in
+     the target function to start a pool anyway.
+   - The toolbox is not installed, and runParallel == true, ==> a warning
+     is displayed that parallel computer is not possible.
+   - The toolbox is not installed, and runParallel == false, ==> the
+     target runs as intended, as "parfor" will automatically run in serial
+     mode instead.
+
+ Input:
+   runParallel         logical, whether the target function (which calls
+                       parallelPoolRAVEN) should be run in parallel (optional,
+                       default true)
+
+ Output:
+   ps                  parallel settings structure that will be used by
+                       the target function    
+   oldPoolAutoCreate   logical, to reset the original ps.Pool.AutoCreate
+                       setting once the target function has finished
+
+ Use: [ps, oldPoolAutoCreate] = parallelPoolRAVEN(runParallel)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function [ps, oldPoolAutoCreate] = parallelPoolRAVEN(runParallel)
+0002 % handleParallelRAVEN
+0003 %   Called by RAVEN functions that support parallel processing, to confirm
+0004 %   whether the MATLAB Parallel Computing Toolbox is installed.
+0005 %   - The toolbox is installed, and runParallel == true, ==> a parallel
+0006 %     pool is started.
+0007 %   - The toolbox is installed, but runParallel == false, ==> the auto-
+0008 %     creation of a parallel pool is disabled, to prevent "parfor" in
+0009 %     the target function to start a pool anyway.
+0010 %   - The toolbox is not installed, and runParallel == true, ==> a warning
+0011 %     is displayed that parallel computer is not possible.
+0012 %   - The toolbox is not installed, and runParallel == false, ==> the
+0013 %     target runs as intended, as "parfor" will automatically run in serial
+0014 %     mode instead.
+0015 %
+0016 % Input:
+0017 %   runParallel         logical, whether the target function (which calls
+0018 %                       parallelPoolRAVEN) should be run in parallel (optional,
+0019 %                       default true)
+0020 %
+0021 % Output:
+0022 %   ps                  parallel settings structure that will be used by
+0023 %                       the target function
+0024 %   oldPoolAutoCreate   logical, to reset the original ps.Pool.AutoCreate
+0025 %                       setting once the target function has finished
+0026 %
+0027 % Use: [ps, oldPoolAutoCreate] = parallelPoolRAVEN(runParallel)
+0028 
+0029 if nargin<1 || isempty(runParallel)
+0030     runParallel = true;
+0031 end
+0032 
+0033 addonList = matlab.addons.installedAddons;
+0034 ps = []; oldPoolAutoCreate = [];
+0035 if ~any(strcmpi(addonList.Name,'Parallel Computing Toolbox'))
+0036     if runParallel % User wants parallel, but will not be possible
+0037         disp('Cannot find MATLAB Parallel Computing Toolbox, process is not parallelized.')
+0038     end
+0039 else
+0040     pool = gcp('nocreate');
+0041     if ~runParallel % User has Parallel toolbox, but does not want pool to start.
+0042         % If pool is already running, delete it
+0043         ps = parallel.Settings;
+0044         oldPoolAutoCreate = ps.Pool.AutoCreate;
+0045         ps.Pool.AutoCreate = false;
+0046         delete(pool);
+0047     elseif isempty(pool)
+0048         parpool('IdleTimeout',120);
+0049     end
+0050 end
+0051 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/parseFormulas.html b/doc/core/parseFormulas.html new file mode 100644 index 000000000..2a99eeabf --- /dev/null +++ b/doc/core/parseFormulas.html @@ -0,0 +1,318 @@ + + + + Description of parseFormulas + + + + + + + + + +
Home > core > parseFormulas.m
+ + + +

parseFormulas +

+ +

PURPOSE ^

+
parseFormulas
+ +

SYNOPSIS ^

+
function [elements, useMat, exitFlag, MW]=parseFormulas(formulas, noPolymers,isInchi,ignoreRX)
+ +

DESCRIPTION ^

+
 parseFormulas
+   Gets the elemental composition from formulas
+
+   formulas      a cell array with formulas
+   noPolymers    assume that all polymers consist of one element.
+                 Corresponds to counting everything between (...)n as
+                 n being equal to one. Only one set of parentheses
+                 is allowed. If this is false then polymers are returned as
+                 "Could not parse formula" (optional, default false)
+   isInchi       true if the formulas are in the InChI format (optional,
+                 default false)
+   ignoreRX      ignore R-groups and bound protein. This can be useful since they
+                 are often used only as intermediates (optional, default false)
+
+   elements
+       abbrevs   cell array with abbreviations for all used elements
+       names     cell array with the names for all used elements
+   useMat        MxN matrix with the number of atoms for each formula (M) and each
+                 element (N)
+   exitFlag      array with the exit flags:
+                 1=  Sucessful parsing
+                 0=  No formula found
+                 -1= Could not parse formula
+   MW            predicted molecular weight (g/mol). This is only returned
+                 for formulas which can be sucessfully parsed, and its
+                 calculation doesn't affect the exitFlag variable. NaN is
+                 returned if the weight couldn't be calculated
+   
+ Usage: [elements, useMat, exitFlag, MW]=
+               parseFormulas(formulas, noPolymers,isInchi,ignoreRX)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function [elements, useMat, exitFlag, MW]=parseFormulas(formulas, noPolymers,isInchi,ignoreRX)
+0002 % parseFormulas
+0003 %   Gets the elemental composition from formulas
+0004 %
+0005 %   formulas      a cell array with formulas
+0006 %   noPolymers    assume that all polymers consist of one element.
+0007 %                 Corresponds to counting everything between (...)n as
+0008 %                 n being equal to one. Only one set of parentheses
+0009 %                 is allowed. If this is false then polymers are returned as
+0010 %                 "Could not parse formula" (optional, default false)
+0011 %   isInchi       true if the formulas are in the InChI format (optional,
+0012 %                 default false)
+0013 %   ignoreRX      ignore R-groups and bound protein. This can be useful since they
+0014 %                 are often used only as intermediates (optional, default false)
+0015 %
+0016 %   elements
+0017 %       abbrevs   cell array with abbreviations for all used elements
+0018 %       names     cell array with the names for all used elements
+0019 %   useMat        MxN matrix with the number of atoms for each formula (M) and each
+0020 %                 element (N)
+0021 %   exitFlag      array with the exit flags:
+0022 %                 1=  Sucessful parsing
+0023 %                 0=  No formula found
+0024 %                 -1= Could not parse formula
+0025 %   MW            predicted molecular weight (g/mol). This is only returned
+0026 %                 for formulas which can be sucessfully parsed, and its
+0027 %                 calculation doesn't affect the exitFlag variable. NaN is
+0028 %                 returned if the weight couldn't be calculated
+0029 %
+0030 % Usage: [elements, useMat, exitFlag, MW]=
+0031 %               parseFormulas(formulas, noPolymers,isInchi,ignoreRX)
+0032 
+0033 if nargin<2
+0034     noPolymers=false;
+0035 end
+0036 if nargin<3
+0037     isInchi=false;
+0038 end
+0039 if nargin<4
+0040     ignoreRX=false;
+0041 end
+0042 
+0043 elements.abbrevs={'C', 'N', 'O', 'S', 'P', 'H', 'He', 'Li', 'Be', 'B', 'F', 'Ne', 'Na', 'Mg', 'Al',...
+0044     'Si', 'Cl', 'Ar', 'K', 'Ca', 'Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe', 'Co', 'Ni',...
+0045     'Cu', 'Zn', 'Ga', 'Ge', 'As', 'Se', 'Br', 'Kr', 'Rb', 'Sr', 'Y', 'Zr', 'Nb', 'Mo', 'Tc',...
+0046     'Ru', 'Rh', 'Pd', 'Ag', 'Cd', 'In', 'Sn', 'Sb', 'Te', 'I', 'Xe', 'Cs', 'Ba', 'La', 'Ce',...
+0047     'Pr', 'Nd', 'Pm', 'Sm', 'Eu', 'Gd', 'Tb', 'Dy', 'Ho', 'Er', 'Tm', 'Yb', 'Lu', 'Hf', 'Ta',...
+0048     'W', 'Re', 'Os', 'Ir', 'Pt', 'Au', 'Hg', 'Tl', 'Pb', 'Bi', 'Po', 'At', 'Rn', 'Fr', 'Ra',...
+0049     'Ac', 'Th', 'Pa', 'U', 'Np', 'Pu', 'Am', 'Cm', 'Bk', 'Cf', 'Es', 'Fm', 'Md', 'No', 'Lr',...
+0050     'Rf', 'Db', 'Sg', 'Bh', 'Hs', 'Mt', 'Ds', 'Rg', 'Cn', 'R', 'X'}';
+0051 elements.names={'carbon', 'nitrogen', 'oxygen', 'sulfur', 'phosphorus', 'hydrogen', 'helium', 'lithium', 'beryllium', 'boron',...
+0052     'fluorine', 'neon', 'sodium', 'magnesium', 'aluminum,', 'silicon',...
+0053     'chlorine', 'argon', 'potassium', 'calcium', 'scandium', 'titanium', 'vanadium',...
+0054     'chromium', 'manganese', 'iron', 'cobalt', 'nickel', 'copper', 'zinc', 'gallium', 'germanium',...
+0055     'arsenic', 'selenium', 'bromine', 'krypton', 'rubidium', 'strontium', 'yttrium', 'zirconium',...
+0056     'niobium', 'molybdenum', 'technetium', 'ruthenium', 'rhodium', 'palladium', 'silver', 'cadmium',...
+0057     'indium', 'tin', 'antimony', 'tellurium', 'iodine', 'xenon', 'cesium', 'barium', 'lanthanum',...
+0058     'cerium', 'praseodymium', 'neodymium', 'promethium', 'samarium', 'europium', 'gadolinium',...
+0059     'terbium', 'dysprosium', 'holmium', 'erbium', 'thulium', 'ytterbium', 'lutetium', 'hafnium',...
+0060     'tantalum', 'tungsten', 'rhenium', 'osmium', 'iridium', 'platinum', 'gold', 'mercury',...
+0061     'thallium', 'lead', 'bismuth', 'polonium', 'astatine', 'radon', 'francium', 'radium',...
+0062     'actinium', 'thorium', 'protactinium', 'uranium', 'neptunium', 'plutonium', 'americium',...
+0063     'curium', 'berkelium', 'californium', 'einsteinium', 'fermium', 'mendelevium', 'nobelium',...
+0064     'lawrencium', 'rutherfordium', 'dubnium', 'seaborgium', 'bohrium', 'hassium', 'meitnerium',...
+0065     'darmstadtium', 'roentgenium', 'copernicium', 'generic group', 'bound protein'}';
+0066 
+0067 EWs=[12.0107 14.0067 15.9994 32.065 30.973762 1.00794 4.002602 6.941 9.012182 10.811 18.9984032 ...
+0068     20.1797 22.98976928 24.305 26.9815386 28.0855 35.453 39.948 39.0983 40.078 44.955912 47.867 50.9415 ...
+0069     51.9961 54.938045 55.845 58.933195 58.6934 63.546 65.39 69.723 72.64 74.9216 78.96 79.904 83.798 ...
+0070     85.4678 87.62 88.90585 91.224 92.906 95.94 97.9072 101.07 102.905 106.42 107.8682 112.411 114.818 ...
+0071     118.71 121.76 127.6 126.904 131.293 132.9054519 137.327 138.90547 140.116 140.90765 144.242 144.9127 ...
+0072     150.36 151.964 157.25 158.92535 162.5 164.93 167.259 168.93421 173.04 174.967 178.49 180.94788 183.84 ...
+0073     186.207 190.23 192.217 195.084 196.966569 200.59 204.3833 207.2 208.9804 208.9824 209.9871 222.0176 ...
+0074     223.0197 226.0254 227.0277 232.03806 231.03588 238.02891 237.0482 244.0642 243.0614 247.0704 247.0703 ...
+0075     251.0796 252.083 257.0951 258.0984 259.101 262.1097 261.1088 262 266 264 277 268 271 272 nan nan nan]';
+0076 
+0077 %Set the EWs of these groups to 0
+0078 if ignoreRX==true
+0079     EWs(end-1:end)=0;
+0080 end
+0081 
+0082 useMat=zeros(numel(formulas),numel(elements.abbrevs));
+0083 
+0084 exitFlag=zeros(numel(formulas),1);
+0085 
+0086 %"H+", if parsed from InChI code, would have the composition "p+1". Change
+0087 %to fit with how the rest of the compounds are written
+0088 formulas=strrep(formulas,'p+1','H+');
+0089 
+0090 %Ignore charge to make the parsing easier
+0091 formulas=strrep(formulas,'+','');
+0092 formulas=strrep(formulas,'-','');
+0093 
+0094 %Loop through each formula
+0095 for i=1:numel(formulas)
+0096     if ~isempty(formulas{i})
+0097         sucess=false; %To see if it works
+0098         formula=formulas{i};
+0099         
+0100         %If it's an InChI code. The composition is found between the first
+0101         %and the second "/" For some simple molecules such as salts only
+0102         %the first "/" is present
+0103         if isInchi==true
+0104             S=regexp(formula,'/','split');
+0105             if numel(S)>=2
+0106                 formula=S{2};
+0107             else
+0108                 formula='';
+0109             end
+0110         end
+0111         %Only look at what's between the parantheses (polymers are not
+0112         %supported in InChI)
+0113         if isInchi==false
+0114             LP=strfind(formula,'(');
+0115             RP=strfind(formula,')n');
+0116             %            if numel(LP)>1 || numel(RP)>1
+0117             %               exitFlag(i)=-1; continue;
+0118             %            end if numel(LP)>1 || numel(RP)>1
+0119             %               exitFlag(i)=-1; continue;
+0120             %            end
+0121             if numel(LP)==1 && numel(RP)==1
+0122                 %This means that the polymer should be regarded as a
+0123                 %monomer
+0124                 if noPolymers==true
+0125                     %This means that there are one set of parantheses
+0126                     formula=strrep(formula,'(','');
+0127                     formula=strrep(formula,')n','');
+0128                 else
+0129                     %This means that polymers should be ignored
+0130                     exitFlag(i)=-1;
+0131                     continue;
+0132                 end
+0133             else
+0134                 if ~isempty(LP) || ~isempty(RP)
+0135                     exitFlag(i)=-1;
+0136                     continue;
+0137                 end
+0138             end
+0139         end
+0140         
+0141         %Get the indexes of the numeric (or ".") characters
+0142         nonNumeric=false(numel(formula),1);
+0143         nonNumeric(regexp(formula,'[^0-9.]'))=true;
+0144         
+0145         %Get the indexes of the upper characters (since each element starts
+0146         %with an upper character)
+0147         upperI=isstrprop(formula,'upper');
+0148         upperX=find(upperI);
+0149         
+0150         for j=1:numel(upperX)
+0151             %The first case is when it's the last character. Then the
+0152             %coefficient must be 1
+0153             isLast=false;
+0154             if upperX(j)==numel(formula)
+0155                 coeff=1;
+0156                 element=formula(upperX(j));
+0157                 isLast=true;
+0158             end
+0159             
+0160             if isLast==false
+0161                 %The second case is when the following character is a
+0162                 %character
+0163                 if nonNumeric(upperX(j)+1)
+0164                     %Is it a new element?
+0165                     if upperI(upperX(j)+1)
+0166                         %New element, that means that the coefficient was 1
+0167                         %and that the element was only one character
+0168                         coeff=1;
+0169                         element=formula(upperX(j));
+0170                     else
+0171                         %This means that it's an element with two
+0172                         %characters
+0173                         if j==numel(upperX)
+0174                             if upperX(j)<numel(formula)-1
+0175                                 coeff=str2double(formula(upperX(j)+2:end));
+0176                             else
+0177                                 coeff=1;
+0178                             end
+0179                         else
+0180                             %Check if there is a number or a new element
+0181                             %after it
+0182                             if nonNumeric(upperX(j)+2)==true
+0183                                 coeff=1;
+0184                             else
+0185                                 coeff=str2double(formula(upperX(j)+2:upperX(j+1)-1));
+0186                             end
+0187                         end
+0188                         element=formula(upperX(j):upperX(j)+1);
+0189                     end
+0190                 else
+0191                     %Then it is a numeral
+0192                     if j==numel(upperX)
+0193                         coeff=str2double(formula(upperX(j)+1:end));
+0194                     else
+0195                         coeff=str2double(formula(upperX(j)+1:upperX(j+1)-1));
+0196                     end
+0197                     element=formula(upperX(j));
+0198                 end
+0199             end
+0200             
+0201             %Find the element
+0202             I=strcmp(element,elements.abbrevs);
+0203             if any(I)
+0204                 if ~isnan(coeff)
+0205                     useMat(i,I)=useMat(i,I)+coeff;
+0206                     sucess=true;
+0207                 else
+0208                     break;
+0209                 end
+0210             else
+0211                 break;
+0212             end
+0213         end
+0214         if sucess==false
+0215             useMat(i,:)=0; %Reset for this formula
+0216             exitFlag(i)=-1;
+0217         else
+0218             exitFlag(i)=1;
+0219         end
+0220     end
+0221 end
+0222 
+0223 %Remove the elements which are never used
+0224 I=~any(useMat);
+0225 useMat(:,I)=[];
+0226 elements.abbrevs(I)=[];
+0227 elements.names(I)=[];
+0228 EWs(I)=[];
+0229 
+0230 %Calcluate the weight contribution of each element in each formula. Note
+0231 %that this will give NaNs for all formulas if R or X groups are in EWs,
+0232 %since 0*NaN is still NaN. Therefore only use elements with known mass
+0233 if nargout>3
+0234     P=bsxfun(@times,useMat(:,~isnan(EWs)),EWs(~isnan(EWs)).');
+0235     MW=sum(P,2);
+0236     
+0237     %Then remove the calculations for elements with unknown mass
+0238     I=find(useMat(:,isnan(EWs)));
+0239     MW(I)=nan;
+0240     MW(exitFlag~=1)=nan;
+0241 end
+0242 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/parseRxnEqu.html b/doc/core/parseRxnEqu.html new file mode 100644 index 000000000..81d3bff56 --- /dev/null +++ b/doc/core/parseRxnEqu.html @@ -0,0 +1,135 @@ + + + + Description of parseRxnEqu + + + + + + + + + +
Home > core > parseRxnEqu.m
+ + + +

parseRxnEqu +

+ +

PURPOSE ^

+
parseRxnEqu
+ +

SYNOPSIS ^

+
function metabolites=parseRxnEqu(equations)
+ +

DESCRIPTION ^

+
 parseRxnEqu
+   Gets all metabolite names from a cell array of equations
+
+   metabolites=parseRxnEqu(equations)
+
+   equations     A cell array with equation strings
+
+   metabolites   A cell array with the involved metabolites
+
+   The equations should be written like:
+   1 A + 3 B (=> or <=>) 5C + 2 D
+
+   If the equation is expressed as for example '... + (n-1) starch' then
+   '(n-1) starch' will be interpreted as one metabolite
+
+ Usage: metabolites=parseRxnEqu(equations)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function metabolites=parseRxnEqu(equations)
+0002 % parseRxnEqu
+0003 %   Gets all metabolite names from a cell array of equations
+0004 %
+0005 %   metabolites=parseRxnEqu(equations)
+0006 %
+0007 %   equations     A cell array with equation strings
+0008 %
+0009 %   metabolites   A cell array with the involved metabolites
+0010 %
+0011 %   The equations should be written like:
+0012 %   1 A + 3 B (=> or <=>) 5C + 2 D
+0013 %
+0014 %   If the equation is expressed as for example '... + (n-1) starch' then
+0015 %   '(n-1) starch' will be interpreted as one metabolite
+0016 %
+0017 % Usage: metabolites=parseRxnEqu(equations)
+0018 
+0019 if ~iscell(equations)
+0020     equations={equations};
+0021 end
+0022 
+0023 metabolites={};
+0024 
+0025 %Replace the the direction arrows and plus signs with a weird character
+0026 %that will be used for parsing
+0027 equations=strrep(equations,' <=> ', '€');
+0028 equations=strrep(equations,' => ', '€');
+0029 equations=strrep(equations,' + ', '€');
+0030 equations=strtrim(equations);
+0031 
+0032 for i=1:numel(equations)
+0033     %Split each equation in possible metabolites
+0034     candidates=regexp(equations{i},'€','split');
+0035     
+0036     %If the splitting character is at the end (if exchange rxns), then an
+0037     %empty string will exist together with the real ones. Remove it
+0038     candidates(cellfun(@isempty,candidates))=[];
+0039     
+0040     %Now remove the potential coefficient before each metabolite
+0041     for j=1:numel(candidates)
+0042         %If the metabolite has a coefficient it will look as 'number name'
+0043         space=strfind(candidates{j},' ');
+0044         
+0045         if isempty(space)
+0046             %Add the metabolite
+0047             metabolites=[metabolites;candidates(j)];
+0048         else
+0049             potNumber=candidates{j}(1:space(1));
+0050             %I use str2double here which can't deal with fractions (1/3 glc
+0051             %and so on). I do this because I don't want to risk calling
+0052             %functions
+0053             [~,isNumber]=str2num(potNumber);
+0054             
+0055             if isNumber==1
+0056                 %Remove the coefficient
+0057                 metName=candidates{j}(space(1)+1:end);
+0058                 metabolites=[metabolites;metName];
+0059             else
+0060                 %The metabolite name contained spaces
+0061                 metabolites=[metabolites;candidates(j)];
+0062             end
+0063         end
+0064     end
+0065 end
+0066 
+0067 metabolites=strtrim(metabolites);
+0068 
+0069 %Upper/lower case is treated as different names. This should be checked for
+0070 %later since it's bad modelling practice
+0071 metabolites=unique(metabolites);
+0072 
+0073 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/parseTaskList.html b/doc/core/parseTaskList.html new file mode 100644 index 000000000..51aa28e2a --- /dev/null +++ b/doc/core/parseTaskList.html @@ -0,0 +1,441 @@ + + + + Description of parseTaskList + + + + + + + + + +
Home > core > parseTaskList.m
+ + + +

parseTaskList +

+ +

PURPOSE ^

+
parseTaskList
+ +

SYNOPSIS ^

+
function taskStruct=parseTaskList(inputFile)
+ +

DESCRIPTION ^

+
 parseTaskList
+   Parses a task list file.
+
+   inputFile       a task list in either Excel (*.xlsx, with a sheet named
+                   TASKS with all relevant content) or tab-delimited
+                   (*.txt) format. The file may contain the following
+                   column headers (note, all rows starting with a
+                   non-empty cell are removed. The first row after that
+                   is considered the headers):
+                   ID
+                       the only required header. Each task must have a
+                       unique id (string or numeric). Tasks can span multiple
+                       rows, only the first row in each task should have
+                       an id
+                   DESCRIPTION
+                       description of the task
+                   IN
+                       allowed input(s) for the task. Metabolite names
+                       should be on the form
+                       "model.metName[model.comps]". Several inputs
+                       can be delimited by ";". If so, then the same
+                       bounds are used for all inputs. If that is not
+                       wanted, then use several rows for the task
+                   IN LB
+                       lower bound for the uptake of the metabolites in
+                       the row (optional, default 0 which corresponds to a
+                       minimal uptake of 0 units)
+                   IN UB
+                       upper bound for the uptake of the metabolites in
+                       the row (optional, default 1000 which corresponds to a
+                       maximal uptake of 1000 units)
+                   OUT
+                       allowed output(s) for the task (see IN)
+                   OUT LB
+                       lower bound for the production of the metabolites in
+                       the row (optional, default 0 which corresponds to a
+                       minimal production of 0 units)
+                   OUT UB
+                       upper bound for the production of the metabolites in
+                       the row (optional, default 1000 which corresponds to a
+                       maximal production of 1000 units)
+                   EQU
+                       equation to add. The equation should be on the form
+                       "0.4 A + 2 B <=> (or =>) C" and the metabolites
+                       should be on the form
+                       "model.metName[model.comps]" (optional)
+                   EQU LB
+                       lower bound for the equation (optional, default -1000
+                       for reversible and 0 for irreversible)
+                   EQU UB
+                       upper bound for the equation (optional, default 1000)
+                   CHANGED RXN
+                       reaction ID for which to change the bounds for.
+                       Several IDs can be delimited by ";". If so,
+                       then the same bounds are used for all reactions. If
+                       that is not wanted, then use several rows for the task
+                   CHANGED LB
+                       lower bound for the reaction
+                   CHANGED UB
+                       upper bound for the reaction
+                   SHOULD FAIL
+                       true if the correct behavior of the model is to
+                       not have a feasible solution given the constraints
+                       (optional, default false)
+                   PRINT FLUX
+                       true if the function should print the corresponding
+                       flux distribution for a task. Can be useful for
+                       testing (optional, default false)
+
+   taskStruct      array of structures with the following fields
+       id          the id of the task
+       description the description of the task
+       shouldFail  true if the task should fail
+       printFluxes true if the fluxes should be printed
+       comments    string with comments
+       inputs      cell array with input metabolites (in the form metName[comps])
+       LBin        array with lower bounds on inputs (default, 0)
+       UBin        array with upper bounds on inputs (default, 1000)
+       outputs     cell array with output metabolites (in the form metName[comps])
+       LBout       array with lower bounds on outputs (default, 0)
+       UBout       array with upper bounds on outputs (default, 1000)
+       equations   cell array with equations (with mets in the form metName[comps])
+       LBequ       array with lower bounds on equations (default, -1000 for
+                   reversible and 0 for irreversible)
+       UBequ       array with upper bounds on equations (default, 1000)
+       changed     cell array with reactions to change bounds for
+       LBrxn       array with lower bounds on changed reactions
+       UBrxn       array with upper bounds on changed reactions
+
+   This function is used for defining a set of tasks for a model to
+   perform. The tasks are defined by defining constraints on the model,
+   and if the problem is feasible, then the task is considered successful.
+   In general, each row can contain one constraint on uptakes, one
+   constraint on outputs, one new equation, and one change of reaction
+   bounds. If more bounds are needed to define the task, then several rows
+   can be used for each task. To perform the task use checkTasks or
+   fitTasks.
+
+   NOTE: The general metabolites "ALLMETS" and "ALLMETSIN[comps]"
+   can be used as inputs or outputs in the similar manner to normal
+   metabolites. This is a convenient way to, for example, allow excretion of
+   all metabolites to check whether it's the synthesis of some metabolite
+   that is limiting or whether it's the degradation of some byproduct. One
+   important difference is that only the upper bounds are used for these general
+   metabolites. That is, you can only say that uptake or excretion is
+   allowed, not that it is required. This is to avoid conflicts where the
+   constraints for the general metabolites overwrite those of the real
+   ones.
+
+ Usage: taskStruct=parseTaskList(inputFile)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function taskStruct=parseTaskList(inputFile)
+0002 % parseTaskList
+0003 %   Parses a task list file.
+0004 %
+0005 %   inputFile       a task list in either Excel (*.xlsx, with a sheet named
+0006 %                   TASKS with all relevant content) or tab-delimited
+0007 %                   (*.txt) format. The file may contain the following
+0008 %                   column headers (note, all rows starting with a
+0009 %                   non-empty cell are removed. The first row after that
+0010 %                   is considered the headers):
+0011 %                   ID
+0012 %                       the only required header. Each task must have a
+0013 %                       unique id (string or numeric). Tasks can span multiple
+0014 %                       rows, only the first row in each task should have
+0015 %                       an id
+0016 %                   DESCRIPTION
+0017 %                       description of the task
+0018 %                   IN
+0019 %                       allowed input(s) for the task. Metabolite names
+0020 %                       should be on the form
+0021 %                       "model.metName[model.comps]". Several inputs
+0022 %                       can be delimited by ";". If so, then the same
+0023 %                       bounds are used for all inputs. If that is not
+0024 %                       wanted, then use several rows for the task
+0025 %                   IN LB
+0026 %                       lower bound for the uptake of the metabolites in
+0027 %                       the row (optional, default 0 which corresponds to a
+0028 %                       minimal uptake of 0 units)
+0029 %                   IN UB
+0030 %                       upper bound for the uptake of the metabolites in
+0031 %                       the row (optional, default 1000 which corresponds to a
+0032 %                       maximal uptake of 1000 units)
+0033 %                   OUT
+0034 %                       allowed output(s) for the task (see IN)
+0035 %                   OUT LB
+0036 %                       lower bound for the production of the metabolites in
+0037 %                       the row (optional, default 0 which corresponds to a
+0038 %                       minimal production of 0 units)
+0039 %                   OUT UB
+0040 %                       upper bound for the production of the metabolites in
+0041 %                       the row (optional, default 1000 which corresponds to a
+0042 %                       maximal production of 1000 units)
+0043 %                   EQU
+0044 %                       equation to add. The equation should be on the form
+0045 %                       "0.4 A + 2 B <=> (or =>) C" and the metabolites
+0046 %                       should be on the form
+0047 %                       "model.metName[model.comps]" (optional)
+0048 %                   EQU LB
+0049 %                       lower bound for the equation (optional, default -1000
+0050 %                       for reversible and 0 for irreversible)
+0051 %                   EQU UB
+0052 %                       upper bound for the equation (optional, default 1000)
+0053 %                   CHANGED RXN
+0054 %                       reaction ID for which to change the bounds for.
+0055 %                       Several IDs can be delimited by ";". If so,
+0056 %                       then the same bounds are used for all reactions. If
+0057 %                       that is not wanted, then use several rows for the task
+0058 %                   CHANGED LB
+0059 %                       lower bound for the reaction
+0060 %                   CHANGED UB
+0061 %                       upper bound for the reaction
+0062 %                   SHOULD FAIL
+0063 %                       true if the correct behavior of the model is to
+0064 %                       not have a feasible solution given the constraints
+0065 %                       (optional, default false)
+0066 %                   PRINT FLUX
+0067 %                       true if the function should print the corresponding
+0068 %                       flux distribution for a task. Can be useful for
+0069 %                       testing (optional, default false)
+0070 %
+0071 %   taskStruct      array of structures with the following fields
+0072 %       id          the id of the task
+0073 %       description the description of the task
+0074 %       shouldFail  true if the task should fail
+0075 %       printFluxes true if the fluxes should be printed
+0076 %       comments    string with comments
+0077 %       inputs      cell array with input metabolites (in the form metName[comps])
+0078 %       LBin        array with lower bounds on inputs (default, 0)
+0079 %       UBin        array with upper bounds on inputs (default, 1000)
+0080 %       outputs     cell array with output metabolites (in the form metName[comps])
+0081 %       LBout       array with lower bounds on outputs (default, 0)
+0082 %       UBout       array with upper bounds on outputs (default, 1000)
+0083 %       equations   cell array with equations (with mets in the form metName[comps])
+0084 %       LBequ       array with lower bounds on equations (default, -1000 for
+0085 %                   reversible and 0 for irreversible)
+0086 %       UBequ       array with upper bounds on equations (default, 1000)
+0087 %       changed     cell array with reactions to change bounds for
+0088 %       LBrxn       array with lower bounds on changed reactions
+0089 %       UBrxn       array with upper bounds on changed reactions
+0090 %
+0091 %   This function is used for defining a set of tasks for a model to
+0092 %   perform. The tasks are defined by defining constraints on the model,
+0093 %   and if the problem is feasible, then the task is considered successful.
+0094 %   In general, each row can contain one constraint on uptakes, one
+0095 %   constraint on outputs, one new equation, and one change of reaction
+0096 %   bounds. If more bounds are needed to define the task, then several rows
+0097 %   can be used for each task. To perform the task use checkTasks or
+0098 %   fitTasks.
+0099 %
+0100 %   NOTE: The general metabolites "ALLMETS" and "ALLMETSIN[comps]"
+0101 %   can be used as inputs or outputs in the similar manner to normal
+0102 %   metabolites. This is a convenient way to, for example, allow excretion of
+0103 %   all metabolites to check whether it's the synthesis of some metabolite
+0104 %   that is limiting or whether it's the degradation of some byproduct. One
+0105 %   important difference is that only the upper bounds are used for these general
+0106 %   metabolites. That is, you can only say that uptake or excretion is
+0107 %   allowed, not that it is required. This is to avoid conflicts where the
+0108 %   constraints for the general metabolites overwrite those of the real
+0109 %   ones.
+0110 %
+0111 % Usage: taskStruct=parseTaskList(inputFile)
+0112 
+0113 if ~isfile(inputFile)
+0114     error('Task list %s cannot be found',string(inputFile));
+0115 end
+0116 
+0117 %Load the tasks file
+0118 convNumeric = false;
+0119 if strcmp(extractAfter(inputFile,strlength(inputFile) - 4), '.txt')
+0120     %load from tab delimited text file
+0121     fid = fopen(inputFile);
+0122     %Need to read numeric columns as strings, this is converted further
+0123     %down. If not, the titles would be lost.
+0124     convNumeric = true;
+0125     C = textscan(fid,'%q%q%q%q%q%q%q%q%q%q%q%q%q%q%q%q%q%q%q%q%*[^\n]', 'Delimiter', '\t');
+0126     fclose(fid);
+0127     raw = [C{:}];%unnest the cell array of cell arrays into a 2-dim cell array
+0128 else
+0129     [raw,flag]=loadSheet(loadWorkbook(inputFile), 'TASKS');
+0130     if flag~=0
+0131         EM=['Could not load sheet "TASKS" from ' inputFile];
+0132         dispEM(EM);
+0133     end
+0134 end
+0135 
+0136 %Remove all lines starting with "#" (or actually any character) and all
+0137 %empty columns
+0138 raw=cleanSheet(raw);
+0139 
+0140 %Captions
+0141 columns={'ID';'DESCRIPTION';'IN';'IN LB';'IN UB';'OUT';'OUT LB';'OUT UB';'EQU';'EQU LB';'EQU UB';'CHANGED RXN';'CHANGED LB';'CHANGED UB';'SHOULD FAIL';'PRINT FLUX';'COMMENTS'};
+0142 %Match the columns
+0143 [I, colI]=ismember(columns,raw(1,:));
+0144 
+0145 %If read from  a text file, the numbers will be strings - fix that
+0146 if convNumeric % in theory, this if should not be needed, the code should do nothing if all are already numeric. But it is kept as a safeguard.
+0147     numericColumns = [0 0 0 1 1 0 1 1 0 1 1 0 1 1 0 0 0] == 1;
+0148     cols = colI(numericColumns);
+0149     numeric = cellfun(@isnumeric,raw(:,cols));
+0150     %trick to avoid messing up the title row:
+0151     numeric(1,:) = 1;
+0152     for colind = 1:numel(cols)
+0153         col = cols(colind);
+0154         raw(~numeric(:,colind),col) = cellfun(@str2num, raw(~numeric(:,colind),col), 'UniformOutput', false);
+0155     end
+0156 end
+0157 
+0158 %Check that the ID field is present
+0159 if I(1)==0
+0160     EM='The TASKS sheet must have a column named ID';
+0161     dispEM(EM);
+0162 end
+0163 
+0164 %make sure numerical fields are converted from strings
+0165 
+0166 %Add default bounds where needed
+0167 for i=[4 5 7 8]
+0168     I=cellfun(@isempty,raw(:,colI(i)));
+0169     if i==5 || i==8
+0170         raw(I,colI(i))={1000};
+0171     else
+0172         raw(I,colI(i))={0};
+0173     end
+0174 end
+0175 
+0176 %Create an empty task structure
+0177 eTask.id='';
+0178 eTask.description='';
+0179 eTask.shouldFail=false;
+0180 eTask.printFluxes=false;
+0181 eTask.comments='';
+0182 eTask.inputs={};
+0183 eTask.LBin=[];
+0184 eTask.UBin=[];
+0185 eTask.outputs={};
+0186 eTask.LBout=[];
+0187 eTask.UBout=[];
+0188 eTask.equations={};
+0189 eTask.LBequ=[];
+0190 eTask.UBequ=[];
+0191 eTask.changed={};
+0192 eTask.LBrxn=[];
+0193 eTask.UBrxn=[];
+0194 
+0195 %Main loop
+0196 taskStruct=[];
+0197 task=eTask;
+0198 if isnumeric(raw{2,colI(1)})
+0199     task.id=num2str(raw{2,colI(1)});
+0200 else
+0201     task.id=raw{2,colI(1)};
+0202 end
+0203 task.description=raw{2,colI(2)};
+0204 if ~isempty(raw{2,colI(15)})
+0205     task.shouldFail=true;
+0206 end
+0207 if ~isempty(raw{2,colI(16)})
+0208     task.printFluxes=true;
+0209 end
+0210 if ~isempty(raw{2,colI(17)})
+0211     task.comments=raw{2,colI(17)};
+0212 end
+0213 
+0214 for i=2:size(raw,1)
+0215     %Set the inputs
+0216     if ischar(raw{i,colI(3)})
+0217         inputs=regexp(raw{i,colI(3)},';','split');
+0218         task.inputs=[task.inputs;inputs(:)];
+0219         task.LBin=[task.LBin;ones(numel(inputs),1)*raw{i,colI(4)}];
+0220         task.UBin=[task.UBin;ones(numel(inputs),1)*raw{i,colI(5)}];
+0221     end
+0222     %Set the outputs
+0223     if ischar(raw{i,colI(6)})
+0224         outputs=regexp(raw{i,colI(6)},';','split');
+0225         task.outputs=[task.outputs;outputs(:)];
+0226         task.LBout=[task.LBout;ones(numel(outputs),1)*raw{i,colI(7)}];
+0227         task.UBout=[task.UBout;ones(numel(outputs),1)*raw{i,colI(8)}];
+0228     end
+0229     %Add new rxns
+0230     if ischar(raw{i,colI(9)})
+0231         task.equations=[task.equations;raw{i,colI(9)}];
+0232         if ~isempty(raw{i,colI(10)})
+0233             task.LBequ=[task.LBequ;raw{i,colI(10)}];
+0234         else
+0235             if any(strfind(raw{i,colI(9)},'<=>'))
+0236                 task.LBequ=[task.LBequ;-1000];
+0237             else
+0238                 task.LBequ=[task.LBequ;0];
+0239             end
+0240         end
+0241         if ~isempty(raw{i,colI(11)})
+0242             task.UBequ=[task.UBequ;raw{i,colI(11)}];
+0243         else
+0244             task.UBequ=[task.UBequ;1000];
+0245         end
+0246     end
+0247     %Add changed bounds
+0248     if ischar(raw{i,colI(12)})
+0249         changed=regexp(raw{i,colI(12)},';','split');
+0250         task.changed=[task.changed;changed(:)];
+0251         task.LBrxn=[task.LBrxn;ones(numel(changed),1)*raw{i,colI(13)}];
+0252         task.UBrxn=[task.UBrxn;ones(numel(changed),1)*raw{i,colI(14)}];
+0253     end
+0254     
+0255     %Check if it should add more constraints
+0256     if i<size(raw,1)
+0257         if isempty(raw{i+1,colI(1)})
+0258             continue;
+0259         end
+0260     end
+0261     
+0262     taskStruct=[taskStruct;task];
+0263     task=eTask;
+0264     if i<size(raw,1)
+0265         if isnumeric(raw{i+1,colI(1)})
+0266             task.id=num2str(raw{i+1,colI(1)});
+0267         else
+0268             task.id=raw{i+1,colI(1)};
+0269         end
+0270         task.description=raw{i+1,colI(2)};
+0271         if ~isempty(raw{i+1,colI(15)})
+0272             task.shouldFail=true;
+0273         end
+0274         if ~isempty(raw{i+1,colI(16)})
+0275             task.printFluxes=true;
+0276         end
+0277         if ~isempty(raw{i+1,colI(17)})
+0278             task.comments=raw{i+1,colI(17)};
+0279         end
+0280     end
+0281 end
+0282 
+0283 %Should add more checks, such as unique IDs and missing headers
+0284 
+0285 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/permuteModel.html b/doc/core/permuteModel.html new file mode 100644 index 000000000..f86f25f53 --- /dev/null +++ b/doc/core/permuteModel.html @@ -0,0 +1,228 @@ + + + + Description of permuteModel + + + + + + + + + +
Home > core > permuteModel.m
+ + + +

permuteModel +

+ +

PURPOSE ^

+
permuteModel
+ +

SYNOPSIS ^

+
function newModel=permuteModel(model, indexes, type)
+ +

DESCRIPTION ^

+
 permuteModel
+   Changes the order of the reactions or metabolites in a model
+
+   Input:
+   model     a model structure
+   indexes   a vector with the same length as the number of items in the
+             model, which gives the new order of items
+   type      'rxns' for reactions, 'mets' for metabolites, 'genes' for
+             genes, 'comps' for compartments
+
+     Output:
+   newModel  an updated model structure
+
+     Usage: newModel=permuteModel(model, indexes, type)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function newModel=permuteModel(model, indexes, type)
+0002 % permuteModel
+0003 %   Changes the order of the reactions or metabolites in a model
+0004 %
+0005 %   Input:
+0006 %   model     a model structure
+0007 %   indexes   a vector with the same length as the number of items in the
+0008 %             model, which gives the new order of items
+0009 %   type      'rxns' for reactions, 'mets' for metabolites, 'genes' for
+0010 %             genes, 'comps' for compartments
+0011 %
+0012 %     Output:
+0013 %   newModel  an updated model structure
+0014 %
+0015 %     Usage: newModel=permuteModel(model, indexes, type)
+0016 
+0017 newModel=model;
+0018 type=char(type);
+0019 
+0020 switch type
+0021     case 'rxns'
+0022         if isfield(newModel,'rxns')
+0023             newModel.rxns=newModel.rxns(indexes);
+0024         end
+0025         if isfield(newModel,'lb')
+0026             newModel.lb=newModel.lb(indexes);
+0027         end
+0028         if isfield(newModel,'ub')
+0029             newModel.ub=newModel.ub(indexes);
+0030         end
+0031         if isfield(newModel,'rev')
+0032             newModel.rev=newModel.rev(indexes);
+0033         end
+0034         if isfield(newModel,'c')
+0035             newModel.c=newModel.c(indexes);
+0036         end
+0037         if isfield(newModel,'S')
+0038             newModel.S=newModel.S(:,indexes);
+0039         end
+0040         if isfield(newModel,'rxnNames')
+0041             newModel.rxnNames=newModel.rxnNames(indexes);
+0042         end
+0043         if isfield(newModel,'rxnGeneMat')
+0044             newModel.rxnGeneMat=newModel.rxnGeneMat(indexes,:);
+0045         end
+0046         if isfield(newModel,'grRules')
+0047             newModel.grRules=newModel.grRules(indexes);
+0048         end
+0049         if isfield(newModel,'subSystems')
+0050             newModel.subSystems=newModel.subSystems(indexes);
+0051         end
+0052         if isfield(newModel,'eccodes')
+0053             newModel.eccodes=newModel.eccodes(indexes);
+0054         end
+0055         if isfield(newModel,'equations')
+0056             newModel.equations=newModel.equations(indexes);
+0057         end
+0058         if isfield(newModel,'rxnMiriams')
+0059             newModel.rxnMiriams=newModel.rxnMiriams(indexes);
+0060         end
+0061         if isfield(newModel,'rxnComps')
+0062             newModel.rxnComps=newModel.rxnComps(indexes);
+0063         end
+0064         if isfield(newModel,'rxnFrom')
+0065             newModel.rxnFrom=newModel.rxnFrom(indexes);
+0066         end
+0067         if isfield(newModel,'rxnScores')
+0068             newModel.rxnScores=newModel.rxnScores(indexes);
+0069         end
+0070         if isfield(newModel,'rxnNotes')
+0071             newModel.rxnNotes=newModel.rxnNotes(indexes);
+0072         end
+0073         if isfield(newModel,'rxnReferences')
+0074             newModel.rxnReferences=newModel.rxnReferences(indexes);
+0075         end
+0076         if isfield(newModel,'rxnConfidenceScores')
+0077             newModel.rxnConfidenceScores=newModel.rxnConfidenceScores(indexes);
+0078         end
+0079         if isfield(newModel,'rxnDeltaG')
+0080             newModel.rxnDeltaG=newModel.rxnDeltaG(indexes);
+0081         end
+0082     case 'mets'
+0083         if isfield(newModel,'mets')
+0084             newModel.mets=newModel.mets(indexes);
+0085         end
+0086         if isfield(newModel,'metNames')
+0087             newModel.metNames=newModel.metNames(indexes);
+0088         end
+0089         if isfield(newModel,'b')
+0090             newModel.b=newModel.b(indexes,:);
+0091         end
+0092         if isfield(newModel,'metComps')
+0093             newModel.metComps=newModel.metComps(indexes);
+0094         end
+0095         if isfield(newModel,'S')
+0096             newModel.S=newModel.S(indexes,:);
+0097         end
+0098         if isfield(newModel,'unconstrained')
+0099             newModel.unconstrained=newModel.unconstrained(indexes);
+0100         end
+0101         if isfield(newModel,'metMiriams')
+0102             newModel.metMiriams=newModel.metMiriams(indexes,:);
+0103         end
+0104         if isfield(newModel,'inchis')
+0105             newModel.inchis=newModel.inchis(indexes);
+0106         end
+0107         if isfield(newModel,'metSmiles')
+0108             newModel.metSmiles=newModel.metSmiles(indexes);
+0109         end
+0110         if isfield(newModel,'metFormulas')
+0111             newModel.metFormulas=newModel.metFormulas(indexes);
+0112         end
+0113         if isfield(newModel,'metFrom')
+0114             newModel.metFrom=newModel.metFrom(indexes);
+0115         end
+0116         if isfield(newModel,'metCharges')
+0117             newModel.metCharges=newModel.metCharges(indexes);
+0118         end
+0119         if isfield(newModel,'metDeltaG')
+0120             newModel.metDeltaG=newModel.metDeltaG(indexes);
+0121         end
+0122     case 'genes'
+0123         if isfield(newModel,'genes')
+0124             newModel.genes=newModel.genes(indexes);
+0125         end
+0126         if isfield(newModel,'geneComps')
+0127             newModel.geneComps=newModel.geneComps(indexes);
+0128         end
+0129         if isfield(newModel,'geneMiriams')
+0130             newModel.geneMiriams=newModel.geneMiriams(indexes);
+0131         end
+0132         if isfield(newModel,'geneShortNames')
+0133             newModel.geneShortNames=newModel.geneShortNames(indexes);
+0134         end
+0135         if isfield(newModel,'proteins')
+0136             newModel.proteins=newModel.proteins(indexes);
+0137         end
+0138         if isfield(newModel,'rxnGeneMat')
+0139             newModel.rxnGeneMat=newModel.rxnGeneMat(:,indexes);
+0140         end
+0141     case 'comps'
+0142         if isfield(newModel,'comps')
+0143             newModel.comps=newModel.comps(indexes);
+0144         end
+0145         if isfield(newModel,'compNames')
+0146             newModel.compNames=newModel.compNames(indexes);
+0147         end
+0148         if isfield(newModel,'compOutside')
+0149             newModel.compOutside=newModel.compOutside(indexes);
+0150         end
+0151         if isfield(newModel,'compMiriams')
+0152             newModel.compMiriams=newModel.compMiriams(indexes);
+0153         end
+0154         [~,J]=sort(indexes); % The *index* of compartment is used in next fields
+0155         if isfield(newModel,'metComps')
+0156             [toreplace, bywhat] = ismember(newModel.metComps,1:length(J));
+0157             newModel.metComps(toreplace) = J(bywhat(toreplace));
+0158         end
+0159         if isfield(model,'rxnComps')
+0160             [toreplace, bywhat] = ismember(model.rxnComps,1:length(J));
+0161             model.rxnComps(toreplace) = J(bywhat(toreplace));
+0162         end
+0163         if isfield(model,'geneComps')
+0164             [toreplace, bywhat] = ismember(model.geneComps,1:length(J));
+0165             model.geneComps(toreplace) = J(bywhat(toreplace));
+0166         end
+0167 end
+0168 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/predictLocalization.html b/doc/core/predictLocalization.html new file mode 100644 index 000000000..8b7b0ddfd --- /dev/null +++ b/doc/core/predictLocalization.html @@ -0,0 +1,1247 @@ + + + + Description of predictLocalization + + + + + + + + + +
Home > core > predictLocalization.m
+ + + +

predictLocalization +

+ +

PURPOSE ^

+
predictLocalization
+ +

SYNOPSIS ^

+
function [outModel, geneLocalization, transportStruct, scores,removedRxns] = predictLocalization(model, GSS,defaultCompartment, transportCost, maxTime, plotResults)
+ +

DESCRIPTION ^

+
 predictLocalization
+    Tries to assign reactions to compartments in a manner that is in
+    agreement with localization predictors while at the same time
+    maintaining connectivity.
+
+   Input:
+    model                   a model structure. If the model contains
+                           several compartments they will be merged
+    GSS                     a gene scoring structure as from parseScores
+    defaultCompartment      transport reactions are expressed as diffusion
+                           between the defaultCompartment and the others.
+                           This is usually the cytosol. The default
+                           compartment must have a match in GSS
+    transportCost           the cost for including a transport reaction. If
+                           this a scalar then the same cost is used for
+                           all metabolites. It can also be a vector of
+                           costs with the same dimension as model.mets.
+                           Note that negative costs will result in that
+                           transport of the metabolite is encouraged (optional,
+                           default 0.5)
+    maxTime                 maximum optimization time in minutes (optional,
+                           default 15)
+    plotResults             true if the results should be plotted during the
+                           optimization (optional, default false)
+
+   Output:
+    outModel                the resulting model structure
+    geneLocalization        structure with the genes and their resulting
+                           localization
+    transportStruct         structure with the transport reactions that had
+                           to be inferred and between which compartments
+    scores                  structure that contains the total score history
+                           together with the score based on gene
+                           localization and the score based on included
+                           transport reactions
+    removedRxns             cell array with the reaction ids that had to be
+                           removed in order to have a connected input
+                           model
+
+    This function requires that the starting network is connected when it
+    is in one compartment. Reactions that are unconnected are removed and
+    saved in removedRxns. Try running fillGaps to have a more connected
+    input model if there are many such reactions. The input model should
+    also not include any exchange, demand or sink reactions, otherwise this
+    function would not provide any results.
+
+    In the final model all metabolites are produced in at least one
+    reaction. This does not guarantee a fully functional model since there
+    can be internal loops. Transport reactions are only included as passive
+    diffusion (A <=> B).
+
+    The score of a model is the sum of scores for all genes in their
+    assigned compartment minus the cost of all transport reactions that had
+    to be included. A gene can only be assigned to one compartment. This is
+    a simplification to keep the problem size down. The problem is solved
+    using simulated annealing.
+
+ Usage: [outModel, geneLocalization, transportStruct, scores,...
+       removedRxns] = predictLocalization(model, GSS,...
+       defaultCompartment, transportCost, maxTime, plotResults)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 function [outModel, geneLocalization, transportStruct, scores,...
+0002     removedRxns] = predictLocalization(model, GSS,...
+0003     defaultCompartment, transportCost, maxTime, plotResults)
+0004 % predictLocalization
+0005 %    Tries to assign reactions to compartments in a manner that is in
+0006 %    agreement with localization predictors while at the same time
+0007 %    maintaining connectivity.
+0008 %
+0009 %   Input:
+0010 %    model                   a model structure. If the model contains
+0011 %                           several compartments they will be merged
+0012 %    GSS                     a gene scoring structure as from parseScores
+0013 %    defaultCompartment      transport reactions are expressed as diffusion
+0014 %                           between the defaultCompartment and the others.
+0015 %                           This is usually the cytosol. The default
+0016 %                           compartment must have a match in GSS
+0017 %    transportCost           the cost for including a transport reaction. If
+0018 %                           this a scalar then the same cost is used for
+0019 %                           all metabolites. It can also be a vector of
+0020 %                           costs with the same dimension as model.mets.
+0021 %                           Note that negative costs will result in that
+0022 %                           transport of the metabolite is encouraged (optional,
+0023 %                           default 0.5)
+0024 %    maxTime                 maximum optimization time in minutes (optional,
+0025 %                           default 15)
+0026 %    plotResults             true if the results should be plotted during the
+0027 %                           optimization (optional, default false)
+0028 %
+0029 %   Output:
+0030 %    outModel                the resulting model structure
+0031 %    geneLocalization        structure with the genes and their resulting
+0032 %                           localization
+0033 %    transportStruct         structure with the transport reactions that had
+0034 %                           to be inferred and between which compartments
+0035 %    scores                  structure that contains the total score history
+0036 %                           together with the score based on gene
+0037 %                           localization and the score based on included
+0038 %                           transport reactions
+0039 %    removedRxns             cell array with the reaction ids that had to be
+0040 %                           removed in order to have a connected input
+0041 %                           model
+0042 %
+0043 %    This function requires that the starting network is connected when it
+0044 %    is in one compartment. Reactions that are unconnected are removed and
+0045 %    saved in removedRxns. Try running fillGaps to have a more connected
+0046 %    input model if there are many such reactions. The input model should
+0047 %    also not include any exchange, demand or sink reactions, otherwise this
+0048 %    function would not provide any results.
+0049 %
+0050 %    In the final model all metabolites are produced in at least one
+0051 %    reaction. This does not guarantee a fully functional model since there
+0052 %    can be internal loops. Transport reactions are only included as passive
+0053 %    diffusion (A <=> B).
+0054 %
+0055 %    The score of a model is the sum of scores for all genes in their
+0056 %    assigned compartment minus the cost of all transport reactions that had
+0057 %    to be included. A gene can only be assigned to one compartment. This is
+0058 %    a simplification to keep the problem size down. The problem is solved
+0059 %    using simulated annealing.
+0060 %
+0061 % Usage: [outModel, geneLocalization, transportStruct, scores,...
+0062 %       removedRxns] = predictLocalization(model, GSS,...
+0063 %       defaultCompartment, transportCost, maxTime, plotResults)
+0064 
+0065 if nargin<4
+0066     transportCost=ones(numel(model.mets),1)*0.5;
+0067 end
+0068 if numel(transportCost)==1
+0069     transportCost=ones(numel(model.mets),1)*transportCost;
+0070 end
+0071 transportCost=transportCost(:);
+0072 
+0073 if numel(transportCost)~=numel(model.mets)
+0074     EM='The vector of transport costs must have the same dimension as model.mets';
+0075     dispEM(EM,true);
+0076 end
+0077 if nargin<5
+0078     maxTime=15;
+0079 end
+0080 if nargin<6
+0081     plotResults=false;
+0082 end
+0083 
+0084 if isfield(model,'rxnComps')
+0085     model=rmfield(model,'rxnComps');
+0086     EM='The model structure contains information about reaction compartmentalization. This is not supported by this function. The rxnComps field has been deleted';
+0087     dispEM(EM,false);
+0088 end
+0089 if isfield(model,'geneComps')
+0090     model=rmfield(model,'geneComps');
+0091     EM='The model structure contains information about gene compartmentalization. This is not supported by this function. The geneComps field has been deleted';
+0092     dispEM(EM,false);
+0093 end
+0094 
+0095 defaultCompartment=char(defaultCompartment);
+0096 I=ismember(defaultCompartment,GSS.compartments);
+0097 if I==false
+0098     EM='defaultCompartment not found in GSS';
+0099     dispEM(EM);
+0100 end
+0101 
+0102 if numel(model.comps)>1
+0103     EM='The model has several compartments. All compartments will be merged';
+0104     dispEM(EM,false);
+0105     model=mergeCompartments(model,true,true);
+0106 end
+0107 
+0108 noGenes = ismember(model.genes,GSS.genes);
+0109 if ~all(noGenes)
+0110     EM=['For ' num2str(numel(find(~noGenes))) ' of ' num2str(numel(model.genes)) ' model genes no data was found in GSS'];
+0111     dispEM(EM,false);
+0112 end
+0113 
+0114 %***Begin formating the data structures
+0115 
+0116 %Expand the model so that iso-enzymes have different reactions
+0117 model=expandModel(model);
+0118 
+0119 %Identify reactions that have to be deleted because the involved mets are
+0120 %never produced. This is done in an iterative manner
+0121 removedRxns={};
+0122 %This is to keep track of which metabolites are removed in this step. It is
+0123 %needed to adjust the transport costs
+0124 originalModelMets=model.mets;
+0125 while 1
+0126     irrevModel=convertToIrrev(model);
+0127     
+0128     I=sum(irrevModel.S>0,2);
+0129     
+0130     %Pretend that the unconstrained metabolites are made enough
+0131     if isfield(irrevModel,'unconstrained')
+0132         I(irrevModel.unconstrained~=0)=2;
+0133     end
+0134     metsToDelete=false(numel(model.mets),1);
+0135     
+0136     %This is not very neat but iterate through each metabolite and check
+0137     %whether it can be produced (without using only one isolated reversible
+0138     %reaction)
+0139     for i=1:numel(irrevModel.mets)
+0140         %If something can be made in two reactions then everything is fine.
+0141         %If it can be made in one reaction it is fine unless it is through
+0142         %an isolated reversible reaction (which can act as a mini loop)
+0143         if I(i)<2
+0144             if I(i)==1
+0145                 %Find the reaction where this metabolite is produced
+0146                 [~, J]=find(irrevModel.S(i,:)>0);
+0147                 
+0148                 %Check the metabolites that are consumed in this reaction.
+0149                 %The problem is if any of them is only produced in the
+0150                 %opposite reversible reaction
+0151                 K=irrevModel.S(:,J)<0;
+0152                 check=find(K & I<=1);
+0153                 
+0154                 for j=1:numel(check)
+0155                     %Find the reactions where it participates
+0156                     [~, L]=find(irrevModel.S(check(j),:)>0);
+0157                     
+0158                     if ~isempty(L)
+0159                         rxn=irrevModel.rxns(J);
+0160                         rxnRev=irrevModel.rxns(L);
+0161                         if strcmp(strrep(rxn,'_REV',''),strrep(rxnRev,'_REV',''))
+0162                             metsToDelete(i)=true;
+0163                         end
+0164                     else
+0165                         %If the metabolite was never produced then do
+0166                         %nothing and deal with it when the loop gets there
+0167                         continue;
+0168                     end
+0169                 end
+0170             else
+0171                 %Not made anywhere
+0172                 metsToDelete(i)=true;
+0173             end
+0174         end
+0175     end
+0176     
+0177     if any(metsToDelete)
+0178         %Delete any reactions involving any of the metsToDelete
+0179         [~, I]=find(model.S(metsToDelete,:));
+0180         removedRxns=[removedRxns;model.rxns(I)];
+0181         model=removeReactions(model,I,true,true);
+0182     else
+0183         %All bad reactions deleted
+0184         break;
+0185     end
+0186 end
+0187 
+0188 %Adjust the transport costs
+0189 transportCost=transportCost(ismember(originalModelMets,model.mets));
+0190 
+0191 %Assign fake genes to reactions without genes. This is just to make things
+0192 %easier later on
+0193 I=find(sum(model.rxnGeneMat,2)==0);
+0194 for i=1:numel(I)
+0195     model.genes=[model.genes;['&&FAKE&&' num2str(i)]];
+0196     if isfield(model,'geneShortNames')
+0197         model.geneShortNames=[model.geneShortNames;{''}];
+0198     end
+0199     if isfield(model,'geneMiriams')
+0200         model.geneMiriams=[model.geneMiriams;{[]}];
+0201     end
+0202     if isfield(model,'proteins')
+0203         model.proteins=[model.proteins;{[]}];
+0204     end
+0205     if isfield(model,'geneFrom')
+0206         model.geneFrom=[model.geneFrom;{{'FAKE'}}];
+0207     end
+0208     model.rxnGeneMat(I(i),numel(model.genes))=1;
+0209     model.grRules{I(i)}='';
+0210 end
+0211 
+0212 %Update the GSS. All genes, fake or real, for which there is no evidence
+0213 %gets a score 0.5 in all compartments. Also just to make it easier further
+0214 %on
+0215 I=setdiff(model.genes,GSS.genes);
+0216 GSS.genes=[GSS.genes;I];
+0217 GSS.scores=[GSS.scores;ones(numel(I),numel(GSS.compartments))*0.5];
+0218 
+0219 %Gene complexes should be moved together in order to be biologically
+0220 %relevant. The average score for the genes is used for each compartment.
+0221 %This is done by changing the model so that gene complexes are used as a
+0222 %single gene name and then a score is calculated for that "gene".
+0223 
+0224 %Only "and"-relationships exist after expandModel
+0225 genes=unique(model.grRules);
+0226 nGenes=strrep(genes,'(','');
+0227 nGenes=strrep(nGenes,')','');
+0228 %nGenes=strrep(nGenes,' and ','_and_');
+0229 complexes=setdiff(nGenes,model.genes);
+0230 if ~isempty(complexes)
+0231     if isempty(complexes{1}) %Empty grRules also come up here
+0232         complexes(1)=[];
+0233     end
+0234 end
+0235 cScores=zeros(numel(complexes),numel(GSS.compartments));
+0236 for i=1:numel(complexes)
+0237     genesInComplex=regexp(complexes{i},' and ','split');
+0238     
+0239     %Find these genes in GSS
+0240     [I, J]=ismember(genesInComplex,GSS.genes);
+0241     
+0242     if any(I)
+0243         %Get the average of the genes that were found
+0244         mScores=mean(GSS.scores(J(I),:));
+0245         
+0246         %And add 0.5 for the genes that were not found in order to be
+0247         %consistent with non-complexes
+0248         mScores=(mScores.*sum(I)+(numel(genesInComplex)-sum(I))*0.5)/numel(genesInComplex);
+0249     else
+0250         EM=['Could not parse grRule "' complexes{i} '". Assigning score 0.0 in all compartments'];
+0251         dispEM(EM,false);
+0252         mScores=ones(1,numel(genesInComplex))*0.5;
+0253     end
+0254     cScores(i,:)=mScores;
+0255     
+0256     %Add this complex as a new gene
+0257     model.genes=[model.genes;complexes{i}];
+0258     if isfield(model,'geneMiriams')
+0259         model.geneMiriams=[model.geneMiriams;{[]}];
+0260     end
+0261     if isfield(model,'geneShortNames')
+0262         model.geneShortNames=[model.geneShortNames;{''}];
+0263     end
+0264     if isfield(model,'proteins')
+0265         model.proteins=[model.proteins;{''}];
+0266     end
+0267     if isfield(model,'geneFrom')
+0268         model.geneFrom=[model.geneFrom;{'COMPLEX'}];
+0269     end
+0270     %Find the reactions which had the original complex and change them to
+0271     %use the new "gene"
+0272     I=ismember(model.grRules,['(' complexes{i} ')']);
+0273     
+0274     %Should check more carefully if there can be an error here
+0275     if ~isempty(I)
+0276         model.rxnGeneMat(I,:)=0; %Ok since the split on "or" was applied
+0277         model.rxnGeneMat(I,numel(model.genes))=1;
+0278     end
+0279 end
+0280 
+0281 %Add the new "genes"
+0282 GSS.genes=[GSS.genes;complexes];
+0283 GSS.scores=[GSS.scores;cScores];
+0284 
+0285 %After merging the complexes it could happen that there are genes that are
+0286 %no longer in use. Delete such genes
+0287 model=removeReactions(model,{},false,true);
+0288 
+0289 %Exchange reactions, defined as involving an unconstrained metabolite, are
+0290 %special in that they have to stay in the defaultCompartment. This means
+0291 %that uptake/excretion of metabolites is always via the default
+0292 %compartment. This is a small simplification, but should be valid in most
+0293 %cases
+0294 [~, I]=getExchangeRxns(model);
+0295 
+0296 %It will be easier later on if the same place. Put them in the beginning
+0297 J=1:numel(model.rxns);
+0298 J(I)=[];
+0299 model=permuteModel(model,[I;J'],'rxns');
+0300 
+0301 %Number of exchange reactions
+0302 nER=numel(I);
+0303 
+0304 %Also put the exchange metabolites in the beginning
+0305 if isfield(model,'unconstrained')
+0306     I=find(model.unconstrained);
+0307     J=1:numel(model.mets);
+0308     J(I)=[];
+0309     model=permuteModel(model,[I;J'],'mets');
+0310     %Also reorder the transport costs
+0311     transportCost=transportCost([I;J']);
+0312     %Number of exchange metabolites
+0313     nEM=numel(I);
+0314 else
+0315     nEM=0;
+0316 end
+0317 
+0318 %There is no point of having genes for exchange reactions, so delete them.
+0319 %Also to make computations easier
+0320 model.rxnGeneMat(1:nER,:)=0;
+0321 model.grRules(1:nER)={''};
+0322 
+0323 %Remove unused genes
+0324 model=removeReactions(model,{},false,true);
+0325 
+0326 %Remove genes with no match to the model and reorder so that the genes are
+0327 %in the same order as model.genes. Since the fake genes are already added
+0328 %so that all genes in model exist in GSS it is fine to do like this
+0329 [~, J]=ismember(model.genes,GSS.genes);
+0330 GSS.genes=model.genes;
+0331 GSS.scores=GSS.scores(J,:);
+0332 
+0333 %Reorder the GSS so that the first index corresponds to the default
+0334 %compartment
+0335 [~, J]=ismember(defaultCompartment,GSS.compartments);
+0336 reorder=1:numel(GSS.compartments);
+0337 reorder(J)=[];
+0338 reorder=[J reorder];
+0339 GSS.scores=GSS.scores(:,reorder);
+0340 GSS.compartments=GSS.compartments(reorder);
+0341 
+0342 %Since it is only checked whether the metabolites can be synthesized, there
+0343 %is no need to care about the stoichiometry. Change to -1/1 to simplify
+0344 %later. Keep the S matrix for later though
+0345 oldS=model.S;
+0346 model.S(model.S>0)=1;
+0347 model.S(model.S<0)=-1;
+0348 
+0349 %Here is a bit of a trick. To avoid the recurring calculation which
+0350 %reactions are reversible, the reversible reactions have the coefficients
+0351 %-10/10 instead of -1/1
+0352 model.S(:,model.rev==1)=model.S(:,model.rev==1).*10;
+0353 
+0354 %***Begin problem formulation
+0355 
+0356 %Some numbers that are good to have
+0357 nRxns=numel(model.rxns)-nER; %Excluding exchange rxns
+0358 nMets=numel(model.mets)-nEM; %Excluding exchange mets
+0359 nGenes=numel(model.genes);
+0360 nComps=numel(GSS.compartments);
+0361 
+0362 %Create a big stoichiometric matrix that will be the current model. In
+0363 %order to have faster simulations the maximal model size is declared and
+0364 %reactions are then moved within it.
+0365 
+0366 %First the original model (with the first nE being exchange rxns), then
+0367 %reserve space for number of rxns minus exchange rxns for each non-default
+0368 %compartment, then transport reactions for all non-exchange mets between
+0369 %the default compartment and all others.
+0370 %NOTE: Kept eye()*0 since eye() can be used to include all transport from
+0371 %the beginning
+0372 s=repmat(eye(nMets)*0,1,nComps-1);
+0373 s=[zeros(numel(model.mets)-nMets,size(s,2));s];
+0374 S=[model.S sparse(numel(model.mets),nRxns*(nComps-1)) s];
+0375 s=[sparse(nMets*(nComps-1),numel(model.rxns)+nRxns*(nComps-1)) eye(nMets*(nComps-1))*0];
+0376 S=[S;s];
+0377 
+0378 %Also replicate the transport costs
+0379 transportCost=[transportCost(1:nEM);repmat(transportCost(nEM+1:end),nComps,1)];
+0380 
+0381 %Create a binary matrix that says where the genes are in the current
+0382 %solution
+0383 g2c=false(nGenes,nComps);
+0384 %All genes start in the default compartment
+0385 g2c(:,1)=true;
+0386 
+0387 %Start of main optimization loop
+0388 tic;
+0389 bestScore=-inf;
+0390 bestS=[];
+0391 bestg2c=[];
+0392 
+0393 %Temp for testing
+0394 plotScore=[];
+0395 nTrans=[];
+0396 totScore=[];
+0397 minScore=sum(min(GSS.scores,[],2));
+0398 maxScore=sum(max(GSS.scores,[],2));
+0399 
+0400 while toc<maxTime*60
+0401     %Pick a random gene, weighted by it is current score minus the best
+0402     %score for that gene (often 1.0, but can be 0.5 for no genes or average
+0403     %for complexes). Genes with bad fits are more likely to be moved. This
+0404     %formulation never moves a gene from its best compartment. Therefore a
+0405     %small uniform weight is added
+0406     [I, J]=find(g2c);
+0407     geneToMove=randsample(nGenes,1,true,max(GSS.scores(I,:),[],2)-GSS.scores(sub2ind(size(g2c),I,J))+0.1);
+0408     
+0409     %Sample among possible compartments to move to. Add a larger weight to
+0410     %even out the odds a little. Also a way of getting rid of loops where
+0411     %the same set of genes are moved back and forth several times
+0412     toComp=randsample(nComps,1,true,GSS.scores(geneToMove,:)+0.2);
+0413     
+0414     %Check that it moves to a new compartment
+0415     if toComp==find(g2c(geneToMove,:))
+0416         continue;
+0417     end
+0418     
+0419     %Moves the gene
+0420     [newS, newg2c]=moveGene(S,model,g2c,geneToMove,toComp,nRxns,nMets);
+0421     
+0422     %Tries to connect the network. If this was not possible in 10
+0423     %iterations, then abort. If more than 20 modifications were needed then
+0424     %it is unlikely that it will be a lower score
+0425     wasConnected=false;
+0426     for j=1:10
+0427         %Find the metabolites that are now unconnected
+0428         unconnected=findUnconnected(newS,nEM);
+0429         
+0430         %Continue if there are still unconnected
+0431         if any(unconnected)
+0432             %For each gene find out how many of these could be connected if
+0433             %the gene was moved and how many would be disconnected by
+0434             %moving that gene
+0435             [geneIndex, moveTo, deltaConnected, deltaScore]=selectGenes(newS,nEM,nMets,nER,nRxns,model,unconnected,g2c,GSS);
+0436             
+0437             %Score which gene would be the best to move. The highest
+0438             %deltaScore is 1.0. It should be possible to move a gene from
+0439             %worst to best compartment even if it disconnects, say, 1.5
+0440             %more metabolites
+0441             [score, I]=max(1.5*deltaScore+deltaConnected);
+0442             
+0443             %Check if it has to add a transport or if there is a gene that
+0444             %could be moved order to have a more connected network
+0445             hasToAddTransport=true;
+0446             if ~isempty(deltaConnected)
+0447                 if score>0
+0448                     hasToAddTransport=false;
+0449                 end
+0450             end
+0451             
+0452             %If it is possible to move any gene in order to have a more
+0453             %connected network, then move the best one
+0454             if hasToAddTransport==false
+0455                 [newS, newg2c]=moveGene(newS,model,g2c,geneIndex(I),moveTo(I),nRxns,nMets);
+0456             else
+0457                 %Choose a random unconnected metabolite that should be
+0458                 %connected
+0459                 transMet=unconnected(randsample(numel(unconnected),1));
+0460                 
+0461                 %First get where the metabolite is now
+0462                 comps=ceil((transMet-nEM)/((size(S,1)-nEM)/nComps));
+0463                 
+0464                 %Find the corresponding metabolite index if it were in the
+0465                 %default compartment
+0466                 dcIndex=transMet-(comps-1)*nMets;
+0467                 
+0468                 %Then get the indexes of that metabolite in all
+0469                 %compartments
+0470                 allIndexes=dcIndex;
+0471                 for k=1:nComps-1
+0472                     allIndexes=[allIndexes;dcIndex+nMets*k];
+0473                 end
+0474                 
+0475                 %It could be that some of these are not used in any
+0476                 %reaction. Get only the ones which are
+0477                 I=sum(newS(allIndexes,:)~=0,2)>0;
+0478                 
+0479                 %Then get the ones that are used but not in unconnected.
+0480                 %These are metabolites that could potentially be
+0481                 %transported to connect transMet
+0482                 connectedUsed=setdiff(allIndexes(I),unconnected);
+0483                 
+0484                 %This may be an error but leave it for now. It seems to
+0485                 %happen if nothing can be connected in one step
+0486                 if isempty(connectedUsed)
+0487                     break;
+0488                 end
+0489                 
+0490                 %If transMet is in the default compartment then everything
+0491                 %is fine, just connect it to a random one
+0492                 if transMet==dcIndex
+0493                     newS=addTransport(newS,nRxns,nER,nMets,nEM,nComps,transMet,connectedUsed(randsample(numel(connectedUsed),1)));
+0494                 else
+0495                     %If one of the connectedUsed is in the default
+0496                     %compartment then connect to that one
+0497                     I=connectedUsed(connectedUsed<(nMets+nEM));
+0498                     if any(I)
+0499                         newS=addTransport(newS,nRxns,nER,nMets,nEM,nComps,transMet,I(randsample(numel(I),1)));
+0500                     else
+0501                         %This is if the only way to connect it is by adding
+0502                         %two transport reactions, going via the default
+0503                         %compartment
+0504                         break;
+0505                     end
+0506                 end
+0507             end
+0508         else
+0509             wasConnected=true;
+0510             break;
+0511         end
+0512     end
+0513     
+0514     %If the network was connected in a new way, it is possible that some
+0515     %transport reactions are no longer needed. They should be removed
+0516     if wasConnected==true
+0517         %These are the metabolites that are being transported
+0518         activeTransport=find(sum(newS(:,nER+nRxns*nComps+1:end),2));
+0519         
+0520         %Get the metabolites that are unconnected if transport was not used
+0521         unconnected=findUnconnected(newS(:,1:nER+nRxns*nComps),nEM);
+0522         
+0523         %Find the transport reactions that are not needed and delete them
+0524         I=setdiff(activeTransport,unconnected);
+0525         
+0526         %Since both metabolites in a transport rxns must be connected for
+0527         %the reaction to be deleted, the sum over the colums should be 4
+0528         newS(:,find(sum(newS(I,nER+nRxns*nComps+1:end))==4)+nER+nRxns*nComps)=0;
+0529         
+0530         %Score the solution and determine whether to keep it as a new
+0531         %solution
+0532         [score, geneScore, trCost]=scoreModel(newS,newg2c,GSS,transportCost);
+0533         
+0534         %If it was the best solution so far, keep it
+0535         if score>bestScore
+0536             bestScore=score;
+0537             bestS=newS;
+0538             bestg2c=newg2c;
+0539         end
+0540         
+0541         %This should not be steepest descent later
+0542         if score>=bestScore% || exp((score-bestScore)*7)>rand()
+0543             plotScore=[plotScore;geneScore];
+0544             nTrans=[nTrans;trCost];
+0545             totScore=[totScore;score];
+0546             S=newS;
+0547             g2c=newg2c;
+0548             
+0549             if plotResults==true
+0550                 subplot(3,2,1);
+0551                 spy(S);
+0552                 subplot(3,2,2);
+0553                 plot(plotScore,'r');
+0554                 xlabel('Gene score');
+0555                 subplot(3,2,3);
+0556                 plot((plotScore-minScore)/(maxScore-minScore),'r');
+0557                 xlabel('Gene score relative to predictions');
+0558                 subplot(3,2,4);
+0559                 plot(nTrans,'g');
+0560                 xlabel('Transport cost');
+0561                 subplot(3,2,5);
+0562                 plot(totScore,'b');
+0563                 xlabel('Total score');
+0564                 subplot(3,2,6);
+0565                 pause(0.2);
+0566             end
+0567         end
+0568     end
+0569 end
+0570 scores.totScore=score;
+0571 scores.geneScore=geneScore;
+0572 scores.transCost=trCost;
+0573 
+0574 %Find which metabolites are transported and to where
+0575 [I, J]=find(bestS(nEM+1:nEM+nMets,end-nMets*(nComps-1)+1:end));
+0576 J=ceil(J/nMets+1);
+0577 transportStruct.mets=model.metNames(I+nEM);
+0578 transportStruct.toComp=GSS.compartments(J);
+0579 
+0580 [I, J]=find(bestg2c);
+0581 geneLocalization.genes=GSS.genes(I);
+0582 geneLocalization.comps=GSS.compartments(J);
+0583 
+0584 %Resort the gene names
+0585 [~, I]=sort(geneLocalization.genes);
+0586 geneLocalization.genes=geneLocalization.genes(I);
+0587 geneLocalization.comps=geneLocalization.comps(I);
+0588 
+0589 %Remove the fake genes
+0590 I=strncmp('&&FAKE&&',geneLocalization.genes,8);
+0591 geneLocalization.genes(I)=[];
+0592 geneLocalization.comps(I)=[];
+0593 
+0594 %Put together the model. This is done by first duplicating the S matrix
+0595 %into the different compartments. Then the transport reactions are added
+0596 %based on transportStruct. By now model.S should have the same size as the
+0597 %S matrix used in the optimization, but with conserved stoichiometry. In
+0598 %the final step all reactions and metabolites that are not used in the S
+0599 %matrix from the optimization are deleted from the model
+0600 outModel=model;
+0601 outModel.S=oldS;
+0602 
+0603 %This is the S matrix without exchange rxns or metabolites
+0604 copyPart=outModel.S(nEM+1:end,nER+1:end);
+0605 
+0606 %Replicate to give the rxnGeneMat for the full system
+0607 copyRxnGeneMat=outModel.rxnGeneMat(nER+1:end,:);
+0608 outModel.rxnGeneMat=[outModel.rxnGeneMat;repmat(copyRxnGeneMat,nComps-1,1)];
+0609 
+0610 %First fix the compartments. The model is already ordered with the exchange
+0611 %metabolites first. The original model may contain one or two compartments,
+0612 %depending on whether any exchange metabolites are defined
+0613 nStartComps=numel(outModel.comps);
+0614 if nStartComps==1
+0615     outModel.comps={'1'};
+0616     outModel.compNames=GSS.compartments(1);
+0617 else
+0618     if model.metComps(1)==1
+0619         outModel.compNames(1)=GSS.compartments(1);
+0620     else
+0621         outModel.compNames(2)=GSS.compartments(1);
+0622     end
+0623 end
+0624 outModel.compNames=[outModel.compNames;GSS.compartments(2:end)];
+0625 
+0626 %Ugly little loop
+0627 for i=1:numel(GSS.compartments)-1
+0628     outModel.comps=[outModel.comps;num2str(numel(outModel.comps)+1)];
+0629 end
+0630 %This information is not known from the data, so empty fields are added
+0631 outModel.compOutside=cell(numel(outModel.comps),1);
+0632 outModel.compOutside(:)={''};
+0633 
+0634 for i=1:nComps-1
+0635     outModel.S=[outModel.S sparse(size(outModel.S,1),nRxns)];
+0636     outModel.S=[outModel.S;[sparse(nMets,nRxns*i+nER) copyPart]];
+0637     outModel.rxns=[outModel.rxns;strcat(outModel.rxns(nER+1:nER+nRxns),'_',GSS.compartments{i+1})];
+0638     outModel.rxnNames=[outModel.rxnNames;strcat(outModel.rxnNames(nER+1:nER+nRxns),' (',GSS.compartments{i+1},')')];
+0639     outModel.lb=[outModel.lb;outModel.lb(nER+1:nER+nRxns)];
+0640     outModel.ub=[outModel.ub;outModel.ub(nER+1:nER+nRxns)];
+0641     outModel.rev=[outModel.rev;outModel.rev(nER+1:nER+nRxns)];
+0642     outModel.c=[outModel.c;outModel.c(nER+1:nER+nRxns)];
+0643     if isfield(outModel,'grRules')
+0644         outModel.grRules=[outModel.grRules;outModel.grRules(nER+1:nER+nRxns)];
+0645     end
+0646     if isfield(outModel,'subSystems')
+0647         outModel.subSystems=[outModel.subSystems;outModel.subSystems(nER+1:nER+nRxns)];
+0648     end
+0649     if isfield(outModel,'eccodes')
+0650         outModel.eccodes=[outModel.eccodes;outModel.eccodes(nER+1:nER+nRxns)];
+0651     end
+0652     if isfield(outModel,'rxnFrom')
+0653         outModel.rxnFrom=[outModel.rxnFrom;outModel.rxnFrom(nER+1:nER+nRxns)];
+0654     end
+0655     if isfield(outModel,'rxnMiriams')
+0656         outModel.rxnMiriams=[outModel.rxnMiriams;outModel.rxnMiriams(nER+1:nER+nRxns)];
+0657     end
+0658     if isfield(outModel,'rxnNotes')
+0659         outModel.rxnNotes=[outModel.rxnNotes;outModel.rxnNotes(nER+1:nER+nRxns)];
+0660     end
+0661     if isfield(outModel,'rxnReferences')
+0662         outModel.rxnReferences=[outModel.rxnReferences;outModel.rxnReferences(nER+1:nER+nRxns)];
+0663     end
+0664     if isfield(outModel,'rxnConfidenceScores')
+0665         outModel.rxnConfidenceScores=[outModel.rxnConfidenceScores;outModel.rxnConfidenceScores(nER+1:nER+nRxns)];
+0666     end
+0667     if isfield(outModel,'rxnDeltaG')
+0668         outModel.rxnDeltaG=[outModel.rxnDeltaG;outModel.rxnDeltaG(nER+1:nER+nRxns)];
+0669     end
+0670     outModel.mets=[outModel.mets;strcat(outModel.mets(nEM+1:nEM+nMets),'_',GSS.compartments{i+1})];
+0671     outModel.metNames=[outModel.metNames;outModel.metNames(nEM+1:nEM+nMets)];
+0672     outModel.b=[outModel.b;outModel.b(nEM+1:nEM+nMets,:)];
+0673     I=ones(nMets,1)*nStartComps+i;
+0674     outModel.metComps=[outModel.metComps;I];
+0675     if isfield(outModel,'inchis')
+0676         outModel.inchis=[outModel.inchis;outModel.inchis(nEM+1:nEM+nMets)];
+0677     end
+0678     if isfield(outModel,'metSmiles')
+0679         outModel.metSmiles=[outModel.metSmiles;outModel.metSmiles(nEM+1:nEM+nMets)];
+0680     end
+0681     if isfield(outModel,'unconstrained')
+0682         outModel.unconstrained=[outModel.unconstrained;outModel.unconstrained(nEM+1:nEM+nMets)];
+0683     end
+0684     if isfield(outModel,'metMiriams')
+0685         outModel.metMiriams=[outModel.metMiriams;outModel.metMiriams(nEM+1:nEM+nMets)];
+0686     end
+0687     if isfield(outModel,'metFormulas')
+0688         outModel.metFormulas=[outModel.metFormulas;outModel.metFormulas(nEM+1:nEM+nMets)];
+0689     end
+0690     if isfield(outModel,'metFrom')
+0691         outModel.metFrom=[outModel.metFrom;outModel.metFrom(nEM+1:nEM+nMets)];
+0692     end
+0693     if isfield(outModel,'metCharges')
+0694         outModel.metCharges=[outModel.metCharges;outModel.metCharges(nEM+1:nEM+nMets)];
+0695     end
+0696     if isfield(outModel,'metDeltaG')
+0697         outModel.metDeltaG=[outModel.metDeltaG;outModel.metDeltaG(nEM+1:nEM+nMets)];
+0698     end
+0699 end
+0700 
+0701 %Add the transport reactions
+0702 transS=bestS(:,numel(outModel.rxns)+1:end);
+0703 J=sum(transS)>0; %Active rxns
+0704 
+0705 %Transport reactions are written in a different way compared to a "real"
+0706 %stoichimetric matrix. This is to fix that
+0707 transS(transS~=0)=1;
+0708 transS(1:nEM+nMets,:)=transS(1:nEM+nMets,:)*-1;
+0709 I=find(sum(transS>0,2));
+0710 nTransRxns=numel(I);
+0711 outModel.S=[outModel.S transS(:,J)];
+0712 filler=ones(nTransRxns,1);
+0713 outModel.lb=[outModel.lb;filler*-1000];
+0714 outModel.ub=[outModel.ub;filler*1000];
+0715 outModel.rev=[outModel.rev;filler];
+0716 outModel.c=[outModel.c;filler*0];
+0717 outModel.rxnGeneMat=[outModel.rxnGeneMat;sparse(nTransRxns,numel(outModel.genes))];
+0718 
+0719 for i=1:numel(I)
+0720     outModel.rxns=[outModel.rxns;strcat('transport',num2str(i))];
+0721     outModel.rxnNames=[outModel.rxnNames;['Transport of ',outModel.metNames{I(i)}]];
+0722     if isfield(outModel,'grRules')
+0723         outModel.grRules=[outModel.grRules;{''}];
+0724     end
+0725     if isfield(outModel,'rxnMiriams')
+0726         outModel.rxnMiriams=[outModel.rxnMiriams;{[]}];
+0727     end
+0728     if isfield(outModel,'subSystems')
+0729         if any(cellfun(@(x) iscell(x), outModel.subSystems))
+0730             outModel.subSystems=[outModel.subSystems;{{'Inferred transport reactions'}}];
+0731         else
+0732             outModel.subSystems=[outModel.subSystems;{'Inferred transport reactions'}];
+0733         end
+0734     end
+0735     if isfield(outModel,'eccodes')
+0736         outModel.eccodes=[outModel.eccodes;{''}];
+0737     end
+0738     if isfield(outModel,'rxnFrom')
+0739         outModel.rxnFrom=[outModel.rxnFrom;{''}];
+0740     end
+0741     if isfield(outModel,'rxnNotes')
+0742         outModel.rxnNotes=[outModel.rxnNotes;{''}];
+0743     end
+0744     if isfield(outModel,'rxnReferences')
+0745         outModel.rxnReferences=[outModel.rxnReferences;{''}];
+0746     end
+0747     if isfield(outModel,'rxnConfidenceScores')
+0748         outModel.rxnConfidenceScores=[outModel.rxnConfidenceScores;NaN];
+0749     end
+0750     if isfield(outModel,'rxnDeltaG')
+0751         outModel.rxnDeltaG=[outModel.rxnDeltaG;NaN];
+0752     end
+0753 end
+0754 
+0755 %Then remove all reactions and metabolites that aren't used in the final
+0756 %solution from the optimization
+0757 [~, J]=find(bestS(:,1:nER+nComps*nRxns));
+0758 K=true(numel(outModel.rxns),1);
+0759 K(J)=false;
+0760 K(end-nTransRxns+1:end)=false;
+0761 outModel=removeReactions(outModel,K,true);
+0762 
+0763 %Remove all fake genes
+0764 I=strncmp('&&FAKE&&',outModel.genes,8);
+0765 outModel.genes(I)=[];
+0766 if isfield(outModel,'geneMiriams')
+0767     outModel.geneMiriams(I)=[];
+0768 end
+0769 if isfield(outModel,'geneShortNames')
+0770     outModel.geneShortNames(I)=[];
+0771 end
+0772 if isfield(outModel,'proteins')
+0773     outModel.proteins(I)=[];
+0774 end
+0775 outModel.rxnGeneMat(:,I)=[];
+0776 
+0777 %Fix grRules and reconstruct rxnGeneMat
+0778 [grRules,rxnGeneMat] = standardizeGrRules(outModel,true);
+0779 outModel.grRules = grRules;
+0780 outModel.rxnGeneMat = rxnGeneMat;
+0781 end
+0782 
+0783 %Moves a gene and all associated reactions from one compartment to another
+0784 function [S, g2c]=moveGene(S,model,g2c,geneToMove,toComp,nRxns,nMets)
+0785 %Find the current compartment and update to the new one
+0786 currentComp=find(g2c(geneToMove,:));
+0787 g2c(geneToMove,:)=false;
+0788 g2c(geneToMove,toComp)=true;
+0789 
+0790 %Find the reactions in the original model that the gene controls
+0791 [I, ~]=find(model.rxnGeneMat(:,geneToMove));
+0792 
+0793 %Calculate their current positions in the S matrix
+0794 oldRxns=I+(currentComp-1)*nRxns;
+0795 
+0796 %And their new positions
+0797 newRxns=I+(toComp-1)*nRxns;
+0798 
+0799 %The metabolite ids also have to be changed in order to match the new
+0800 %compartment
+0801 metChange=nMets*(toComp-currentComp);
+0802 
+0803 %Update the reactions
+0804 [I, J, K]=find(S(:,oldRxns));
+0805 I=I+metChange;
+0806 
+0807 %Move the reactions
+0808 S(:,oldRxns)=0;
+0809 S(sub2ind(size(S),I,newRxns(J)))=K;
+0810 end
+0811 
+0812 %Finds which metabolites are unconnected, in the sense that they are never
+0813 %a product or only a product in a reversible reaction where one reactant is
+0814 %only a product in the opposite direction of that reaction. This function
+0815 %ignores exchange metabolites. Returns a vector of metabolite indexes.
+0816 %metsToCheck is an array of metabolite indexes to check for connectivity.
+0817 %If not supplied then all metabolites are checked
+0818 function unconnected=findUnconnected(S,nEM,metsToCheck)
+0819 if nargin>2
+0820     %Do this by deleting everything from the network that is not in
+0821     %metsToCheck and that is not exchange metabolites
+0822     I=false(size(S,1),1);
+0823     I(1:nEM)=true;
+0824     I(metsToCheck)=true;
+0825     S=S(I,:);
+0826 end
+0827 
+0828 em=false(size(S,1),1);
+0829 em(1:nEM)=true;
+0830 
+0831 %Construct a matrix in which the reversible reactions are inverted
+0832 I=sum(S>2,1) | sum(S>2,1);
+0833 revS=S;
+0834 revS(:,I)=revS(:,I)*-1;
+0835 
+0836 %First calculate the ones that are ok
+0837 %Produced in 2 rxns, is exchange, is not used at all, is produced in
+0838 %non-reversible, involved in more than 1 reversible reactions
+0839 connected=sum(S>0,2)>1 | em | sum(S~=0,2)==0 | sum(S(:,~I)>0,2)>0 | sum(S(:,I)~=0,2)>1;
+0840 
+0841 %Then get the ones that are unconnected because they are never produced
+0842 unconnected=sum(S>0 | revS>0,2)==0 & connected==false;
+0843 
+0844 %Then get the ones that are potentially unconnected
+0845 maybeUnconnected=~connected & ~unconnected;
+0846 %maybeUnconnected=find(maybeUnconnectedS);
+0847 
+0848 %The metabolites in maybeUnconnected are involved in one reversible
+0849 %reaction and not produced in any other reaction. This means that the
+0850 %reactions which have at least one met in maybeUnconnected as reactant and
+0851 %one as product are unconnected. The metabolites in maybeUnconnected that
+0852 %are present in those reactions are then dead ends
+0853 deadRxns=any(S(maybeUnconnected,:)>0) & any(S(maybeUnconnected,:)<0);
+0854 
+0855 %Get the mets involved in any of those reactions
+0856 problematic=any(S(:,deadRxns)~=0,2);
+0857 
+0858 %If any of these are in the maybeUnconnected list then the metabolite is
+0859 %unconnected
+0860 unconnected(problematic & maybeUnconnected)=true;
+0861 
+0862 %Map back to metsToCheck
+0863 if nargin>2
+0864     unconnected=metsToCheck(unconnected(nEM+1:end));
+0865 else
+0866     unconnected=find(unconnected);
+0867 end
+0868 end
+0869 
+0870 %Given a set of unconnected metabolites, this function tries to move each
+0871 %gene that could connect any of them, calculates the number of newly
+0872 %connected metabolites minus the number of newly disconnected metabolites.
+0873 %As some metabolites are very connected, only 25 genes are checked. Genes
+0874 %that have a low score in their current compartment are more likely to be
+0875 %moved
+0876 function [geneIndex, moveTo, deltaConnected, deltaScore]=selectGenes(S,nEM,nMets,nER,nRxns,model,unconnected,g2c,GSS)
+0877 %If moveTo is 0 then the gene cannot connect any of the metabolites
+0878 moveTo=zeros(numel(model.genes),1);
+0879 deltaConnected=zeros(numel(model.genes),1);
+0880 
+0881 %First get where the metabolites are now
+0882 nComps=size(g2c,2);
+0883 comps=ceil((unconnected-nEM)/((size(S,1)-nEM)/nComps));
+0884 
+0885 %Find the corresponding metabolite indexes if they all were in the default
+0886 %compartment
+0887 dcIndexes=unique(unconnected-(comps-1)*nMets);
+0888 
+0889 %Then find them if they were in any other compartment
+0890 allIndexes=dcIndexes;
+0891 for i=1:nComps-1
+0892     allIndexes=[allIndexes;dcIndexes+nMets*i];
+0893 end
+0894 
+0895 %Also check which reversible reactions that could be used
+0896 I=sum(S>2,1) | sum(S>2,1);
+0897 revS=S;
+0898 revS(:,I)=revS(:,I)*-1;
+0899 
+0900 %Find all reactions that could make any of the unconnected metabolites in
+0901 %some other compartment
+0902 newMets=setdiff(allIndexes,unconnected);
+0903 [~, potential]=find(S(newMets,:)>0 | revS(newMets,:)>0);
+0904 potential(potential<=nER | potential>nER+nRxns*nComps)=[]; %No exchange rxns or transport rxns
+0905 
+0906 %Map J to the real metabolic reactions in model
+0907 rxnComps=ceil((potential-nER)/(nRxns));
+0908 
+0909 %Find the corresponding reaction indexes if they all were in the default
+0910 %compartment
+0911 dcRxnIndexes=potential-(rxnComps-1)*nRxns;
+0912 
+0913 %Get the genes for those reactions
+0914 genes=find(sum(model.rxnGeneMat(dcRxnIndexes,:)>0,1));
+0915 
+0916 %For some cases there can be very many reactions to connect something. This
+0917 %is in particular true in the beginning of the optimization if, say, ATP is
+0918 %unconnected. Therefore limit the number of genes to be checked to 25.
+0919 %Weigh so that genes with bad scores in their current compartment are more
+0920 %likely to be moved.
+0921 
+0922 %Get scores for these genes
+0923 [~, J]=find(g2c(genes,:));
+0924 
+0925 %Add a small weight so that genes in their best compartment could be moved
+0926 %as well
+0927 geneScores=GSS.scores(sub2ind(size(g2c),genes(:),J));
+0928 modGeneScores=1.1-geneScores;
+0929 if numel(genes)>25
+0930     rGenes=genes(randsample(numel(genes),min(numel(genes),25),true,modGeneScores));
+0931     
+0932     %The sampling with weights could give duplicates
+0933     rGenes=unique(rGenes);
+0934     
+0935     %Reorder the geneScores to match
+0936     [~, I]=ismember(rGenes,genes);
+0937     geneScores=geneScores(I);
+0938     genes=rGenes;
+0939 end
+0940 for i=1:numel(genes)
+0941     %Since one gene is moved at a time, only metabolites involved in any of
+0942     %the reactions for that gene can become unconnected. This helps to
+0943     %speed up the algorithm. First get all involved reactions in the
+0944     %default compartment
+0945     rxns=find(model.rxnGeneMat(:,genes(i)));
+0946     
+0947     %Then get their mets
+0948     mets=find(sum(model.S(:,rxns)~=0,2)>0);
+0949     
+0950     %Then get their indexes in all compartments
+0951     allIndexes=mets;
+0952     for j=1:nComps-1
+0953         allIndexes=[allIndexes;mets+nMets*j];
+0954     end
+0955     
+0956     %Check which of the unconnected metabolites that these reactions
+0957     %correspond to. This could have been done earlier, but it is fast. The
+0958     %reversibility check is skipped because it is unlikely to be an issue
+0959     %here. Worst case is that the gene is tested once to much
+0960     [I, ~]=find(model.S(:,rxns));
+0961     moveToComps=unique(comps(ismember(dcIndexes,I)));
+0962     
+0963     %Try to move the gene to each of the compartments
+0964     bestMove=-inf;
+0965     bestComp=[];
+0966     for j=1:numel(moveToComps)
+0967         newS=moveGene(S,model,g2c,genes(i),moveToComps(j),nRxns,nMets);
+0968         
+0969         %Check how many metabolites that are unconnected after moving the
+0970         %gene
+0971         dConnected=numel(unconnected)-numel(findUnconnected(newS,nEM,[allIndexes;unconnected]));
+0972         if dConnected>bestMove
+0973             bestMove=dConnected;
+0974             bestComp=moveToComps(j);
+0975         end
+0976     end
+0977     
+0978     %Add the difference in connectivity and where the genes should be moved
+0979     moveTo(genes(i))=bestComp;
+0980     deltaConnected(genes(i))=bestMove;
+0981 end
+0982 
+0983 %Finish up
+0984 geneIndex=genes(:);
+0985 moveTo=moveTo(geneIndex);
+0986 deltaConnected=deltaConnected(geneIndex);
+0987 deltaScore=GSS.scores(sub2ind(size(g2c),geneIndex(:),moveTo))-geneScores;
+0988 end
+0989 
+0990 %Small function to add a transport reactions between two metabolites.
+0991 %Transport reactions are written as having a coefficient 2.0 for both
+0992 %reactant and product. This is not a "real" reaction, but since all normal
+0993 %reactions have coefficient -1/1 or -10/10 it is a compact way of writing
+0994 %it
+0995 function S=addTransport(S,nRxns,nER,nMets,nEM,nComps,metA,metB)
+0996 mets=[metA;metB];
+0997 %Find the current compartments for the metabolites
+0998 comps=ceil((mets-nEM)/((size(S,1)-nEM)/nComps));
+0999 
+1000 if sum(comps==1)~=1
+1001     EM='Tried to create a transport reaction from a non-default compartment';
+1002     dispEM(EM);
+1003 end
+1004 
+1005 %Calculate the reaction index
+1006 rIndex=(nER+nRxns*nComps)+mets(comps~=1)-nEM-nMets;
+1007 
+1008 S(mets,rIndex)=2;
+1009 end
+1010 
+1011 %Scores a network based on the localization of the genes and the number of
+1012 %transporter reactions used
+1013 function [score, geneScore, transportCost]=scoreModel(S,g2c,GSS,transportCost)
+1014 [I, J]=find(g2c);
+1015 geneScore=sum(GSS.scores(sub2ind(size(g2c),I,J)));
+1016 [I, ~]=find(S==2);
+1017 I=unique(I);
+1018 transportCost=sum(transportCost(I));
+1019 score=geneScore-transportCost;
+1020 end
+1021 
+1022 % To avoid dependency on stats toolbox, use this alternative implementation
+1023 % of randsample, source:
+1024 % https://github.com/gpeyre/numerical-tours/blob/dacee30081c04ef5f67b26b387ead85f2b193af9/matlab/toolbox_signal/randsample.m
+1025 function y = randsample(n, k, replace, w)
+1026 %RANDSAMPLE Random sample, with or without replacement.
+1027 %   Y = RANDSAMPLE(N,K) returns Y as a vector of K values sampled uniformly
+1028 %   at random, without replacement, from the integers 1:N.
+1029 %
+1030 %   Y = RANDSAMPLE(POPULATION,K) returns K values sampled uniformly at
+1031 %   random, without replacement, from the values in the vector POPULATION.
+1032 %
+1033 %   Y = RANDSAMPLE(...,REPLACE) returns a sample taken with replacement if
+1034 %   REPLACE is true, or without replacement if REPLACE is false (the default).
+1035 %
+1036 %   Y = RANDSAMPLE(...,true,W) returns a weighted sample, using positive
+1037 %   weights W, taken with replacement.  W is often a vector of probabilities.
+1038 %   This function does not support weighted sampling without replacement.
+1039 %
+1040 %   Example:  Generate a random sequence of the characters ACGT, with
+1041 %   replacement, according to specified probabilities.
+1042 %
+1043 %      R = randsample('ACGT',48,true,[0.15 0.35 0.35 0.15])
+1044 %
+1045 %   See also RAND, RANDPERM.
+1046 
+1047 %   Copyright 1993-2008 The MathWorks, Inc.
+1048 %   $Revision: 1.1.4.3 $  $Date: 2008/12/01 08:09:34 $
+1049 
+1050 if nargin < 2
+1051     error('stats:randsample:TooFewInputs','Requires two input arguments.');
+1052 elseif numel(n) == 1
+1053     population = [];
+1054 else
+1055     population = n;
+1056     n = numel(population);
+1057     if length(population)~=n
+1058        error('stats:randsample:BadPopulation','POPULATION must be a vector.');
+1059     end
+1060 end
+1061 
+1062 if nargin < 3
+1063     replace = false;
+1064 end
+1065 
+1066 if nargin < 4
+1067     w = [];
+1068 elseif ~isempty(w)
+1069     if length(w) ~= n
+1070         if isempty(population)
+1071             error('stats:randsample:InputSizeMismatch',...
+1072                   'W must have length equal to N.');
+1073         else
+1074             error('stats:randsample:InputSizeMismatch',...
+1075                   'W must have the same length as the population.');
+1076         end
+1077     else
+1078         p = w(:)' / sum(w);
+1079     end
+1080 end
+1081 
+1082 switch replace
+1083 
+1084 % Sample with replacement
+1085 case {true, 'true', 1}
+1086     if isempty(w)
+1087         y = ceil(n .* rand(k,1));
+1088     else
+1089         [dum, y] = histc(rand(k,1),[0 cumsum(p)]);
+1090     end
+1091 
+1092 % Sample without replacement
+1093 case {false, 'false', 0}
+1094     if k > n
+1095         if isempty(population)
+1096             error('stats:randsample:SampleTooLarge',...
+1097         'K must be less than or equal to N for sampling without replacement.');
+1098         else
+1099             error('stats:randsample:SampleTooLarge',...
+1100                   'K must be less than or equal to the population size.');
+1101         end
+1102     end
+1103 
+1104     if isempty(w)
+1105         % If the sample is a sizeable fraction of the population,
+1106         % just randomize the whole population (which involves a full
+1107         % sort of n random values), and take the first k.
+1108         if 4*k > n
+1109             rp = randperm(n);
+1110             y = rp(1:k);
+1111 
+1112         % If the sample is a small fraction of the population, a full sort
+1113         % is wasteful.  Repeatedly sample with replacement until there are
+1114         % k unique values.
+1115         else
+1116             x = zeros(1,n); % flags
+1117             sumx = 0;
+1118             while sumx < k
+1119                 x(ceil(n * rand(1,k-sumx))) = 1; % sample w/replacement
+1120                 sumx = sum(x); % count how many unique elements so far
+1121             end
+1122             y = find(x > 0);
+1123             y = y(randperm(k));
+1124         end
+1125     else
+1126         error('stats:randsample:NoWeighting',...
+1127               'Weighted sampling without replacement is not supported.');
+1128     end
+1129 otherwise
+1130     error('stats:randsample:BadReplaceValue',...
+1131           'REPLACE must be either true or false.');
+1132 end
+1133 
+1134 if ~isempty(population)
+1135     y = population(y);
+1136 else
+1137     y = y(:);
+1138 end
+1139 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/printFluxes.html b/doc/core/printFluxes.html new file mode 100644 index 000000000..58765a14c --- /dev/null +++ b/doc/core/printFluxes.html @@ -0,0 +1,270 @@ + + + + Description of printFluxes + + + + + + + + + +
Home > core > printFluxes.m
+ + + +

printFluxes +

+ +

PURPOSE ^

+
printFluxes
+ +

SYNOPSIS ^

+
function printFluxes(model, fluxes, onlyExchange, cutOffFlux, outputFile,outputString,metaboliteList)
+ +

DESCRIPTION ^

+
 printFluxes
+   Prints reactions and fluxes to the screen or to a file
+
+ Input:
+   model           a model structure
+   fluxes          a vector with fluxes
+   onlyExchange    only print exchange fluxes (optional, default true)
+   cutOffFlux      only print fluxes with absolute values above or equal
+                   to this value (optional, default 10^-8)
+   outputFile      a file to save the print-out to (optional, default is
+                   output to the command window)
+   outputString    a string that specifies the output of each reaction
+                   (optional, default '%rxnID\t(%rxnName):\t%flux\n')
+   metaboliteList  cell array of metabolite names. Only reactions
+                   involving any of these metabolites will be
+                   printed (optional)
+
+ The following codes are available for user-defined output strings:
+
+ %rxnID      reaction ID
+ %rxnName    reaction name
+ %lower      lower bound
+ %upper      upper bound
+ %obj        objective coefficient
+ %eqn        equation
+ %flux       flux
+ %element    equation using the metabolite formulas rather than
+             metabolite names
+ %unbalanced "(*)" if the reaction is unbalanced and "(-)" if it could
+             not be parsed
+ %lumped     equation where the elemental compositions for the left/right
+             hand sides are lumped
+
+ Usage: printFluxes(model, fluxes, onlyExchange, cutOffFlux, outputFile,...
+                    outputString, metaboliteList)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function printFluxes(model, fluxes, onlyExchange, cutOffFlux, outputFile,outputString,metaboliteList)
+0002 % printFluxes
+0003 %   Prints reactions and fluxes to the screen or to a file
+0004 %
+0005 % Input:
+0006 %   model           a model structure
+0007 %   fluxes          a vector with fluxes
+0008 %   onlyExchange    only print exchange fluxes (optional, default true)
+0009 %   cutOffFlux      only print fluxes with absolute values above or equal
+0010 %                   to this value (optional, default 10^-8)
+0011 %   outputFile      a file to save the print-out to (optional, default is
+0012 %                   output to the command window)
+0013 %   outputString    a string that specifies the output of each reaction
+0014 %                   (optional, default '%rxnID\t(%rxnName):\t%flux\n')
+0015 %   metaboliteList  cell array of metabolite names. Only reactions
+0016 %                   involving any of these metabolites will be
+0017 %                   printed (optional)
+0018 %
+0019 % The following codes are available for user-defined output strings:
+0020 %
+0021 % %rxnID      reaction ID
+0022 % %rxnName    reaction name
+0023 % %lower      lower bound
+0024 % %upper      upper bound
+0025 % %obj        objective coefficient
+0026 % %eqn        equation
+0027 % %flux       flux
+0028 % %element    equation using the metabolite formulas rather than
+0029 %             metabolite names
+0030 % %unbalanced "(*)" if the reaction is unbalanced and "(-)" if it could
+0031 %             not be parsed
+0032 % %lumped     equation where the elemental compositions for the left/right
+0033 %             hand sides are lumped
+0034 %
+0035 % Usage: printFluxes(model, fluxes, onlyExchange, cutOffFlux, outputFile,...
+0036 %                    outputString, metaboliteList)
+0037 
+0038 if nargin<3
+0039     onlyExchange=true;
+0040 end
+0041 if nargin<4
+0042     cutOffFlux=10^-8;
+0043 end
+0044 if isempty(cutOffFlux)
+0045     cutOffFlux=10^-8;
+0046 end
+0047 if nargin<5
+0048     fid=1;
+0049 else
+0050     if ~isempty(outputFile)
+0051         outputFile=char(outputFile);
+0052         fid=fopen(outputFile,'w');
+0053     else
+0054         fid=1;
+0055     end
+0056 end
+0057 if nargin<6 || isempty(outputString)
+0058     outputString='%rxnID\t(%rxnName):\t%flux\n';
+0059 else
+0060     outputString=char(outputString);
+0061 end
+0062 if nargin<7
+0063     metaboliteList={};
+0064 else
+0065     metaboliteList=convertCharArray(metaboliteList);
+0066 end
+0067 if isempty(fluxes)
+0068     EM='Empty vector of fluxes, solveLP possibly returned infeasible';
+0069     dispEM(EM);
+0070 elseif size(fluxes,1)~=numel(model.rxns)
+0071     EM='The number of fluxes and the number of reactions must be the same';
+0072     dispEM(EM);
+0073 end
+0074 
+0075 %Only keep reactions involving the defined metabolites
+0076 if ~isempty(metaboliteList)
+0077     I=ismember(upper(model.metNames),upper(metaboliteList));
+0078     [~, K]=find(model.S(I,:));
+0079     
+0080     %Delete all other reactions
+0081     toDelete=true(numel(model.rxns),1);
+0082     toDelete(K)=false;
+0083     model=removeReactions(model,toDelete);
+0084     fluxes(toDelete,:)=[];
+0085 end
+0086 
+0087 if onlyExchange==true
+0088     fprintf(fid,'EXCHANGE FLUXES:\n');
+0089 else
+0090     fprintf(fid,'FLUXES:\n');
+0091 end
+0092 
+0093 %Remove reactions which are below the cut off
+0094 toDelete=abs(fluxes)<cutOffFlux;
+0095 toDelete=all(toDelete,2);
+0096 model=removeReactions(model,toDelete,true,true);
+0097 fluxes(toDelete,:)=[];
+0098 
+0099 if any(strfind(outputString,'%eqn'))
+0100     %Construct the equations
+0101     eqn=constructEquations(model);
+0102 else
+0103     eqn=cell(numel(model.rxns),1);
+0104     eqn(:)={''};
+0105 end
+0106 if any(strfind(outputString,'%element'))
+0107     %For printing equations using the composition
+0108     cModel=model;
+0109     cModel.metNames=cModel.metFormulas;
+0110     cModel.metNames(cellfun(@isempty,cModel.metNames))={'?'};
+0111     element=constructEquations(cModel);
+0112 else
+0113     element=cell(numel(model.rxns),1);
+0114     element(:)={''};
+0115 end
+0116 
+0117 if any(strfind(outputString,'%unbalanced')) || any(strfind(outputString,'%lumped'))
+0118     balanceStructure=getElementalBalance(model);
+0119 end
+0120 
+0121 unbalanced=cell(numel(model.rxns),1);
+0122 unbalanced(:)={''};
+0123 if any(strfind(outputString,'%unbalanced'))
+0124     unbalanced(balanceStructure.balanceStatus==0)={'(*)'};
+0125     unbalanced(balanceStructure.balanceStatus<0)={'(-)'};
+0126 end
+0127 
+0128 lumped=cell(numel(model.rxns),1);
+0129 lumped(:)={''};
+0130 if any(strfind(outputString,'%lumped'))
+0131     for i=1:numel(model.rxns)
+0132         leftGroup='';
+0133         rightGroup='';
+0134         for j=1:numel(balanceStructure.elements.names)
+0135             I=balanceStructure.leftComp(i,j);
+0136             if I~=0
+0137                 if I==1
+0138                     leftGroup=[leftGroup balanceStructure.elements.abbrevs{j}];
+0139                 else
+0140                     leftGroup=[leftGroup balanceStructure.elements.abbrevs{j} num2str(I)];
+0141                 end
+0142             end
+0143             I=balanceStructure.rightComp(i,j);
+0144             if I~=0
+0145                 if I==1
+0146                     rightGroup=[rightGroup balanceStructure.elements.abbrevs{j}];
+0147                 else
+0148                     rightGroup=[rightGroup balanceStructure.elements.abbrevs{j} num2str(I)];
+0149                 end
+0150             end
+0151         end
+0152         if model.rev(i)
+0153             lumped{i}=[leftGroup ' <=> ' rightGroup];
+0154         else
+0155             lumped{i}=[leftGroup ' => ' rightGroup];
+0156         end
+0157     end
+0158 end
+0159 
+0160 for i=1:numel(model.rxns)
+0161     %Only print if it's an exchange reaction or if all reactions should be
+0162     %printed. Exchange reactions only have reactants or only products.
+0163     reactants=model.S(:,i)<0;
+0164     products=model.S(:,i)>0;
+0165     
+0166     %Only print if the absolute value is >= cutOffFlux
+0167     if (onlyExchange==false || (~any(reactants) || ~any(products)))
+0168         printString=outputString;
+0169         
+0170         %Produce the final string
+0171         printString=strrep(printString,'%rxnID',model.rxns{i});
+0172         printString=strrep(printString,'%eqn',eqn{i});
+0173         printString=strrep(printString,'%rxnName',model.rxnNames{i});
+0174         printString=strrep(printString,'%lower',num2str(model.lb(i)));
+0175         printString=strrep(printString,'%upper',num2str(model.ub(i)));
+0176         printString=strrep(printString,'%obj',num2str(model.c(i)));
+0177         printString=strrep(printString,'%flux',num2str(fluxes(i,:)));
+0178         printString=strrep(printString,'%element',element{i});
+0179         printString=strrep(printString,'%unbalanced',unbalanced{i});
+0180         printString=strrep(printString,'%lumped',lumped{i});
+0181         fprintf(fid,printString);
+0182     end
+0183 end
+0184 
+0185 if fid~=1
+0186     fprintf('File successfully saved.\n');
+0187     fclose(fid);
+0188 end
+0189 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/printModel.html b/doc/core/printModel.html new file mode 100644 index 000000000..887a7beb1 --- /dev/null +++ b/doc/core/printModel.html @@ -0,0 +1,147 @@ + + + + Description of printModel + + + + + + + + + +
Home > core > printModel.m
+ + + +

printModel +

+ +

PURPOSE ^

+
printModel
+ +

SYNOPSIS ^

+
function printModel(model,rxnList,outputString,outputFile,metaboliteList)
+ +

DESCRIPTION ^

+
 printModel
+   Prints reactions to the screen or to a file
+
+   model           a model structure
+   rxnList         either a cell array of reaction IDs, a logical vector 
+                   with the same number of elements as reactions in the model,
+                   or a vector of indexes to remove (optional, default
+                   model.rxns)
+   outputString    a string that specifies the output of each reaction (optional,
+                   default '%rxnID (%rxnName)\n\t%eqn [%lower %upper]\n')
+   outputFile      a file to save the print-out to (optional, default is output to
+                   the command window)
+   metaboliteList  cell array of metabolite names. Only reactions
+                   involving any of these metabolites will be 
+                   printed (optional)
+
+   The following codes are available for user-defined output strings:
+
+   %rxnID      reaction ID
+   %rxnName    reaction name
+   %lower      lower bound
+   %upper      upper bound
+   %obj        objective coefficient
+   %eqn        equation
+   %element    equation using the metabolite formulas rather than
+               metabolite names
+   %unbalanced "(*)" if the reaction is unbalanced and "(-)" if it could not
+               be parsed
+   %lumped     equation where the elemental compositions for the left/right
+               hand sides are lumped
+
+   NOTE: This is just a wrapper function around printFluxes. It is
+           intended to be used when there is no flux distribution.
+
+ Usage: printModel(model,rxnList,outputString,outputFile,metaboliteList)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function printModel(model,rxnList,outputString,outputFile,metaboliteList)
+0002 % printModel
+0003 %   Prints reactions to the screen or to a file
+0004 %
+0005 %   model           a model structure
+0006 %   rxnList         either a cell array of reaction IDs, a logical vector
+0007 %                   with the same number of elements as reactions in the model,
+0008 %                   or a vector of indexes to remove (optional, default
+0009 %                   model.rxns)
+0010 %   outputString    a string that specifies the output of each reaction (optional,
+0011 %                   default '%rxnID (%rxnName)\n\t%eqn [%lower %upper]\n')
+0012 %   outputFile      a file to save the print-out to (optional, default is output to
+0013 %                   the command window)
+0014 %   metaboliteList  cell array of metabolite names. Only reactions
+0015 %                   involving any of these metabolites will be
+0016 %                   printed (optional)
+0017 %
+0018 %   The following codes are available for user-defined output strings:
+0019 %
+0020 %   %rxnID      reaction ID
+0021 %   %rxnName    reaction name
+0022 %   %lower      lower bound
+0023 %   %upper      upper bound
+0024 %   %obj        objective coefficient
+0025 %   %eqn        equation
+0026 %   %element    equation using the metabolite formulas rather than
+0027 %               metabolite names
+0028 %   %unbalanced "(*)" if the reaction is unbalanced and "(-)" if it could not
+0029 %               be parsed
+0030 %   %lumped     equation where the elemental compositions for the left/right
+0031 %               hand sides are lumped
+0032 %
+0033 %   NOTE: This is just a wrapper function around printFluxes. It is
+0034 %           intended to be used when there is no flux distribution.
+0035 %
+0036 % Usage: printModel(model,rxnList,outputString,outputFile,metaboliteList)
+0037 
+0038 if nargin<2 || isempty(rxnList)
+0039     rxnList=model.rxns;
+0040 elseif ~islogical(rxnList) && ~isnumeric(rxnList)
+0041     rxnList=convertCharArray(rxnList);
+0042 end
+0043 if nargin<3 || isempty(outputString)
+0044     outputString='%rxnID (%rxnName)\n\t%eqn [%lower %upper]\n';
+0045 else
+0046     outputString=char(outputString);
+0047 end
+0048 if nargin<4
+0049     outputFile=[];
+0050 else
+0051     outputFile=char(outputFile);
+0052 end
+0053 if nargin<5
+0054     metaboliteList=[];
+0055 else
+0056     metaboliteList=convertCharArray(metaboliteList);
+0057 end
+0058 
+0059 I=getIndexes(model,rxnList,'rxns',true)*1.00; %To convert it to "fluxes"
+0060 
+0061 if ~isempty(metaboliteList)
+0062     printFluxes(model, I, false, 0.1, outputFile,outputString,metaboliteList);
+0063 else
+0064     printFluxes(model, I, false, 0.1, outputFile,outputString);
+0065 end
+0066 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/printModelStats.html b/doc/core/printModelStats.html new file mode 100644 index 000000000..f7abf19aa --- /dev/null +++ b/doc/core/printModelStats.html @@ -0,0 +1,221 @@ + + + + Description of printModelStats + + + + + + + + + +
Home > core > printModelStats.m
+ + + +

printModelStats +

+ +

PURPOSE ^

+
printModelStats
+ +

SYNOPSIS ^

+
function printModelStats(model, printModelIssues, printDetails)
+ +

DESCRIPTION ^

+
 printModelStats
+   prints some statistics about a model to the screen
+
+   model               a model structure
+   printModelIssues    true if information about unconnected
+                       reactions/metabolites and elemental balancing
+                       should be printed (optional, default false)
+   printDetails        true if detailed information should be printed
+                       about model issues. Only used if printModelIssues
+                       is true (optional, default true)
+
+ Usage: printModelStats(model,printModelIssues, printDetails)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function printModelStats(model, printModelIssues, printDetails)
+0002 % printModelStats
+0003 %   prints some statistics about a model to the screen
+0004 %
+0005 %   model               a model structure
+0006 %   printModelIssues    true if information about unconnected
+0007 %                       reactions/metabolites and elemental balancing
+0008 %                       should be printed (optional, default false)
+0009 %   printDetails        true if detailed information should be printed
+0010 %                       about model issues. Only used if printModelIssues
+0011 %                       is true (optional, default true)
+0012 %
+0013 % Usage: printModelStats(model,printModelIssues, printDetails)
+0014 
+0015 if nargin<2
+0016     printModelIssues=false;
+0017 end
+0018 if nargin<3
+0019     printDetails=true;
+0020 end
+0021 
+0022 fprintf(['Network statistics for ' model.id ': ' model.name '\n']);
+0023 
+0024 %Get which reactions are present in each compartment
+0025 rxnComps=sparse(numel(model.rxns),numel(model.comps));
+0026 
+0027 %For each compartment, find the metabolites that are present in that
+0028 %compartment and then the reactions they are involved in
+0029 for i=1:numel(model.comps)
+0030     [~, I]=find(model.S(model.metComps==i,:));
+0031     rxnComps(I,i)=1;
+0032 end
+0033 
+0034 if isfield(model,'eccodes')
+0035     fprintf(['EC-numbers\t\t\t' num2str(numel(unique(model.eccodes))) '\n']);
+0036 end
+0037 
+0038 %Print information about genes
+0039 if isfield(model,'genes')
+0040     fprintf(['Genes*\t\t\t\t' num2str(numel(model.genes)) '\n']);
+0041     %Find the genes in each compartment
+0042     for i=1:numel(model.comps)
+0043         [~, I]=find(model.rxnGeneMat(rxnComps(:,i)==1,:));
+0044         fprintf(['\t' model.compNames{i} '\t' num2str(numel(unique(I))) '\n']);
+0045     end
+0046 end
+0047 
+0048 %Print information about reactions
+0049 fprintf(['\nReactions*\t\t\t' num2str(numel(model.rxns)) '\n']);
+0050 for i=1:numel(model.comps)
+0051     fprintf(['\t' model.compNames{i} '\t' num2str(sum(rxnComps(:,i))) '\n']);
+0052 end
+0053 
+0054 %Removes the effect of compartments and removes duplicate reactions
+0055 temp=model;
+0056 temp.comps(:)={'s'}; %Set all compartments to be the same
+0057 equ=constructEquations(sortModel(temp,true,true),temp.rxns,false);
+0058 
+0059 fprintf(['Unique reactions**\t' num2str(numel(unique(equ))) '\n']);
+0060 
+0061 %Print information about metabolites
+0062 fprintf(['\nMetabolites\t\t\t' num2str(numel(model.mets)) '\n']);
+0063 for i=1:numel(model.comps)
+0064     fprintf(['\t' model.compNames{i} '\t' num2str(sum(model.metComps==i)) '\n']);
+0065 end
+0066 
+0067 fprintf(['Unique metabolites\t' num2str(numel(unique(model.metNames))) '\n']);
+0068 
+0069 fprintf('\n* Genes and reactions are counted for each compartment if any of the corresponding metabolites are in that compartment. The sum may therefore not add up to the total number.\n');
+0070 fprintf('** Unique reactions are defined as being biochemically unique (no compartmentalization)\n');
+0071 
+0072 %Also print some potential problems if there are any
+0073 if printModelIssues==true
+0074     fprintf(['\nShort model quality summary for ' model.id ': ' model.name '\n']);
+0075     
+0076     %Check that all the metabolites are being used
+0077     involvedMat=model.S;
+0078     involvedMat(involvedMat~=0)=1;
+0079     usedMets=sum(involvedMat,2);
+0080     notPresent=find(usedMets==0);
+0081     if ~isempty(notPresent)
+0082         errorText=['Non-used metabolites\t' num2str(numel(notPresent)) '\n'];
+0083         if printDetails==true
+0084             for i=1:numel(notPresent)
+0085                 errorText=[errorText '\t(' model.mets{notPresent(i)} ') ' model.metNames{notPresent(i)} '\n'];
+0086             end
+0087             errorText=[errorText '\n'];
+0088         end
+0089         fprintf(errorText);
+0090     end
+0091     
+0092     %Check if there are empty reactions
+0093     usedRxns=sum(involvedMat,1);
+0094     notUsed=find(usedRxns==0);
+0095     if ~isempty(notUsed)
+0096         errorText=['Empty reactions\t' num2str(numel(notUsed)) '\n'];
+0097         if printDetails==true
+0098             for i=1:numel(notUsed)
+0099                 errorText=[errorText '\t' model.rxns{notUsed(i)} '\n'];
+0100             end
+0101             errorText=[errorText '\n'];
+0102         end
+0103         fprintf(errorText);
+0104     end
+0105     
+0106     %Check if there are dead-end reactions/metabolites
+0107     [~, deletedReactions, deletedMetabolites]=simplifyModel(model,true,false,false,true);
+0108     
+0109     if ~isempty(deletedReactions)
+0110         errorText=['Dead-end reactions\t' num2str(numel(deletedReactions)) '\n'];
+0111         if printDetails==true
+0112             for i=1:numel(deletedReactions)
+0113                 errorText=[errorText '\t' deletedReactions{i} '\n'];
+0114             end
+0115             errorText=[errorText '\n'];
+0116         end
+0117         fprintf(errorText);
+0118     end
+0119     
+0120     %Ignore non-used metabolites
+0121     deletedMetabolites=setdiff(deletedMetabolites,model.mets(notPresent));
+0122     %Must map to indexes in order to print names
+0123     deletedMetabolites=find(ismember(model.mets,deletedMetabolites));
+0124     if ~isempty(deletedMetabolites)
+0125         errorText=['Dead-end metabolites\t' num2str(numel(deletedMetabolites)) '\n'];
+0126         if printDetails==true
+0127             for i=1:numel(deletedMetabolites)
+0128                 errorText=[errorText '\t(' model.mets{deletedMetabolites(i)} ') ' model.metNames{deletedMetabolites(i)} '\n'];
+0129             end
+0130             errorText=[errorText '\n'];
+0131         end
+0132         fprintf(errorText);
+0133     end
+0134     
+0135     balanceStructure=getElementalBalance(model);
+0136     
+0137     notParsed=find(balanceStructure.balanceStatus<0);
+0138     notBalanced=find(balanceStructure.balanceStatus==0);
+0139     
+0140     if ~isempty(notParsed)
+0141         errorText=['Reactions which could not be elementally balanced\t' num2str(numel(notParsed)) '\n'];
+0142         if printDetails==true
+0143             for i=1:numel(notParsed)
+0144                 errorText=[errorText '\t' model.rxns{notParsed(i)} '\n'];
+0145             end
+0146             errorText=[errorText '\n'];
+0147         end
+0148         fprintf(errorText);
+0149     end
+0150     if ~isempty(notBalanced)
+0151         errorText=['Reactions which are elementally unbalanced\t' num2str(numel(notBalanced)) '\n'];
+0152         if printDetails==true
+0153             names=strcat(balanceStructure.elements.names,{', '});
+0154             for i=1:numel(notBalanced)
+0155                 badOnes=sprintf('%s', names{abs(balanceStructure.leftComp(notBalanced(i),:)-balanceStructure.rightComp(notBalanced(i),:))>10^-7});
+0156                 errorText=[errorText '\t' model.rxns{notBalanced(i)} '\t' badOnes(1:end-2) '\n'];
+0157             end
+0158             errorText=[errorText '\n'];
+0159         end
+0160         fprintf(errorText);
+0161     end
+0162 end
+0163 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/printOrange.html b/doc/core/printOrange.html new file mode 100644 index 000000000..20753a03a --- /dev/null +++ b/doc/core/printOrange.html @@ -0,0 +1,78 @@ + + + + Description of printOrange + + + + + + + + + +
Home > core > printOrange.m
+ + + +

printOrange +

+ +

PURPOSE ^

+
printOrange
+ +

SYNOPSIS ^

+
function orangeString = printOrange(stringToPrint)
+ +

DESCRIPTION ^

+
 printOrange
+   Print orange-colored stringToPrint to the MATLAB Command Window. Only
+   if MATLAB is open with GUI, does not work with command-line MATLAB.
+
+ Input: 
+   stringToPrint   string that should be printed in orange color
+
+ Usage: printOrange(stringToPrint)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function orangeString = printOrange(stringToPrint)
+0002 % printOrange
+0003 %   Print orange-colored stringToPrint to the MATLAB Command Window. Only
+0004 %   if MATLAB is open with GUI, does not work with command-line MATLAB.
+0005 %
+0006 % Input:
+0007 %   stringToPrint   string that should be printed in orange color
+0008 %
+0009 % Usage: printOrange(stringToPrint)
+0010 
+0011 try useDesktop = usejava('desktop'); catch, useDesktop = false; end
+0012 if useDesktop
+0013     orangeString = ['[\b' stringToPrint,']\b'];
+0014 else
+0015     orangeString = stringToPrint;
+0016 end
+0017 if nargout < 1
+0018     % Wrap text to command window size
+0019     sz = get(0, 'CommandWindowSize');
+0020     orangeString = textwrap({orangeString},sz(1));
+0021     orangeString = strjoin(orangeString,'\n');
+0022     fprintf(orangeString);
+0023 end
+0024 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/randomSampling.html b/doc/core/randomSampling.html new file mode 100644 index 000000000..17bf0e439 --- /dev/null +++ b/doc/core/randomSampling.html @@ -0,0 +1,317 @@ + + + + Description of randomSampling + + + + + + + + + +
Home > core > randomSampling.m
+ + + +

randomSampling +

+ +

PURPOSE ^

+
randomSampling
+ +

SYNOPSIS ^

+
function [solutions, goodRxns]=randomSampling(model,nSamples,replaceBoundsWithInf,supressErrors,runParallel,goodRxns,minFlux)
+ +

DESCRIPTION ^

+
 randomSampling
+   Performs random sampling of the solution space, as described in Bordel
+   et al. (2010) PLOS Compt Biol (doi:10.1371/journal.pcbi.1000859).
+
+ Input:
+   model                   a model structure
+   nSamples                the number of solutions to return
+                           (optional, default 1000)
+   replaceBoundsWithInf    replace the largest upper bounds with Inf and
+                           the smallest lower bounds with -Inf. This is
+                           needed in order to get solutions without loops
+                           if your model has for example 1000/-1000 as
+                           arbitary large bounds. If your model only has
+                           "biologically relevant" bounds, then set this
+                           to false (optional, default true)
+   supressErrors           the program will halt if it has problems
+                           finding non-zero solutions which are not
+                           involved in loops. This could be because the
+                           constraints on the model are too relaxed (such
+                           as unlimited glucose uptake) or too strict
+                           (such as too many and too narrow constraints)
+                           (optional, default false)
+   runParallel             speed up calculations by parallel processing.
+                           Requires MATLAB Parallel Computing Toolbox. If
+                           this is not installed, the calculations will
+                           not be parallelized, regardless what is
+                           indicated as runParallel. (optional, default
+                           true)
+   goodRxns                double vector of indexes of those reactions
+                           that are not involved in loops and can be used
+                           as random objective functions, as generated by
+                           a previous run of randomSampling on the same
+                           model (optional, default empty)
+   minFlux                 determines if a second optimization should be
+                           performed for each random sample, to minimize
+                           the number of fluxes and thereby preventing
+                           loops. Typically, loops are averaged out when a
+                           large number of samples are taken, but this is
+                           not always the case (optional, default false)
+
+ Output:
+   solutions               matrix with the solutions
+   goodRxns                double vector of indexes of those reactions
+                           that are not involved in loops or always carry
+                           zero flux and can be used as random objective
+                           functions
+
+ Note: The solutions are generated by maximizing (with random weights) for
+ a random set of three reactions. For reversible reactions it randomly
+ chooses between maximizing and minimizing.
+
+ If the model is a GECKO v3+ ecModel, then usage_prot reactions are not
+ selected for sampling, instead focusing on sampling from the metabolic
+ aspects that form the solution space.
+
+ Usage: solutions = randomSampling(model, nSamples, replaceBoundsWithInf,...
+                       supressErrors, runParallel, goodRxns, minFlux)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 function [solutions, goodRxns]=randomSampling(model,nSamples,replaceBoundsWithInf,supressErrors,runParallel,goodRxns,minFlux)
+0002 % randomSampling
+0003 %   Performs random sampling of the solution space, as described in Bordel
+0004 %   et al. (2010) PLOS Compt Biol (doi:10.1371/journal.pcbi.1000859).
+0005 %
+0006 % Input:
+0007 %   model                   a model structure
+0008 %   nSamples                the number of solutions to return
+0009 %                           (optional, default 1000)
+0010 %   replaceBoundsWithInf    replace the largest upper bounds with Inf and
+0011 %                           the smallest lower bounds with -Inf. This is
+0012 %                           needed in order to get solutions without loops
+0013 %                           if your model has for example 1000/-1000 as
+0014 %                           arbitary large bounds. If your model only has
+0015 %                           "biologically relevant" bounds, then set this
+0016 %                           to false (optional, default true)
+0017 %   supressErrors           the program will halt if it has problems
+0018 %                           finding non-zero solutions which are not
+0019 %                           involved in loops. This could be because the
+0020 %                           constraints on the model are too relaxed (such
+0021 %                           as unlimited glucose uptake) or too strict
+0022 %                           (such as too many and too narrow constraints)
+0023 %                           (optional, default false)
+0024 %   runParallel             speed up calculations by parallel processing.
+0025 %                           Requires MATLAB Parallel Computing Toolbox. If
+0026 %                           this is not installed, the calculations will
+0027 %                           not be parallelized, regardless what is
+0028 %                           indicated as runParallel. (optional, default
+0029 %                           true)
+0030 %   goodRxns                double vector of indexes of those reactions
+0031 %                           that are not involved in loops and can be used
+0032 %                           as random objective functions, as generated by
+0033 %                           a previous run of randomSampling on the same
+0034 %                           model (optional, default empty)
+0035 %   minFlux                 determines if a second optimization should be
+0036 %                           performed for each random sample, to minimize
+0037 %                           the number of fluxes and thereby preventing
+0038 %                           loops. Typically, loops are averaged out when a
+0039 %                           large number of samples are taken, but this is
+0040 %                           not always the case (optional, default false)
+0041 %
+0042 % Output:
+0043 %   solutions               matrix with the solutions
+0044 %   goodRxns                double vector of indexes of those reactions
+0045 %                           that are not involved in loops or always carry
+0046 %                           zero flux and can be used as random objective
+0047 %                           functions
+0048 %
+0049 % Note: The solutions are generated by maximizing (with random weights) for
+0050 % a random set of three reactions. For reversible reactions it randomly
+0051 % chooses between maximizing and minimizing.
+0052 %
+0053 % If the model is a GECKO v3+ ecModel, then usage_prot reactions are not
+0054 % selected for sampling, instead focusing on sampling from the metabolic
+0055 % aspects that form the solution space.
+0056 %
+0057 % Usage: solutions = randomSampling(model, nSamples, replaceBoundsWithInf,...
+0058 %                       supressErrors, runParallel, goodRxns, minFlux)
+0059 
+0060 if nargin<2 | isempty(nSamples)
+0061     nSamples=1000;
+0062 end
+0063 if nargin<3 | isempty(replaceBoundsWithInf)
+0064     replaceBoundsWithInf=true;
+0065 end
+0066 if nargin<4 | isempty(supressErrors)
+0067     supressErrors=false;
+0068 end
+0069 if nargin<5 | isempty(runParallel)
+0070     runParallel=true;
+0071 end
+0072 if nargin<7 | isempty(minFlux)
+0073     minFlux=false;
+0074 end
+0075 
+0076 [ps, oldPoolAutoCreateSetting] = parallelPoolRAVEN(runParallel);
+0077 
+0078 nObjRxns=2; %Number of reactions in the objective function in each iteration
+0079 
+0080 %Simplify the model to speed stuff up a little. Keep original mapping
+0081 originalRxns=model.rxns;
+0082 model=simplifyModel(model,false,false,true,true);
+0083 
+0084 %Then change the bounds to +/- Inf. This is needed in order to not have
+0085 %loops in the solutions
+0086 if replaceBoundsWithInf==true
+0087     model.ub(model.ub==max(model.ub))=Inf;
+0088     if min(model.lb)<0 % Only negative lower bounds should be set to -Inf
+0089         model.lb(model.lb==min(model.lb))=-Inf;
+0090     end
+0091 end
+0092 
+0093 %Check that the model is feasible given the constraints
+0094 [sol,~]=solveLP(model);
+0095 if isempty(sol.x)
+0096     EM='The model has no feasible solution, likely due to incompatible constraints';
+0097     dispEM(EM);
+0098 elseif sol.f==0 && showProgress
+0099     warning('The model objective function cannot reach a non-zero value. This might be intended, so randomSampling will continue, but this could indicate problems with your model')
+0100 end
+0101 
+0102 nRxns = numel(model.rxns);
+0103 %Reactions which can be involved in loops should not be optimized for.
+0104 %Check which reactions reach an arbitary high upper bound
+0105 if nargin<6 || isempty(goodRxns)
+0106     revRxns = transpose(find(model.lb < 0));
+0107     fwdRxns = transpose(find(model.ub > 0));
+0108     rxnList = [fwdRxns,revRxns];
+0109     objList = [ones(numel(fwdRxns),1);-ones(numel(revRxns),1)];
+0110     testSol = zeros(numel(objList),1);
+0111     PB = ProgressBar2(nRxns,'Prepare goodRxns not involved in loops','cli');
+0112 
+0113     parfor i = 1:numel(objList)
+0114         testModel=setParam(model,'obj',rxnList(i),objList(i));
+0115         sol=solveLP(testModel,0);
+0116         if ~isempty(sol.f)
+0117             testSol(i) = sol.x(rxnList(i));
+0118         end
+0119         count(PB);
+0120     end
+0121     testSol  = testSol.*objList;
+0122     goodRxns = true(nRxns,1);
+0123     % Filter out reactions that can reach (-)1000 (= involved in loop)
+0124     goodRxns(fwdRxns(testSol(1:numel(fwdRxns)) > 999)) = false;
+0125     goodRxns(revRxns(testSol(numel(fwdRxns)+1:end) > 999)) = false;
+0126     testSol(revRxns) = testSol(revRxns) + testSol(numel(fwdRxns)+1:end);
+0127     % Filter out reactions that cannot carry flux
+0128     goodRxns(testSol(1:nRxns) == 0) = false;
+0129     % In ecModels do not sample from usage_prot reactions
+0130     if isfield(model,'ec')
+0131         usageRxns = startsWith(model.rxns,'usage_prot_');
+0132         goodRxns(usageRxns) = false;
+0133     end
+0134     goodRxns = find(goodRxns);
+0135 end
+0136 
+0137 %Reserve space for a solution matrix
+0138 sols = zeros(numel(model.rxns),nSamples);
+0139 sols = num2cell(sols,1);
+0140 
+0141 %Main loop
+0142 if nSamples > 0
+0143 
+0144     PB = ProgressBar2(nSamples,'Performing random sampling','cli');
+0145     parfor i=1:nSamples
+0146         badSolutions = 1;
+0147         tmpModel = model;
+0148         while lt(0,badSolutions)
+0149             rxns = randsample(numel(goodRxns),nObjRxns);
+0150             tmpModel.c = zeros(numel(tmpModel.rxns),1);
+0151             
+0152             multipliers = randsample([-1 1],nObjRxns,true);
+0153             multipliers(tmpModel.ub(goodRxns(rxns))<0) = 1;
+0154             
+0155             tmpModel.c(goodRxns(rxns)) = rand(nObjRxns,1).*multipliers;
+0156 
+0157             if true(minFlux)
+0158                 sol=solveLP(tmpModel,1);
+0159             else
+0160                 sol=solveLP(tmpModel,0);
+0161             end
+0162             if any(sol.x) && abs(sol.f)>10^-8
+0163                 sols{i} = sol.x;
+0164                 badSolutions = 0;
+0165             else
+0166                 badSolutions = badSolutions+1;
+0167                 %If it only finds bad solutions then throw an error.
+0168                 if badSolutions == 100 && supressErrors==false
+0169                     error('The program is having problems finding non-zero solutions (ignoring reactions that might be involved in loops). Review the constraints on your model. Set supressErrors to true to ignore this error');
+0170                 end
+0171             end
+0172         end
+0173         count(PB);
+0174     end
+0175 
+0176     %Map to original model
+0177     sols = cell2mat(sols);
+0178     [~, I]=ismember(model.rxns,originalRxns);
+0179     solutions=zeros(numel(originalRxns),nSamples);
+0180     solutions(I,:)=sols;
+0181 else
+0182     solutions=[];
+0183 end
+0184 % Reset original Parallel setting
+0185 ps.Pool.AutoCreate = oldPoolAutoCreateSetting;
+0186 end
+0187 
+0188 %To use instead of the normal Matlab randsample function. This is in order
+0189 %to not depend on the Matlab statistical toolbox.
+0190 function I=randsample(n,k,replacement)
+0191 if nargin<3
+0192     replacement=false;
+0193 end
+0194 %n can be a integer, which leads to I being sampled from 1:n, or it can be
+0195 %a population to sample from.
+0196 if numel(n)==1 && isnumeric(n)
+0197     n=1:n;
+0198 end
+0199 %Loop and get random numbers until the list is unique. This is only a good
+0200 %option is the number of samples is small compared to the population. There
+0201 %are several checks that should be made here, for example regarding size
+0202 %and that the number of samples is <=population size if replacement==false.
+0203 %This is not the case in randomSampling, so such checks are ignored
+0204 while true
+0205     J=randi(numel(n),[k,1]);
+0206     if replacement==true || numel(J)==numel(unique(J))
+0207         I=n(J);
+0208         break;
+0209     end
+0210 end
+0211 I=I(:);
+0212 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/removeBadRxns.html b/doc/core/removeBadRxns.html new file mode 100644 index 000000000..2c3e20e2a --- /dev/null +++ b/doc/core/removeBadRxns.html @@ -0,0 +1,357 @@ + + + + Description of removeBadRxns + + + + + + + + + +
Home > core > removeBadRxns.m
+ + + +

removeBadRxns +

+ +

PURPOSE ^

+
removeBadRxns
+ +

SYNOPSIS ^

+
function [newModel, removedRxns]=removeBadRxns(model,rxnRules,ignoreMets,isNames,balanceElements,refModel,ignoreIntBounds,printReport)
+ +

DESCRIPTION ^

+
 removeBadRxns
+   Iteratively removes reactions which enable production/consumption of some
+   metabolite without any uptake/excretion
+
+   model                   a model structure. For the intented function,
+                           the model shouldn't allow for any uptake/excretion.
+                           The easiest way to achieve this is to import the
+                           model using importModel('filename',false)
+   rxnRules                1: only remove reactions which are unbalanced
+                           2: also remove reactions which couldn't be checked for
+                           mass balancing
+                           3: all reactions can be removed
+                           (optional, default 1)
+   ignoreMets              either a cell array of metabolite IDs, a logical vector
+                           with the same number of elements as metabolites in the model,
+                           of a vector of indexes for metabolites to exclude from
+                           this analysis (optional, default [])
+   isNames                 true if the supplied mets represent metabolite names
+                           (as opposed to IDs). This is a way to delete
+                           metabolites in several compartments at once without
+                           knowing the exact IDs. This only works if ignoreMets
+                           is a cell array (optional, default false)
+   balanceElements         a cell array with the elements for which to
+                           balance the reactions. May contain any
+                           combination of the elements defined in parseFormulas
+                           (optional, default {'C';'P';'S';'N';'O'})
+   refModel                a reference model which can be used to ensure
+                           that the resulting model is still functional.
+                           The intended use is that the reference model is
+                           a copy of model, but with uptake/excretion allowed and
+                           some objectives (such as production of biomass)
+                           constrained to a non-zero flux. Before a
+                           reaction is removed from "model" the function first
+                           checks that the same deletion in "refModel"
+                           doesn't render the problem unfeasible (optional)
+   ignoreIntBounds         true if internal bounds (including reversibility)
+                           should be ignored. Exchange reactions are not affected.
+                           This can be used to find unbalanced solutions which are
+                           not possible using the default constraints (optional,
+                           default false)
+   printReport             true if a report should be printed (optional,
+                           default false)
+
+   newModel                   a model structure after the problematic
+                           reactions have been deleted
+   removedRxns             a cell array with the reactions that were
+                           removed
+
+   The purpose of this function is to remove reactions which enable
+   production/consumption of metabolites even when exchange reactions aren't used.
+   Many models, especially if they are automatically inferred from
+   databases, will have unbalanced reactions which allow for
+   net-production/consumption of metabolites without any consumption/excretion.
+   A common reason for this is when general compounds have different meaning
+   in different reactions (as DNA has in these two reactions).
+       dATP + dGTP + dCTP + dTTP <=> DNA + 4 PPi
+       0.25 dATP + 0.25 dGTP + 0.25 dCTP + 0.25 dTTP <=> DNA + PPi
+   Reactions that are problematic like this are always elementally
+   unbalanced, but it is not always that you would like to exclude all
+   unbalanced reactions from your model.
+   This function tries to remove as few problematic reactions as possible
+   so that the model cannot produce/consume anything from nothing. This is done by
+   repeatedly calling makeSomething/consumeSomething, checking if any of
+   the involved reactions are elementally unbalanced, remove one of them,
+   and then iterating until no metabolites can be produced/consumed.
+   makeSomething is called before consumeSomething.
+
+ Usage: [newModel, removedRxns]=removeBadRxns(model,rxnRules,...
+       ignoreMets,isNames,refModel,ignoreIntBounds,printReport)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function [newModel, removedRxns]=removeBadRxns(model,rxnRules,ignoreMets,isNames,balanceElements,refModel,ignoreIntBounds,printReport)
+0002 % removeBadRxns
+0003 %   Iteratively removes reactions which enable production/consumption of some
+0004 %   metabolite without any uptake/excretion
+0005 %
+0006 %   model                   a model structure. For the intented function,
+0007 %                           the model shouldn't allow for any uptake/excretion.
+0008 %                           The easiest way to achieve this is to import the
+0009 %                           model using importModel('filename',false)
+0010 %   rxnRules                1: only remove reactions which are unbalanced
+0011 %                           2: also remove reactions which couldn't be checked for
+0012 %                           mass balancing
+0013 %                           3: all reactions can be removed
+0014 %                           (optional, default 1)
+0015 %   ignoreMets              either a cell array of metabolite IDs, a logical vector
+0016 %                           with the same number of elements as metabolites in the model,
+0017 %                           of a vector of indexes for metabolites to exclude from
+0018 %                           this analysis (optional, default [])
+0019 %   isNames                 true if the supplied mets represent metabolite names
+0020 %                           (as opposed to IDs). This is a way to delete
+0021 %                           metabolites in several compartments at once without
+0022 %                           knowing the exact IDs. This only works if ignoreMets
+0023 %                           is a cell array (optional, default false)
+0024 %   balanceElements         a cell array with the elements for which to
+0025 %                           balance the reactions. May contain any
+0026 %                           combination of the elements defined in parseFormulas
+0027 %                           (optional, default {'C';'P';'S';'N';'O'})
+0028 %   refModel                a reference model which can be used to ensure
+0029 %                           that the resulting model is still functional.
+0030 %                           The intended use is that the reference model is
+0031 %                           a copy of model, but with uptake/excretion allowed and
+0032 %                           some objectives (such as production of biomass)
+0033 %                           constrained to a non-zero flux. Before a
+0034 %                           reaction is removed from "model" the function first
+0035 %                           checks that the same deletion in "refModel"
+0036 %                           doesn't render the problem unfeasible (optional)
+0037 %   ignoreIntBounds         true if internal bounds (including reversibility)
+0038 %                           should be ignored. Exchange reactions are not affected.
+0039 %                           This can be used to find unbalanced solutions which are
+0040 %                           not possible using the default constraints (optional,
+0041 %                           default false)
+0042 %   printReport             true if a report should be printed (optional,
+0043 %                           default false)
+0044 %
+0045 %   newModel                   a model structure after the problematic
+0046 %                           reactions have been deleted
+0047 %   removedRxns             a cell array with the reactions that were
+0048 %                           removed
+0049 %
+0050 %   The purpose of this function is to remove reactions which enable
+0051 %   production/consumption of metabolites even when exchange reactions aren't used.
+0052 %   Many models, especially if they are automatically inferred from
+0053 %   databases, will have unbalanced reactions which allow for
+0054 %   net-production/consumption of metabolites without any consumption/excretion.
+0055 %   A common reason for this is when general compounds have different meaning
+0056 %   in different reactions (as DNA has in these two reactions).
+0057 %       dATP + dGTP + dCTP + dTTP <=> DNA + 4 PPi
+0058 %       0.25 dATP + 0.25 dGTP + 0.25 dCTP + 0.25 dTTP <=> DNA + PPi
+0059 %   Reactions that are problematic like this are always elementally
+0060 %   unbalanced, but it is not always that you would like to exclude all
+0061 %   unbalanced reactions from your model.
+0062 %   This function tries to remove as few problematic reactions as possible
+0063 %   so that the model cannot produce/consume anything from nothing. This is done by
+0064 %   repeatedly calling makeSomething/consumeSomething, checking if any of
+0065 %   the involved reactions are elementally unbalanced, remove one of them,
+0066 %   and then iterating until no metabolites can be produced/consumed.
+0067 %   makeSomething is called before consumeSomething.
+0068 %
+0069 % Usage: [newModel, removedRxns]=removeBadRxns(model,rxnRules,...
+0070 %       ignoreMets,isNames,refModel,ignoreIntBounds,printReport)
+0071 
+0072 if nargin<2
+0073     rxnRules=1;
+0074 end
+0075 if nargin<3
+0076     ignoreMets=[];
+0077 elseif ~islogical(ignoreMets) && ~isnumeric(ignoreMets)
+0078     ignoreMets=convertCharArray(ignoreMets);
+0079 end
+0080 if nargin<4
+0081     isNames=false;
+0082 end
+0083 if nargin<5
+0084     balanceElements={'C';'P';'S';'N';'O'};
+0085 else
+0086     balanceElements=convertCharArray(balanceElements);
+0087 end
+0088 if nargin<6
+0089     refModel=[];
+0090 else
+0091     if ~isempty(refModel)
+0092         EM='The feature to supply a reference model is currently not supported';
+0093         dispEM(EM,false);
+0094     end
+0095 end
+0096 if nargin<7
+0097     ignoreIntBounds=false;
+0098 end
+0099 if nargin<8
+0100     printReport=false;
+0101 end
+0102 
+0103 %Check if the model has open exchange reactions and print a warning in that
+0104 %case
+0105 if ~isfield(model,'unconstrained')
+0106     [~, I]=getExchangeRxns(model);
+0107     if any(I)
+0108         if any(model.lb(I)~=0) || any(model.ub(I)~=0)
+0109             EM='The model contains open exchange reactions. This is not the intended use of this function. Consider importing your model using importModel(filename,false)';
+0110             dispEM(EM,false);
+0111         end
+0112     end
+0113 end
+0114 
+0115 %Check that the model is feasible
+0116 sol=solveLP(model);
+0117 if isempty(sol.f)
+0118     EM='The model is not feasible. Consider removing lower bounds (such as ATP maintenance)';
+0119     dispEM(EM);
+0120 end
+0121 
+0122 %Check that the reference model is feasible
+0123 if any(refModel)
+0124     sol=solveLP(refModel);
+0125     if isempty(sol.f)
+0126         EM='The reference model is not feasible';
+0127         dispEM(EM);
+0128     end
+0129 end
+0130 
+0131 %Initialize some stuff
+0132 removedRxns={};
+0133 balanceStructure=getElementalBalance(model);
+0134 
+0135 %Check which elements to balance for
+0136 if ~isempty(setdiff(balanceElements,balanceStructure.elements.abbrevs))
+0137     EM='Could not recognize all elements to balance for';
+0138     dispEM(EM);
+0139 end
+0140 bal=ismember(balanceStructure.elements.abbrevs,balanceElements);
+0141 
+0142 %Main loop. First run for makeSomething, second for consumeSomething
+0143 warned=false(2,1); %This is to prevent the same warning being printed multiple times if rxnRules==3
+0144 for i=1:2
+0145     while 1
+0146         %Make some metabolite using as few reactions as possible
+0147         if i==1
+0148             [solution, metabolite]=makeSomething(model,ignoreMets,isNames,false,true,[],ignoreIntBounds);
+0149             if ~isempty(solution)
+0150                 if printReport
+0151                     fprintf(['Can make: ' model.metNames{metabolite(1)} '\n']);
+0152                 end
+0153             else
+0154                 %If no solution could be found, then finish
+0155                 break;
+0156             end
+0157         else
+0158             [solution, metabolite]=consumeSomething(model,ignoreMets,isNames,false,[],ignoreIntBounds);
+0159             if ~isempty(solution)
+0160                 if printReport
+0161                     fprintf(['Can consume: ' model.metNames{metabolite(1)} '\n']);
+0162                 end
+0163             else
+0164                 %If no solution could be found, then finish
+0165                 break;
+0166             end
+0167         end
+0168         
+0169         %Find all reactions that are unbalanced and still carry flux
+0170         I=find(abs(solution)>10^-8 & balanceStructure.balanceStatus>=0 & ~all(balanceStructure.leftComp(:,bal)==balanceStructure.rightComp(:,bal),2));
+0171         
+0172         %If there are unbalanced rxns then delete one of them and iterate
+0173         if any(I)
+0174             rxnToRemove=I(randperm(numel(I),1));
+0175         else
+0176             %If there are no unbalanced rxns in the solution
+0177             if rxnRules==1
+0178                 if i==1
+0179                     EM=['No unbalanced reactions were found in the solution, but the model can still make "' model.metNames{metabolite} '". Aborting search. Consider setting rxnRules to 2 or 3 for a more exhaustive search'];
+0180                     dispEM(EM,false);
+0181                 else
+0182                     EM=['No unbalanced reactions were found in the solution, but the model can still consume "' model.metNames{metabolite} '". Aborting search. Consider setting rxnRules to 2 or 3 for a more exhaustive search'];
+0183                     dispEM(EM,false);
+0184                 end
+0185                 break;
+0186             else
+0187                 %Find reactions which are not checked for mass balancing,
+0188                 %but that still carry flux
+0189                 I=find(abs(solution)>10^-8 & balanceStructure.balanceStatus<0);
+0190                 
+0191                 %If there are any such reactions, remove one of them and
+0192                 %iterate
+0193                 if any(I)
+0194                     rxnToRemove=I(randperm(numel(I),1));
+0195                 else
+0196                     if rxnRules==2
+0197                         %This happens when all reactions used are balanced
+0198                         %according to the metabolite formulas. This cannot
+0199                         %be, and indicates that one or more of the formulas
+0200                         %are wrong. Print a warning and delete any reaction
+0201                         %with flux
+0202                         if i==1
+0203                             EM=['No unbalanced or unparsable reactions were found in the solution, but the model can still make "' model.metNames{metabolite} '". Aborting search. Consider setting rxnRules to 3 for a more exhaustive search'];
+0204                             dispEM(EM,false);
+0205                         else
+0206                             EM=['No unbalanced or unparsable reactions were found in the solution, but the model can still consume "' model.metNames{metabolite} '". Aborting search. Consider setting rxnRules to 3 for a more exhaustive search'];
+0207                             dispEM(EM,false);
+0208                         end
+0209                         break;
+0210                     else
+0211                         if i==1
+0212                             if warned(1)==false
+0213                                 EM=['No unbalanced or unparsable reactions were found in the solution, but the model can still make "' model.metNames{metabolite} '". This indicates some error in the metabolite formulas. Removing random reactions in the solution'];
+0214                                 dispEM(EM,false);
+0215                                 warned(1)=true;
+0216                             end
+0217                         else
+0218                             if warned(2)==false
+0219                                 EM=['No unbalanced or unparsable reactions were found in the solution, but the model can still consume "' model.metNames{metabolite} '". This indicates some error in the metabolite formulas. Removing random reactions in the solution'];
+0220                                 dispEM(EM,false);
+0221                                 warned(2)=true;
+0222                             end
+0223                         end
+0224                         I=find(abs(solution)>10^-8);
+0225                         rxnToRemove=I(randperm(numel(I),1));
+0226                     end
+0227                 end
+0228             end
+0229         end
+0230         removedRxns=[removedRxns;model.rxns(rxnToRemove)];
+0231         if printReport
+0232             fprintf(['\tRemoved: '  model.rxns{rxnToRemove} '\n']);
+0233         end
+0234         model=removeReactions(model,rxnToRemove);
+0235         balanceStructure.balanceStatus(rxnToRemove)=[];
+0236         balanceStructure.leftComp(rxnToRemove,:)=[];
+0237         balanceStructure.rightComp(rxnToRemove,:)=[];
+0238     end
+0239 end
+0240 
+0241 newModel=model;
+0242 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/removeGenes.html b/doc/core/removeGenes.html new file mode 100644 index 000000000..387120255 --- /dev/null +++ b/doc/core/removeGenes.html @@ -0,0 +1,194 @@ + + + + Description of removeGenes + + + + + + + + + +
Home > core > removeGenes.m
+ + + +

removeGenes +

+ +

PURPOSE ^

+
removeGenes
+ +

SYNOPSIS ^

+
function reducedModel = removeGenes(model,genesToRemove,removeUnusedMets,removeBlockedRxns,standardizeRules)
+ +

DESCRIPTION ^

+
 removeGenes
+   Deletes a set of genes from a model
+
+   model                   a model structure
+   genesToRemove           either a cell array of gene IDs, a logical vector
+                           with the same number of elements as genes in the model,
+                           or a vector of indexes to remove
+   removeUnusedMets        remove metabolites that are no longer in use (optional, default
+                           false)
+   removeBlockedRxns       remove reactions that get blocked after deleting the genes
+                           (optional, default false)
+   standardizeRules        format gene rules to be compliant with standard format
+                           (optional, default true)
+
+   reducedModel            an updated model structure
+
+ Usage: reducedModel = removeGenes(model,genesToRemove,removeUnusedMets,removeBlockedRxns)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 function reducedModel = removeGenes(model,genesToRemove,removeUnusedMets,removeBlockedRxns,standardizeRules)
+0002 % removeGenes
+0003 %   Deletes a set of genes from a model
+0004 %
+0005 %   model                   a model structure
+0006 %   genesToRemove           either a cell array of gene IDs, a logical vector
+0007 %                           with the same number of elements as genes in the model,
+0008 %                           or a vector of indexes to remove
+0009 %   removeUnusedMets        remove metabolites that are no longer in use (optional, default
+0010 %                           false)
+0011 %   removeBlockedRxns       remove reactions that get blocked after deleting the genes
+0012 %                           (optional, default false)
+0013 %   standardizeRules        format gene rules to be compliant with standard format
+0014 %                           (optional, default true)
+0015 %
+0016 %   reducedModel            an updated model structure
+0017 %
+0018 % Usage: reducedModel = removeGenes(model,genesToRemove,removeUnusedMets,removeBlockedRxns)
+0019 
+0020 if nargin<3
+0021     removeUnusedMets = false;
+0022 end
+0023 if nargin<4
+0024     removeBlockedRxns = false;
+0025 end
+0026 if nargin<5
+0027     standardizeRules = true;
+0028 end
+0029 %Format grRules and rxnGeneMatrix:
+0030 if standardizeRules
+0031     [grRules,rxnGeneMat,toCheck] = standardizeGrRules(model,true);
+0032     model.grRules    = grRules;
+0033     model.rxnGeneMat = rxnGeneMat;
+0034 else
+0035     toCheck    = [];
+0036     rxnGeneMat = model.rxnGeneMat;
+0037 end
+0038 reducedModel = model;
+0039 %Only remove genes that are actually in the model
+0040 if ~(islogical(genesToRemove) || isnumeric(genesToRemove))
+0041     genesToRemove=convertCharArray(genesToRemove);
+0042     genesToRemove=genesToRemove(ismember(genesToRemove,model.genes));
+0043 end
+0044 if ~isempty(genesToRemove)
+0045     indexesToRemove = getIndexes(model,genesToRemove,'genes');
+0046     if ~isempty(indexesToRemove)
+0047         %Make 0 corresponding columns from rxnGeneMat:
+0048         reducedModel.rxnGeneMat(:,indexesToRemove) = 0;        
+0049         genes = model.genes(indexesToRemove);
+0050         %Check if conflicting grRules contain any of the genes to remove
+0051         if ~isempty(toCheck)
+0052             for i=1:numel(toCheck)
+0053                 index   = toCheck(i);
+0054                 gIdxs   = find(rxnGeneMat(index,:));
+0055                 g2check = model.genes(gIdxs);
+0056                 if any(ismember(g2check,genes))
+0057                     warning(['Conflicting grRule #' num2str(index) ' (' model.rxns{index} ') contains at least one of the genes to be removed, this grRule will be bypassed in order to avoid logical errors'])
+0058                 end
+0059             end
+0060         end
+0061         canCarryFlux = true(size(model.rxns));       
+0062         %Loop through genes and adapt rxns:
+0063         for i = 1:length(genes)
+0064             %Find all reactions for this gene and loop through them:
+0065             geneRxns = find(rxnGeneMat(:,indexesToRemove(i)));
+0066             if ~isempty(geneRxns)
+0067                 for j = 1:numel(geneRxns)
+0068                     index  = geneRxns(j);
+0069                     grRule = reducedModel.grRules{index};
+0070                     ruleGenes = reducedModel.genes(logical(rxnGeneMat(index,:)));
+0071                     if ~ismember(index,toCheck) && canCarryFlux(index) && ~isempty(grRule)
+0072                         %Check if rxn can carry flux without this gene:
+0073                         canCarryFlux(index) = canRxnCarryFlux(ruleGenes,grRule,genes{i});
+0074                         %Adapt gene rule & gene matrix:
+0075                         grRule = removeGeneFromRule(grRule,genes{i});
+0076                         reducedModel.grRules{index} = grRule;
+0077                     end
+0078                 end
+0079             end
+0080         end
+0081         %Delete or block the reactions that cannot carry flux:
+0082         if removeBlockedRxns
+0083             rxnsToRemove = reducedModel.rxns(~canCarryFlux);
+0084             reducedModel = removeReactions(reducedModel,rxnsToRemove,removeUnusedMets,true);
+0085         else
+0086             reducedModel = removeReactions(reducedModel,[],removeUnusedMets,true);
+0087             reducedModel.lb(~canCarryFlux) = 0;
+0088             reducedModel.ub(~canCarryFlux) = 0;
+0089         end
+0090     end
+0091 end
+0092 %Format grRules and rxnGeneMatrix after all modifications
+0093 if standardizeRules
+0094     [grRules,rxnGeneMat] = standardizeGrRules(reducedModel,true);
+0095     reducedModel.grRules = grRules;
+0096     reducedModel.rxnGeneMat = rxnGeneMat;
+0097 end
+0098 end
+0099 
+0100 function canIt = canRxnCarryFlux(ruleGenes,geneRule,geneToRemove)
+0101 %This function converts a gene rule to a logical statement, and then
+0102 %asseses if the rule is true (i.e. rxn can still carry flux) or not (cannot
+0103 %carry flux).
+0104 geneRule = [' ', geneRule, ' '];
+0105 for i = 1:length(ruleGenes)
+0106     if strcmp(ruleGenes{i},geneToRemove)
+0107         geneRule = strrep(geneRule,[' ' ruleGenes{i} ' '],' false ');
+0108         geneRule = strrep(geneRule,['(' ruleGenes{i} ' '],'(false ');
+0109         geneRule = strrep(geneRule,[' ' ruleGenes{i} ')'],' false)');
+0110     else
+0111         geneRule = strrep(geneRule,[' ' ruleGenes{i} ' '],' true ');
+0112         geneRule = strrep(geneRule,['(' ruleGenes{i} ' '],'(true ');
+0113         geneRule = strrep(geneRule,[' ' ruleGenes{i} ')'],' true)');
+0114     end
+0115 end
+0116 geneRule = strtrim(geneRule);
+0117 geneRule = strrep(geneRule,'and','&&');
+0118 geneRule = strrep(geneRule,'or','||');
+0119 canIt    = eval(geneRule);
+0120 end
+0121 
+0122 function geneRule = removeGeneFromRule(geneRule,geneToRemove)
+0123 %This function receives a standard gene rule and it returns it without the
+0124 %chosen gene.
+0125 geneSets = strsplit(geneRule,' or ');
+0126 hasGene  = ~cellfun(@isempty,strfind(geneSets,geneToRemove));
+0127 geneSets = geneSets(~hasGene);
+0128 geneRule = strjoin(geneSets,' or ');
+0129 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/removeMets.html b/doc/core/removeMets.html new file mode 100644 index 000000000..4a3d2d269 --- /dev/null +++ b/doc/core/removeMets.html @@ -0,0 +1,198 @@ + + + + Description of removeMets + + + + + + + + + +
Home > core > removeMets.m
+ + + +

removeMets +

+ +

PURPOSE ^

+
removeMets
+ +

SYNOPSIS ^

+
function reducedModel=removeMets(model,metsToRemove,isNames,removeUnusedRxns,removeUnusedGenes,removeUnusedComps)
+ +

DESCRIPTION ^

+
 removeMets
+   Deletes a set of metabolites from a model
+
+   model             a model structure
+   metsToRemove      either a cell array of metabolite IDs, a logical vector
+                     with the same number of elements as metabolites in the model,
+                     of a vector of indexes to remove
+   isNames           true if the supplied mets represent metabolite names
+                     (as opposed to IDs). This is a way to delete
+                     metabolites in several compartments at once without
+                     knowing the exact IDs. This only works if metsToRemove
+                     is a cell array (optional, default false)
+   removeUnusedRxns  remove reactions that are no longer in use (optional,
+                     default false)
+   removeUnusedGenes remove genes that are no longer in use (optional,
+                     default false)
+   removeUnusedComps remove compartments that are no longer in use (optional,
+                     default false)
+
+   reducedModel      an updated model structure
+
+ Usage: reducedModel=removeMets(model,metsToRemove,isNames,...
+           removeUnusedRxns,removeUnusedGenes,removeUnusedComps)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function reducedModel=removeMets(model,metsToRemove,isNames,removeUnusedRxns,removeUnusedGenes,removeUnusedComps)
+0002 % removeMets
+0003 %   Deletes a set of metabolites from a model
+0004 %
+0005 %   model             a model structure
+0006 %   metsToRemove      either a cell array of metabolite IDs, a logical vector
+0007 %                     with the same number of elements as metabolites in the model,
+0008 %                     of a vector of indexes to remove
+0009 %   isNames           true if the supplied mets represent metabolite names
+0010 %                     (as opposed to IDs). This is a way to delete
+0011 %                     metabolites in several compartments at once without
+0012 %                     knowing the exact IDs. This only works if metsToRemove
+0013 %                     is a cell array (optional, default false)
+0014 %   removeUnusedRxns  remove reactions that are no longer in use (optional,
+0015 %                     default false)
+0016 %   removeUnusedGenes remove genes that are no longer in use (optional,
+0017 %                     default false)
+0018 %   removeUnusedComps remove compartments that are no longer in use (optional,
+0019 %                     default false)
+0020 %
+0021 %   reducedModel      an updated model structure
+0022 %
+0023 % Usage: reducedModel=removeMets(model,metsToRemove,isNames,...
+0024 %           removeUnusedRxns,removeUnusedGenes,removeUnusedComps)
+0025 if ~islogical(metsToRemove) && ~isnumeric(metsToRemove)
+0026     metsToRemove=convertCharArray(metsToRemove);
+0027 end
+0028 
+0029 if nargin<3
+0030     isNames=false;
+0031 end
+0032 
+0033 if nargin<4
+0034     removeUnusedRxns=false;
+0035 end
+0036 
+0037 if nargin<5
+0038     removeUnusedGenes=false;
+0039 end
+0040 
+0041 if nargin<6
+0042     removeUnusedComps=false;
+0043 end
+0044 
+0045 %Check that metsToRemove is a cell array
+0046 if isNames==true && ~iscell(metsToRemove)
+0047     error('Must supply a cell array of strings if isNames=true');
+0048 end
+0049 
+0050 reducedModel=model;
+0051 
+0052 if isNames==false
+0053     indexesToDelete=getIndexes(model,metsToRemove,'mets');
+0054 else
+0055     indexesToDelete=[];
+0056     for i=1:numel(metsToRemove)
+0057         indexesToDelete=[indexesToDelete;find(strcmp(metsToRemove(i),model.metNames))];
+0058     end
+0059 end
+0060 
+0061 %Remove metabolites
+0062 if ~isempty(indexesToDelete)
+0063     reducedModel.mets(indexesToDelete)=[];
+0064     reducedModel.S(indexesToDelete,:)=[];
+0065     if isfield(reducedModel,'b')
+0066         reducedModel.b(indexesToDelete,:)=[];
+0067     end
+0068     if isfield(reducedModel,'metNames')
+0069         reducedModel.metNames(indexesToDelete)=[];
+0070     end
+0071     if isfield(reducedModel,'metComps')
+0072         reducedModel.metComps(indexesToDelete)=[];
+0073     end
+0074     if isfield(reducedModel,'inchis')
+0075         reducedModel.inchis(indexesToDelete)=[];
+0076     end
+0077     if isfield(reducedModel,'metSmiles')
+0078         reducedModel.metSmiles(indexesToDelete)=[];
+0079     end
+0080     if isfield(reducedModel,'metFormulas')
+0081         reducedModel.metFormulas(indexesToDelete)=[];
+0082     end
+0083     if isfield(reducedModel,'metMiriams')
+0084         reducedModel.metMiriams(indexesToDelete)=[];
+0085     end
+0086     if isfield(reducedModel,'unconstrained')
+0087         reducedModel.unconstrained(indexesToDelete)=[];
+0088     end
+0089     if isfield(reducedModel,'metFrom')
+0090         reducedModel.metFrom(indexesToDelete)=[];
+0091     end
+0092     if isfield(reducedModel,'metCharges')
+0093         reducedModel.metCharges(indexesToDelete)=[];
+0094     end
+0095     if isfield(reducedModel,'metDeltaG')
+0096         reducedModel.metDeltaG(indexesToDelete)=[];
+0097     end
+0098     if isfield(reducedModel,'metNotes')
+0099         reducedModel.metNotes(indexesToDelete)=[];
+0100     end    
+0101 end
+0102 
+0103 %Remove unused reactions
+0104 if removeUnusedRxns==true
+0105     %Get unused reactions
+0106     [~, a]=find(reducedModel.S);
+0107     rxnsToRemove=1:numel(reducedModel.rxns);
+0108     rxnsToRemove(a)=[];
+0109     reducedModel=removeReactions(reducedModel,rxnsToRemove,false,removeUnusedGenes);
+0110 end
+0111 
+0112 %Remove unused compartments
+0113 if removeUnusedComps==true
+0114     oldComps=reducedModel.comps;
+0115     I=ismember(1:numel(oldComps),reducedModel.metComps);
+0116     if ~all(I)
+0117         reducedModel.comps(~I)=[];
+0118         reducedModel.compNames(~I)=[];
+0119         if isfield(reducedModel,'compOutside')
+0120             reducedModel.compOutside(~I)=[];
+0121         end
+0122         if isfield(reducedModel,'compMiriams')
+0123             reducedModel.compMiriams(~I)=[];
+0124         end
+0125         [~, J]=ismember(oldComps(reducedModel.metComps),reducedModel.comps);
+0126         reducedModel.metComps=J;
+0127     end
+0128 end
+0129 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/removeReactions.html b/doc/core/removeReactions.html new file mode 100644 index 000000000..0f658fe0e --- /dev/null +++ b/doc/core/removeReactions.html @@ -0,0 +1,218 @@ + + + + Description of removeReactions + + + + + + + + + +
Home > core > removeReactions.m
+ + + +

removeReactions +

+ +

PURPOSE ^

+
removeReactions
+ +

SYNOPSIS ^

+
function reducedModel=removeReactions(model,rxnsToRemove,removeUnusedMets,removeUnusedGenes,removeUnusedComps)
+ +

DESCRIPTION ^

+
 removeReactions
+   Deletes a set of reactions from a model
+
+ Input:
+   model             a model structure
+   rxnsToRemove      either a cell array of reaction IDs, a logical vector
+                     with the same number of elements as reactions in the
+                     model, or a vector of indexes to remove
+   removeUnusedMets  remove metabolites that are no longer in use
+                     (optional, default false)
+   removeUnusedGenes remove genes that are no longer in use (optional,
+                     default false)
+   removeUnusedComps remove compartments that are no longer in use
+                     (optional, default false)
+
+ Output:
+   reducedModel      an updated model structure
+
+ Usage: reducedModel = removeReactions(model, rxnsToRemove, removeUnusedMets,...
+                           removeUnusedGenes, removeUnusedComps)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function reducedModel=removeReactions(model,rxnsToRemove,removeUnusedMets,removeUnusedGenes,removeUnusedComps)
+0002 % removeReactions
+0003 %   Deletes a set of reactions from a model
+0004 %
+0005 % Input:
+0006 %   model             a model structure
+0007 %   rxnsToRemove      either a cell array of reaction IDs, a logical vector
+0008 %                     with the same number of elements as reactions in the
+0009 %                     model, or a vector of indexes to remove
+0010 %   removeUnusedMets  remove metabolites that are no longer in use
+0011 %                     (optional, default false)
+0012 %   removeUnusedGenes remove genes that are no longer in use (optional,
+0013 %                     default false)
+0014 %   removeUnusedComps remove compartments that are no longer in use
+0015 %                     (optional, default false)
+0016 %
+0017 % Output:
+0018 %   reducedModel      an updated model structure
+0019 %
+0020 % Usage: reducedModel = removeReactions(model, rxnsToRemove, removeUnusedMets,...
+0021 %                           removeUnusedGenes, removeUnusedComps)
+0022 
+0023 if nargin<3
+0024     removeUnusedMets=false;
+0025 end
+0026 if nargin<4
+0027     removeUnusedGenes=false;
+0028 end
+0029 if nargin<5
+0030     removeUnusedComps=false;
+0031 end
+0032 if ~islogical(rxnsToRemove) && ~isnumeric(rxnsToRemove)
+0033     rxnsToRemove=convertCharArray(rxnsToRemove);
+0034 end
+0035 
+0036 reducedModel=model;
+0037 
+0038 if ~isempty(rxnsToRemove) || removeUnusedMets || removeUnusedGenes
+0039     indexesToDelete=getIndexes(model,rxnsToRemove,'rxns');
+0040     
+0041     %Remove reactions
+0042     if ~isempty(indexesToDelete)
+0043         reducedModel.rxns(indexesToDelete)=[];
+0044         if isfield(reducedModel,'lb')
+0045             reducedModel.lb(indexesToDelete)=[];
+0046         end
+0047         if isfield(reducedModel,'ub')
+0048             reducedModel.ub(indexesToDelete)=[];
+0049         end
+0050         if isfield(reducedModel,'rev')
+0051             reducedModel.rev(indexesToDelete)=[];
+0052         end
+0053         if isfield(reducedModel,'c')
+0054             reducedModel.c(indexesToDelete)=[];
+0055         end
+0056         if isfield(reducedModel,'S')
+0057             reducedModel.S(:,indexesToDelete)=[];
+0058         end
+0059         if isfield(reducedModel,'rxnNames')
+0060             reducedModel.rxnNames(indexesToDelete)=[];
+0061         end
+0062         if isfield(reducedModel,'rxnGeneMat')
+0063             reducedModel.rxnGeneMat(indexesToDelete,:)=[];
+0064         end
+0065         if isfield(reducedModel,'grRules')
+0066             reducedModel.grRules(indexesToDelete,:)=[];
+0067         end
+0068         if isfield(reducedModel,'subSystems')
+0069             reducedModel.subSystems(indexesToDelete,:)=[];
+0070         end
+0071         if isfield(reducedModel,'eccodes')
+0072             reducedModel.eccodes(indexesToDelete,:)=[];
+0073         end
+0074         if isfield(reducedModel,'equations')
+0075             reducedModel.equations(indexesToDelete,:)=[];
+0076         end
+0077         if isfield(reducedModel,'rxnMiriams')
+0078             reducedModel.rxnMiriams(indexesToDelete,:)=[];
+0079         end
+0080         if isfield(reducedModel,'rxnComps')
+0081             reducedModel.rxnComps(indexesToDelete,:)=[];
+0082         end
+0083         if isfield(reducedModel,'rxnFrom')
+0084             reducedModel.rxnFrom(indexesToDelete,:)=[];
+0085         end
+0086         if isfield(reducedModel,'rxnScores')
+0087             reducedModel.rxnScores(indexesToDelete,:)=[];
+0088         end
+0089         if isfield(reducedModel,'rxnNotes')
+0090             reducedModel.rxnNotes(indexesToDelete,:)=[];
+0091         end
+0092         if isfield(reducedModel,'rxnReferences')
+0093             reducedModel.rxnReferences(indexesToDelete,:)=[];
+0094         end
+0095         if isfield(reducedModel,'rxnConfidenceScores')
+0096             reducedModel.rxnConfidenceScores(indexesToDelete,:)=[];
+0097         end
+0098         if isfield(reducedModel,'rxnDeltaG')
+0099             reducedModel.rxnDeltaG(indexesToDelete,:)=[];
+0100         end
+0101         if isfield(reducedModel,'pwys')
+0102             reducedModel.pwys(indexesToDelete,:)=[];
+0103         end
+0104         if isfield(reducedModel,'spontaneous')
+0105             reducedModel.spontaneous(indexesToDelete)=[];
+0106         end
+0107     end
+0108     
+0109     %Remove unused metabolites
+0110     if removeUnusedMets==true
+0111         if isfield(reducedModel,'S')
+0112             [usedMets, ~]=find(reducedModel.S);
+0113             unUsedMets=true(numel(reducedModel.mets),1);
+0114             unUsedMets(usedMets)=false;
+0115             reducedModel=removeMets(reducedModel,unUsedMets,false,false,false,removeUnusedComps);
+0116         end
+0117     end
+0118     
+0119     %Remove unused genes
+0120     if removeUnusedGenes==true && isfield(reducedModel,'rxnGeneMat')
+0121         %Find all genes that are not used
+0122         [~, b]=find(reducedModel.rxnGeneMat);
+0123         toKeep=false(numel(reducedModel.genes),1);
+0124         toKeep(b)=true;
+0125         
+0126         reducedModel.genes=reducedModel.genes(toKeep);
+0127         reducedModel.rxnGeneMat=reducedModel.rxnGeneMat(:,toKeep);
+0128         
+0129         if isfield(reducedModel,'geneShortNames')
+0130             reducedModel.geneShortNames=reducedModel.geneShortNames(toKeep);
+0131         end
+0132 
+0133         if isfield(reducedModel,'proteins')
+0134             reducedModel.proteins=reducedModel.proteins(toKeep);
+0135         end
+0136         
+0137         if isfield(reducedModel,'geneMiriams')
+0138             reducedModel.geneMiriams=reducedModel.geneMiriams(toKeep);
+0139         end
+0140         
+0141         if isfield(reducedModel,'geneFrom')
+0142             reducedModel.geneFrom=reducedModel.geneFrom(toKeep);
+0143         end
+0144         
+0145         if isfield(reducedModel,'geneComps')
+0146             reducedModel.geneComps=reducedModel.geneComps(toKeep);
+0147         end
+0148     end
+0149 else
+0150     reducedModel=model;
+0151 end
+0152 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/replaceMets.html b/doc/core/replaceMets.html new file mode 100644 index 000000000..6f4319513 --- /dev/null +++ b/doc/core/replaceMets.html @@ -0,0 +1,226 @@ + + + + Description of replaceMets + + + + + + + + + +
Home > core > replaceMets.m
+ + + +

replaceMets +

+ +

PURPOSE ^

+
replaceMets
+ +

SYNOPSIS ^

+
function [model, removedRxns, idxDuplRxns]=replaceMets(model,metabolite,replacement,verbose,identifiers)
+ +

DESCRIPTION ^

+
 replaceMets
+   Replaces metabolite names and annotation with replacement metabolite
+   that is already in the model. If this results in duplicate metabolites,
+   the replacement metabolite will be kept, while the S matrix is updated
+   to use the replacement metabolite instead. At the end, contractModel is
+   run to remove any duplicate reactions that might have occured.
+
+ Input:
+   model           a model structure
+   metabolite      string with name of metabolite to be replace
+   replacement     string with name of replacement metabolite
+   verbose         logical whether to print the ids of reactions that
+                   involve the replaced metabolite (optional, default
+                   false)
+   identifiers     true if 'metabolite' and 'replacement' refer to
+                   metabolite identifiers instead of metabolite names
+                   (optional, default false)
+ 
+ Output:
+   model           model structure with selected metabolites replaced
+   removedRxns     identifiers of duplicate reactions that were removed
+   idxDuplRxns     index of removedRxns in original model
+
+ Note: This function is useful when the model contains both 'oxygen' and
+ 'o2' as metabolite names. If 'oxygen' and 'o2' are identifiers instead,
+ then the 'identifiers' flag should be set to true.
+
+ Usage: [model, removedRxns, idxDuplRxns] = replaceMets(model, metabolite, replacement, verbose)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function [model, removedRxns, idxDuplRxns]=replaceMets(model,metabolite,replacement,verbose,identifiers)
+0002 % replaceMets
+0003 %   Replaces metabolite names and annotation with replacement metabolite
+0004 %   that is already in the model. If this results in duplicate metabolites,
+0005 %   the replacement metabolite will be kept, while the S matrix is updated
+0006 %   to use the replacement metabolite instead. At the end, contractModel is
+0007 %   run to remove any duplicate reactions that might have occured.
+0008 %
+0009 % Input:
+0010 %   model           a model structure
+0011 %   metabolite      string with name of metabolite to be replace
+0012 %   replacement     string with name of replacement metabolite
+0013 %   verbose         logical whether to print the ids of reactions that
+0014 %                   involve the replaced metabolite (optional, default
+0015 %                   false)
+0016 %   identifiers     true if 'metabolite' and 'replacement' refer to
+0017 %                   metabolite identifiers instead of metabolite names
+0018 %                   (optional, default false)
+0019 %
+0020 % Output:
+0021 %   model           model structure with selected metabolites replaced
+0022 %   removedRxns     identifiers of duplicate reactions that were removed
+0023 %   idxDuplRxns     index of removedRxns in original model
+0024 %
+0025 % Note: This function is useful when the model contains both 'oxygen' and
+0026 % 'o2' as metabolite names. If 'oxygen' and 'o2' are identifiers instead,
+0027 % then the 'identifiers' flag should be set to true.
+0028 %
+0029 % Usage: [model, removedRxns, idxDuplRxns] = replaceMets(model, metabolite, replacement, verbose)
+0030 
+0031 metabolite=char(metabolite);
+0032 replacement=char(replacement);
+0033 
+0034 if nargin<4 || isempty(verbose)
+0035     verbose=false;
+0036 end
+0037 if nargin<5
+0038     identifiers = false;
+0039 end
+0040 
+0041 % Find occurence of replacement metabolites. Annotation will be taken from
+0042 % first metabolite found.
+0043 if identifiers
+0044     repIdx = find(strcmp(replacement,model.mets));
+0045 else
+0046     repIdx = find(strcmp(replacement,model.metNames));
+0047 end
+0048 if isempty(repIdx)
+0049     error('The replacement metabolite cannot be found in the model.');
+0050 end
+0051 
+0052 % Change name and information from metabolite to replacement metabolite
+0053 if identifiers
+0054     metIdx = find(strcmp(metabolite,model.mets));
+0055 else
+0056     metIdx = find(strcmp(metabolite,model.metNames));
+0057 end
+0058 if isempty(metIdx)
+0059     error('The to-be-replaced metabolite cannot be found in the model.');
+0060 end
+0061 
+0062 rxnsWithMet = find(model.S(metIdx,:));
+0063 if verbose==true
+0064     fprintf('\n\nThe following reactions contain the to-be-replaced metabolite as reactant:\n')
+0065     fprintf(strjoin(model.rxns(rxnsWithMet),'\n'))
+0066     fprintf('\n')
+0067 end
+0068 
+0069 model.metNames(metIdx) = model.metNames(repIdx(1));
+0070 if isfield(model,'metFormulas')
+0071     model.metFormulas(metIdx) = model.metFormulas(repIdx(1));
+0072 end
+0073 if isfield(model,'metMiriams')
+0074     model.metMiriams(metIdx) = model.metMiriams(repIdx(1));
+0075 end
+0076 if isfield(model,'metCharges')
+0077     model.metCharges(metIdx) = model.metCharges(repIdx(1));
+0078 end
+0079 if isfield(model,'metDeltaG')
+0080     model.metDeltaG(metIdx) = model.metDeltaG(repIdx(1));
+0081 end
+0082 if isfield(model,'inchis')
+0083     model.inchis(metIdx) = model.inchis(repIdx(1));
+0084 end
+0085 if isfield(model,'metSmiles')
+0086     model.metSmiles(metIdx) = model.metSmiles(repIdx(1));
+0087 end
+0088 
+0089 idxDelete=[];
+0090 if identifiers
+0091     originalStoch = model.S(metIdx,rxnsWithMet);
+0092     model.S(repIdx,rxnsWithMet) = originalStoch;
+0093     model.S(metIdx,rxnsWithMet) = 0;
+0094     idxDelete = metIdx;
+0095 else
+0096     % Run through replacement metabolites and their compartments. If any of the
+0097     % to-be-replaced metabolites is already present (checked by
+0098     % metaboliteName[compartment], then the replacement metabolite is kept and
+0099     % the to-be-replace metabolite ID deleted.
+0100     
+0101     % Build list of metaboliteName[compartment]
+0102     metCompsN =cellstr(num2str(model.metComps));
+0103     map = containers.Map(cellstr(num2str(transpose(1:length(model.comps)))),model.comps);
+0104     metCompsN = map.values(metCompsN);
+0105     metCompsN = strcat(lower(model.metNames),'[',metCompsN,']');
+0106     
+0107     for i = 1:length(repIdx)
+0108         metCompsNidx=find(strcmp(metCompsN(repIdx(i)), metCompsN));
+0109         if length(metCompsNidx)>1
+0110             for j = 2:length(metCompsNidx)
+0111                 model.S(metCompsNidx(1),:) = model.S(metCompsNidx(1),:) + model.S(metCompsNidx(j),:);
+0112                 idxDelete=[idxDelete; metCompsNidx(j)]; % Make list of metabolite IDs to delete
+0113             end
+0114         end
+0115     end
+0116 end
+0117 
+0118 if ~isempty(idxDelete)
+0119     model.S(idxDelete,:) =[];
+0120     model.mets(idxDelete) = [];
+0121     model.metNames(idxDelete) = [];
+0122     model.metComps(idxDelete) = [];
+0123     model.b(idxDelete) = [];
+0124     if isfield(model,'metFormulas')
+0125         model.metFormulas(idxDelete) = [];
+0126     end
+0127     if isfield(model,'unconstrained')
+0128         model.unconstrained(idxDelete) = [];
+0129     end
+0130     if isfield(model,'metMiriams')
+0131         model.metMiriams(idxDelete) = [];
+0132     end
+0133     if isfield(model,'metCharges')
+0134         model.metCharges(idxDelete) = [];
+0135     end
+0136     if isfield(model,'metDeltaG')
+0137         model.metDeltaG(idxDelete) = [];
+0138     end
+0139     if isfield(model,'inchis')
+0140         model.inchis(idxDelete) = [];
+0141     end
+0142     if isfield(model,'metSmiles')
+0143         model.metSmiles(idxDelete) = [];
+0144     end
+0145     if isfield(model,'metFrom')
+0146         model.metFrom(idxDelete) = [];
+0147     end
+0148 end
+0149 
+0150 % This could now have created duplicate reactions. Contract model.
+0151 model=contractModel(model,[],repIdx);
+0152 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/reporterMetabolites.html b/doc/core/reporterMetabolites.html new file mode 100644 index 000000000..d3c5d2309 --- /dev/null +++ b/doc/core/reporterMetabolites.html @@ -0,0 +1,274 @@ + + + + Description of reporterMetabolites + + + + + + + + + +
Home > core > reporterMetabolites.m
+ + + +

reporterMetabolites +

+ +

PURPOSE ^

+
reporterMetabolites
+ +

SYNOPSIS ^

+
function repMets=reporterMetabolites(model,genes,genePValues,printResults,outputFile,geneFoldChanges)
+ +

DESCRIPTION ^

+
 reporterMetabolites
+   The Reporter Metabolites algorithm for identifying metabolites around
+   which transcriptional changes occur
+
+   model           a model structure
+   genes           a cell array of gene names (should match with
+                   model.genes)
+   genePValues     P-values for differential expression of the genes
+   printResults    true if the top 20 Reporter Metabolites should be
+                   printed to the screen (optional, default false)
+   outputFile      the results are printed to this file (optional)
+   geneFoldChanges log-fold changes for the genes. If supplied, then
+                   Reporter Metabolites are calculated for only up/down-
+                   regulated genes in addition to the full test (optional)
+
+   repMets         an array of structures with the following fields.
+       test            a string the describes the genes that were used to
+                       calculate the Reporter Metabolites ('all', 'only up',
+                       or 'only down'). The two latter structures are
+                       only calculated if geneFoldChanges are supplied.
+       mets            a cell array of metabolite IDs for the metabolites for
+                       which a score could be calculated
+       metZScores      Z-scores for differential expression around each
+                       metabolite in "mets"
+       metPValues      P-values for differential expression around each
+                       metabolite in "mets"
+       metNGenes       number of neighbouring genes for each metabolite in
+                       "mets"
+       meanZ           average Z-scores for the genes around each metabolite
+                       in "mets"
+       stdZ            standard deviations of the Z-scores around each
+                       metabolite in "mets"
+
+   NOTE: For details about the algorithm, see Patil KR, Nielsen J,
+   Uncovering transcriptional regulation of metabolism by using metabolic
+   network topology. Proc. Natl Acad. Sci. USA 2005;102:2685-2689.
+
+ Usage: repMets=reporterMetabolites(model,genes,genePValues,printResults,...
+           outputFile,geneFoldChanges)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function repMets=reporterMetabolites(model,genes,genePValues,printResults,outputFile,geneFoldChanges)
+0002 % reporterMetabolites
+0003 %   The Reporter Metabolites algorithm for identifying metabolites around
+0004 %   which transcriptional changes occur
+0005 %
+0006 %   model           a model structure
+0007 %   genes           a cell array of gene names (should match with
+0008 %                   model.genes)
+0009 %   genePValues     P-values for differential expression of the genes
+0010 %   printResults    true if the top 20 Reporter Metabolites should be
+0011 %                   printed to the screen (optional, default false)
+0012 %   outputFile      the results are printed to this file (optional)
+0013 %   geneFoldChanges log-fold changes for the genes. If supplied, then
+0014 %                   Reporter Metabolites are calculated for only up/down-
+0015 %                   regulated genes in addition to the full test (optional)
+0016 %
+0017 %   repMets         an array of structures with the following fields.
+0018 %       test            a string the describes the genes that were used to
+0019 %                       calculate the Reporter Metabolites ('all', 'only up',
+0020 %                       or 'only down'). The two latter structures are
+0021 %                       only calculated if geneFoldChanges are supplied.
+0022 %       mets            a cell array of metabolite IDs for the metabolites for
+0023 %                       which a score could be calculated
+0024 %       metZScores      Z-scores for differential expression around each
+0025 %                       metabolite in "mets"
+0026 %       metPValues      P-values for differential expression around each
+0027 %                       metabolite in "mets"
+0028 %       metNGenes       number of neighbouring genes for each metabolite in
+0029 %                       "mets"
+0030 %       meanZ           average Z-scores for the genes around each metabolite
+0031 %                       in "mets"
+0032 %       stdZ            standard deviations of the Z-scores around each
+0033 %                       metabolite in "mets"
+0034 %
+0035 %   NOTE: For details about the algorithm, see Patil KR, Nielsen J,
+0036 %   Uncovering transcriptional regulation of metabolism by using metabolic
+0037 %   network topology. Proc. Natl Acad. Sci. USA 2005;102:2685-2689.
+0038 %
+0039 % Usage: repMets=reporterMetabolites(model,genes,genePValues,printResults,...
+0040 %           outputFile,geneFoldChanges)
+0041 
+0042 genes=convertCharArray(genes);
+0043 if nargin<4
+0044     printResults=false;
+0045 end
+0046 if nargin<5
+0047     outputFile=[];
+0048 end
+0049 if nargin<6
+0050     geneFoldChanges=[];
+0051 end
+0052 
+0053 %Check some stuff
+0054 if numel(genes)~=numel(genePValues)
+0055     EM='The number of genes and the number of Z-scores must be the same';
+0056     dispEM(EM);
+0057 end
+0058 if ~isfield(model,'rxnGeneMat')
+0059     EM='The model structure must have a rxnGeneMat field';
+0060     dispEM(EM);
+0061 end
+0062 
+0063 %Remove the genes which are not in the model
+0064 genePValues(~ismember(genes,model.genes))=[];
+0065 if any(geneFoldChanges)
+0066     geneFoldChanges(~ismember(genes,model.genes))=[];
+0067 end
+0068 genes(~ismember(genes,model.genes))=[];
+0069 
+0070 %Remove the genes that has NA P-value
+0071 genes(isnan(genePValues))=[];
+0072 if any(geneFoldChanges)
+0073     geneFoldChanges(isnan(genePValues))=[];
+0074 end
+0075 genePValues(isnan(genePValues))=[];
+0076 
+0077 %Convert p-values to Z-scores
+0078 geneZScores=norminv(genePValues)*-1;
+0079 
+0080 %This is to prevent errors if the p-values are exactly 0 or 1
+0081 geneZScores(geneZScores==-inf)=-15;
+0082 geneZScores(geneZScores==inf)=15;
+0083 
+0084 %For each metabolite, calculate the aggregate Z-score and keep track of the
+0085 %number of neighbouring genes
+0086 metZScores=nan(numel(model.mets),1);
+0087 metNGenes=nan(numel(model.mets),1);
+0088 meanZ=nan(numel(model.mets),1);
+0089 stdZ=nan(numel(model.mets),1);
+0090 for i=1:numel(model.mets)
+0091     %Get the involved rxns
+0092     I=model.S(i,:);
+0093     
+0094     %Get the involved genes
+0095     [~, J]=find(model.rxnGeneMat(I~=0,:));
+0096     
+0097     %Find the genes in the gene list
+0098     K=find(ismember(genes,model.genes(J)));
+0099     
+0100     %Calculate the aggregated Z-score for the metabolite
+0101     if any(K)
+0102         metZScores(i)=sum(geneZScores(K))/sqrt(numel(K));
+0103         meanZ(i)=mean(geneZScores(K));
+0104         stdZ(i)=std(geneZScores(K));
+0105         metNGenes(i)=numel(K);
+0106     end
+0107 end
+0108 
+0109 %Remove the metabolites which have no Z-scores
+0110 mets=model.mets(~isnan(metZScores));
+0111 metNames=model.metNames(~isnan(metZScores));
+0112 metZScores(isnan(metZScores))=[];
+0113 metNGenes(isnan(metNGenes))=[];
+0114 meanZ(isnan(meanZ))=[];
+0115 stdZ(isnan(stdZ))=[];
+0116 
+0117 %Then correct for background by calculating the mean Z-score for random
+0118 %sets of the same size as the ones that were found for the metabolites
+0119 sizes=unique(metNGenes);
+0120 nGenes=numel(genes);
+0121 
+0122 for i=1:numel(sizes)
+0123     %Sample 100000 sets for each size. Sample with replacement, which may
+0124     %or may not be the best choice.
+0125     I=ceil(rand(100000,sizes(i))*nGenes);
+0126     J=geneZScores(I);
+0127     K=sum(J,2)/sqrt(sizes(i));
+0128     
+0129     %Correct all elements of this size
+0130     mK=mean(K);
+0131     stdK=std(K);
+0132     metZScores(metNGenes==sizes(i))=(metZScores(metNGenes==sizes(i))-mK)/stdK;
+0133 end
+0134 
+0135 %Calculate the P-values
+0136 metPValues=1-normcdf(metZScores);
+0137 
+0138 %Sort the results
+0139 [metZScores, I]=sort(metZScores,'descend');
+0140 mets=mets(I);
+0141 metNames=metNames(I);
+0142 metPValues=metPValues(I);
+0143 metNGenes=metNGenes(I);
+0144 meanZ=meanZ(I);
+0145 stdZ=stdZ(I);
+0146 
+0147 %Prepare the output
+0148 repMets.mets=mets;
+0149 repMets.metNames=metNames;
+0150 repMets.metZScores=metZScores;
+0151 repMets.metPValues=metPValues;
+0152 repMets.metNGenes=metNGenes;
+0153 repMets.meanZ=meanZ;
+0154 repMets.stdZ=stdZ;
+0155 
+0156 %Call this function recursively if geneFoldChanges has been specified
+0157 repMets(1).test='all';
+0158 if any(geneFoldChanges)
+0159     repMets=[repMets;reporterMetabolites(model,genes(geneFoldChanges>=0),genePValues(geneFoldChanges>=0))];
+0160     repMets=[repMets;reporterMetabolites(model,genes(geneFoldChanges<0),genePValues(geneFoldChanges<0))];
+0161     repMets(2).test='only up';
+0162     repMets(3).test='only down';
+0163 end
+0164 
+0165 %This is for printing results to the screen. For printing a full list of
+0166 %all scores, specify a output file
+0167 if printResults==true
+0168     for i=1:numel(repMets)
+0169         fprintf(['TOP 20 REPORTER METABOLITES\nTEST TYPE: ' repMets(i).test '\nID\tNAME\tP-VALUE\n']);
+0170         for j=1:min(20,numel(repMets(i).mets))
+0171             fprintf([repMets(i).mets{j} '\t' repMets(i).metNames{j} '\t' num2str(repMets(i).metPValues(j)) '\n']);
+0172         end
+0173         fprintf('\n');
+0174     end
+0175 end
+0176 
+0177 %Print results to file
+0178 if any(outputFile)
+0179     fid=fopen(outputFile,'w');
+0180     for i=1:numel(repMets)
+0181         fprintf(fid,['REPORTER METABOLITES USING TEST TYPE: ' repMets(i).test '\n']);
+0182         fprintf(fid,'ID\tNAME\tZ-SCORE\tP-VALUE\tNUMBER OF NEIGHBOURS\tAVERAGE Z-SCORE\tSTD Z-SCORE\n');
+0183         for j=1:numel(repMets(i).mets)
+0184             fprintf(fid,[repMets(i).mets{j} '\t' repMets(i).metNames{j} '\t' num2str(repMets(i).metZScores(j)) '\t' num2str(repMets(i).metPValues(j)) '\t' num2str(repMets(i).metNGenes(j)) '\t' num2str(repMets(i).meanZ(j)) '\t' num2str(repMets(i).stdZ(j)) '\n']);
+0185         end
+0186     end
+0187     fclose(fid);
+0188 end
+0189 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/runDynamicFBA.html b/doc/core/runDynamicFBA.html new file mode 100644 index 000000000..252a1cbec --- /dev/null +++ b/doc/core/runDynamicFBA.html @@ -0,0 +1,218 @@ + + + + Description of runDynamicFBA + + + + + + + + + +
Home > core > runDynamicFBA.m
+ + + +

runDynamicFBA +

+ +

PURPOSE ^

+
runDynamicFBA
+ +

SYNOPSIS ^

+
function [concentrationMatrix, excRxnNames, timeVec, biomassVec] = runDynamicFBA(model, substrateRxns, initConcentrations, initBiomass, timeStep, nSteps, plotRxns, exclUptakeRxns)
+ +

DESCRIPTION ^

+
 runDynamicFBA
+   Performs dynamic FBA simulation using the static optimization approach
+
+ Input:
+   model               a model structure
+   substrateRxns       cell array with exchange reaction identifiers for
+                       substrates that are initially in the media, whose
+                       concentration may change (e.g. not h2o or co2)
+   initConcentrations  numeric initial concentrations of substrates
+                       (matching substrateRxns)
+   initBiomass         numeric initial biomass (must be non-zero)
+   timeStep            numeric time step size
+   nSteps              numeric maximum number of time steps
+   plotRxns            cell array with exchange reaction identifiers for
+                       substrates whose concentration should be plotted
+   exclUptakeRxns      cell array with exchange reaction identifiers for
+                       substrates whose concentration does not change
+                       (e.g. co2, o2, h2o, h)
+
+ Output:
+   concentrationMatrix numeric matrix with extracellular metabolite
+                       concentrations
+   excRxnNames         cell array with exchange reaction identifiers that
+                       match the metabolites included in the
+                       concentrationMatrix
+   timeVec             numeric vector of time points
+   biomassVec          numeric vector with biomass concentrations
+
+ If no initial concentration is given for a substrate that has an open
+ uptake in the model (i.e. `model.lb < 0`) the concentration is assumed to
+ be high enough to not be limiting. If the uptake rate for a nutrient is
+ calculated to exceed the maximum uptake rate for that nutrient specified
+ in the model and the max uptake rate specified is > 0, the maximum uptake
+ rate specified in the model is used instead of the calculated uptake
+ rate.
+
+ Modified from COBRA Toolbox dynamicFBA.m
+
+ Usage: [concentrationMatrix, excRxnNames, timeVec, biomassVec] = runDynamicFBA(model, substrateRxns, initConcentrations, initBiomass, timeStep, nSteps, plotRxns, exclUptakeRxns)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function [concentrationMatrix, excRxnNames, timeVec, biomassVec] = runDynamicFBA(model, substrateRxns, initConcentrations, initBiomass, timeStep, nSteps, plotRxns, exclUptakeRxns)
+0002 % runDynamicFBA
+0003 %   Performs dynamic FBA simulation using the static optimization approach
+0004 %
+0005 % Input:
+0006 %   model               a model structure
+0007 %   substrateRxns       cell array with exchange reaction identifiers for
+0008 %                       substrates that are initially in the media, whose
+0009 %                       concentration may change (e.g. not h2o or co2)
+0010 %   initConcentrations  numeric initial concentrations of substrates
+0011 %                       (matching substrateRxns)
+0012 %   initBiomass         numeric initial biomass (must be non-zero)
+0013 %   timeStep            numeric time step size
+0014 %   nSteps              numeric maximum number of time steps
+0015 %   plotRxns            cell array with exchange reaction identifiers for
+0016 %                       substrates whose concentration should be plotted
+0017 %   exclUptakeRxns      cell array with exchange reaction identifiers for
+0018 %                       substrates whose concentration does not change
+0019 %                       (e.g. co2, o2, h2o, h)
+0020 %
+0021 % Output:
+0022 %   concentrationMatrix numeric matrix with extracellular metabolite
+0023 %                       concentrations
+0024 %   excRxnNames         cell array with exchange reaction identifiers that
+0025 %                       match the metabolites included in the
+0026 %                       concentrationMatrix
+0027 %   timeVec             numeric vector of time points
+0028 %   biomassVec          numeric vector with biomass concentrations
+0029 %
+0030 % If no initial concentration is given for a substrate that has an open
+0031 % uptake in the model (i.e. `model.lb < 0`) the concentration is assumed to
+0032 % be high enough to not be limiting. If the uptake rate for a nutrient is
+0033 % calculated to exceed the maximum uptake rate for that nutrient specified
+0034 % in the model and the max uptake rate specified is > 0, the maximum uptake
+0035 % rate specified in the model is used instead of the calculated uptake
+0036 % rate.
+0037 %
+0038 % Modified from COBRA Toolbox dynamicFBA.m
+0039 %
+0040 % Usage: [concentrationMatrix, excRxnNames, timeVec, biomassVec] = runDynamicFBA(model, substrateRxns, initConcentrations, initBiomass, timeStep, nSteps, plotRxns, exclUptakeRxns)
+0041 
+0042 % Find exchange rxns
+0043 excRxnNames = getExchangeRxns(model);
+0044 excRxnNames(ismember(excRxnNames,exclUptakeRxns))=[];
+0045 excInd = getIndexes(model,excRxnNames,'rxns');
+0046 % Figure out if substrate reactions are correct
+0047 missingInd = find(~ismember(substrateRxns,excRxnNames));
+0048 if (~isempty(missingInd))
+0049     for i = 1:length(missingInd)
+0050         fprintf('%s\n',substrateRxns{missingInd(i)});
+0051     end
+0052     error('Invalid substrate uptake reaction!');
+0053 end
+0054 
+0055 % Initialize concentrations
+0056 [~, substrateMatchInd] = ismember(substrateRxns,excRxnNames);
+0057 concentrations = zeros(length(excRxnNames),1);
+0058 concentrations(substrateMatchInd) = initConcentrations;
+0059 
+0060 % Deal with reactions for which there are no initial concentrations
+0061 originalBound = -model.lb(excInd);
+0062 noInitConcentration = (concentrations == 0 & originalBound > 0);
+0063 concentrations(noInitConcentration) = 1000;
+0064 
+0065 biomass = initBiomass;
+0066 
+0067 % Initialize bounds
+0068 uptakeBound =  concentrations/(biomass*timeStep);
+0069 
+0070 % Make sure bounds are not higher than what are specified in the model
+0071 aboveOriginal = (uptakeBound > originalBound) & (originalBound > 0);
+0072 uptakeBound(aboveOriginal) = originalBound(aboveOriginal);
+0073 model.lb(excInd) = -uptakeBound;
+0074 
+0075 concentrationMatrix = concentrations;
+0076 biomassVec = biomass;
+0077 timeVec(1) = 0;
+0078 [~,hsSol]=solveLP(model,1);
+0079 PB = ProgressBar2(nSteps,'Running dynamic FBA analysis','cli');
+0080 for stepNo = 1:nSteps
+0081     % Run FBA
+0082     [sol,hsSol] = solveLP(model,1,[],hsSol);
+0083     mu = sol.f;
+0084     if (sol.stat ~= 1 || mu == 0)
+0085         fprintf('\nNo feasible solution - nutrients exhausted. Biomass:\t %f\n', biomass);
+0086         break;
+0087     end
+0088     uptakeFlux = sol.x(excInd);
+0089     biomass = biomass*exp(mu*timeStep);
+0090     biomassVec(end+1) = biomass;
+0091 
+0092     % Update concentrations
+0093     concentrations = concentrations - uptakeFlux/mu*biomass*(1-exp(mu*timeStep));
+0094     concentrations(concentrations <= 0) = 0;
+0095     concentrationMatrix(:,end+1) = concentrations;
+0096 
+0097     % Update bounds for uptake reactions
+0098     uptakeBound =  concentrations/(biomass*timeStep);
+0099     % This is to avoid any numerical issues
+0100     uptakeBound(uptakeBound > 1000) = 1000;
+0101     % Figure out if the computed bounds were above the original bounds
+0102     aboveOriginal = (uptakeBound > originalBound) & (originalBound > 0);
+0103     % Revert to original bounds if the rate was too high
+0104     uptakeBound(aboveOriginal) = originalBound(aboveOriginal);
+0105     uptakeBound(abs(uptakeBound) < 1e-9) = 0;
+0106 
+0107     model.lb(excInd) = -uptakeBound;
+0108     timeVec(stepNo+1) = stepNo*timeStep;
+0109 
+0110     count(PB);
+0111 end
+0112 
+0113 selNonZero = any(concentrationMatrix>0,2);
+0114 concentrationMatrix = concentrationMatrix(selNonZero,:);
+0115 excRxnNames = excRxnNames(selNonZero);
+0116 selPlot = ismember(excRxnNames,plotRxns);
+0117 
+0118 % Plot concentrations as a function of time
+0119 clf
+0120 subplot(1,2,1);
+0121 plot(timeVec,biomassVec);
+0122 axis tight
+0123 title('Biomass');
+0124 xlabel('Time (h)');
+0125 ylabel('Concentration (g/L)');
+0126 subplot(1,2,2);
+0127 plot(timeVec,concentrationMatrix(selPlot,:));
+0128 axis tight
+0129 title('Substrates and/or products');
+0130 xlabel('Time (h)');
+0131 ylabel('Concentration (mmol/L)');
+0132 legend(strrep(excRxnNames(selPlot),'EX_',''));
+0133 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/runPhenotypePhasePlane.html b/doc/core/runPhenotypePhasePlane.html new file mode 100644 index 000000000..8cf0ac25d --- /dev/null +++ b/doc/core/runPhenotypePhasePlane.html @@ -0,0 +1,161 @@ + + + + Description of runPhenotypePhasePlane + + + + + + + + + +
Home > core > runPhenotypePhasePlane.m
+ + + +

runPhenotypePhasePlane +

+ +

PURPOSE ^

+
runPhenotypePhasePlane
+ +

SYNOPSIS ^

+
function [growthRates, shadowPrices1, shadowPrices2] = runPhenotypePhasePlane(model, controlRxn1, controlRxn2, nPts, range1, range2)
+ +

DESCRIPTION ^

+
 runPhenotypePhasePlane
+   Runs phenotype phase plane analysis and plots the results. The first
+   plot is a 3D surface plot showing the phenotype phase plane, the other
+   two plots show the shadow prices of the metabolites from the two
+   control reactions, which define the phases. Modified from the COBRA
+   phenotypePhasePlane function.
+
+ Input:
+   model           a model structure
+   controlRxn1     reaction identifier of the first reaction to be plotted
+   controlRxn2     reaction identifier of the second reaction to be plotted
+   nPts            the number of points to plot in each dimension (optional,
+                   default 50)
+   range1          the range [from 0 to range1] of reaction 1 to plot
+                   (optional, default 20)
+   range2          the range [from 0 to range2] of reaction 2 to plot
+                   (optional, default 20)
+
+ Output:
+   growthRates1    a matrix of maximum growth rates
+   shadowPrices1   a matrix with shadow prices for reaction 1
+   shadowPrices2   a matrix with shadow prices for reaction 2
+
+ Modified from COBRA Toolbox phenotypePhasePlane.m
+
+ Usage: [growthRates, shadowPrices1, shadowPrices2] = runPhenotypePhasePlane(model, controlRxn1, controlRxn2, nPts, range1, range2)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function [growthRates, shadowPrices1, shadowPrices2] = runPhenotypePhasePlane(model, controlRxn1, controlRxn2, nPts, range1, range2)
+0002 % runPhenotypePhasePlane
+0003 %   Runs phenotype phase plane analysis and plots the results. The first
+0004 %   plot is a 3D surface plot showing the phenotype phase plane, the other
+0005 %   two plots show the shadow prices of the metabolites from the two
+0006 %   control reactions, which define the phases. Modified from the COBRA
+0007 %   phenotypePhasePlane function.
+0008 %
+0009 % Input:
+0010 %   model           a model structure
+0011 %   controlRxn1     reaction identifier of the first reaction to be plotted
+0012 %   controlRxn2     reaction identifier of the second reaction to be plotted
+0013 %   nPts            the number of points to plot in each dimension (optional,
+0014 %                   default 50)
+0015 %   range1          the range [from 0 to range1] of reaction 1 to plot
+0016 %                   (optional, default 20)
+0017 %   range2          the range [from 0 to range2] of reaction 2 to plot
+0018 %                   (optional, default 20)
+0019 %
+0020 % Output:
+0021 %   growthRates1    a matrix of maximum growth rates
+0022 %   shadowPrices1   a matrix with shadow prices for reaction 1
+0023 %   shadowPrices2   a matrix with shadow prices for reaction 2
+0024 %
+0025 % Modified from COBRA Toolbox phenotypePhasePlane.m
+0026 %
+0027 % Usage: [growthRates, shadowPrices1, shadowPrices2] = runPhenotypePhasePlane(model, controlRxn1, controlRxn2, nPts, range1, range2)
+0028 close all force % Close all existing figure windows (if open)
+0029 if nargin < 4
+0030     nPts = 50;
+0031 end
+0032 if nargin < 5
+0033     range1 = 20;
+0034 end
+0035 if nargin < 6
+0036     range2 = 20;
+0037 end
+0038 
+0039 rxnID1 = getIndexes(model,controlRxn1,'rxns',true);
+0040 metID1 = find(model.S(:,rxnID1));
+0041 rxnID2 = getIndexes(model,controlRxn2,'rxns',true);
+0042 metID2 = find(model.S(:,rxnID2));
+0043 
+0044 % Create empty vectors for the results
+0045 ind1 = linspace(0,range1,nPts);
+0046 ind2 = linspace(0,range2,nPts);
+0047 growthRates = zeros(nPts);
+0048 shadowPrices1 = zeros(nPts);
+0049 shadowPrices2 = zeros(nPts);
+0050 [~,hsSol] = solveLP(model);
+0051 % Calulate points
+0052 PB = ProgressBar2(nPts,'Running PhPP analysis','cli');
+0053 for i = 1:nPts %ind1
+0054     for j = 1:nPts %ind2
+0055         model1 = setParam(model,'eq',controlRxn1,-1*ind1(i));
+0056         model1 = setParam(model1,'eq',controlRxn2,-1*ind2(j));
+0057         [fbasol,hsSol] = solveLP(model1,0,[],hsSol);
+0058         try
+0059             growthRates(j,i) = fbasol.x(logical(model1.c));
+0060             shadowPrices1(j,i) = fbasol.sPrice(metID1);
+0061             shadowPrices2(j,i) = fbasol.sPrice(metID2);   
+0062         end
+0063     end
+0064     count(PB);
+0065 end
+0066 fprintf('\b\b\b\b\b\b\b\b\b\b\b\b\bCOMPLETE\n');
+0067 
+0068 % Plot the points
+0069 figure(2);
+0070 pcolor(ind1,ind2,shadowPrices1);
+0071 xlabel(strrep(strcat(controlRxn1,' (mmol/g DW-hr)'),'_','\_')), ylabel(strrep(strcat(controlRxn2,' (mmol/g DW-hr)'),'_','\_')), zlabel('growth rate (1/hr)');
+0072 title(['Shadow price ' strrep(model.mets{metID1},'_','-')]);
+0073 colorbar();
+0074 xticklabels(sprintfc('%d', -xticks))
+0075 yticklabels(sprintfc('%d', -yticks))
+0076 figure(3);
+0077 pcolor(ind1,ind2,shadowPrices2);
+0078 xlabel(strrep(strcat(controlRxn1,' (mmol/g DW-hr)'),'_','\_')), ylabel(strrep(strcat(controlRxn2,' (mmol/g DW-hr)'),'_','\_')), zlabel('growth rate (1/hr)');
+0079 title(['Shadow price ' strrep(model.mets{metID2},'_','-')]);
+0080 colorbar();
+0081 xticklabels(sprintfc('%d', -xticks))
+0082 yticklabels(sprintfc('%d', -yticks))
+0083 figure(1);
+0084 surfl(ind1,ind2,growthRates);
+0085 xlabel(strrep(strcat(controlRxn1,' (mmol/g DW-hr)'),'_','\_')), ylabel(strrep(strcat(controlRxn2,' (mmol/g DW-hr)'),'_','\_')), zlabel('growth rate (1/hr)');
+0086 colormap(hsv(17));
+0087 xticklabels(sprintfc('%d', -xticks))
+0088 yticklabels(sprintfc('%d', -yticks))
+0089 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/runProductionEnvelope.html b/doc/core/runProductionEnvelope.html new file mode 100644 index 000000000..6c243ae88 --- /dev/null +++ b/doc/core/runProductionEnvelope.html @@ -0,0 +1,127 @@ + + + + Description of runProductionEnvelope + + + + + + + + + +
Home > core > runProductionEnvelope.m
+ + + +

runProductionEnvelope +

+ +

PURPOSE ^

+
runProductionEnvelope
+ +

SYNOPSIS ^

+
function [biomassValues, targetValues] = runProductionEnvelope(model, targetRxn, biomassRxn, nPts)
+ +

DESCRIPTION ^

+
 runProductionEnvelope
+   Calculates the byproduct secretion envelope
+
+ Input:
+   model            a model structure
+   targetRxn        identifier of target metabolite production reaction
+   biomassRxn       identifier of biomass reaction
+   nPts             number of points in the plot (optional, default 20)
+
+ Output:
+   biomassValues    Biomass values for plotting
+   targetValues     Target upper and lower bounds for plotting
+
+ Modified from COBRA Toolbox productionEnvelope.m
+
+ Usage: [biomassValues, targetValues] = runProductionEnvelope(model,...
+               targetRxn, biomassRxn, nPts)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function [biomassValues, targetValues] = runProductionEnvelope(model, targetRxn, biomassRxn, nPts)
+0002 % runProductionEnvelope
+0003 %   Calculates the byproduct secretion envelope
+0004 %
+0005 % Input:
+0006 %   model            a model structure
+0007 %   targetRxn        identifier of target metabolite production reaction
+0008 %   biomassRxn       identifier of biomass reaction
+0009 %   nPts             number of points in the plot (optional, default 20)
+0010 %
+0011 % Output:
+0012 %   biomassValues    Biomass values for plotting
+0013 %   targetValues     Target upper and lower bounds for plotting
+0014 %
+0015 % Modified from COBRA Toolbox productionEnvelope.m
+0016 %
+0017 % Usage: [biomassValues, targetValues] = runProductionEnvelope(model,...
+0018 %               targetRxn, biomassRxn, nPts)
+0019 
+0020 if nargin < 4
+0021     nPts = 20;
+0022 end
+0023 
+0024 % Run FBA to get upper bound for biomass
+0025 model   = setParam(model,'obj',biomassRxn,1);
+0026 [solMax,hsSol]  = solveLP(model);
+0027 solMax  = solMax.x(logical(model.c));
+0028 model.c = -model.c;
+0029 solMin  = solveLP(model,0,[],hsSol);
+0030 solMin  = solMin.x(logical(model.c));
+0031 
+0032 % Create biomass range vector
+0033 biomassValues = linspace(solMin,solMax,nPts);
+0034 targetUpperBound = nan(1,numel(biomassValues));
+0035 targetLowerBound = nan(1,numel(biomassValues));
+0036 
+0037 PB = ProgressBar2(length(biomassValues),'Creating production envelope','cli');
+0038 % Max/min for target production
+0039 model = setParam(model,'obj',targetRxn,1);
+0040 for i = 1:length(biomassValues)
+0041     model1 = setParam(model,'eq',biomassRxn,biomassValues(i));
+0042     sol = solveLP(model1,0,[],hsSol);
+0043     if (sol.stat > 0)
+0044         targetUpperBound(i) = sol.x(logical(model.c));
+0045     else
+0046         targetUpperBound(i) = NaN;
+0047     end
+0048     model1.c = -model1.c;
+0049     sol = solveLP(model1,0,[],hsSol);
+0050     if (sol.stat > 0)
+0051         targetLowerBound(i) = sol.x(logical(model1.c));
+0052     else
+0053         targetLowerBound(i) = NaN;
+0054     end
+0055     count(PB);
+0056 end
+0057 
+0058 % Plot results
+0059 plot([biomassValues fliplr(biomassValues)],[targetUpperBound fliplr(targetLowerBound)],'blue','LineWidth',2);
+0060 axis tight;
+0061 ylabel([strrep(targetRxn,'_','-') ' (mmol/gDW h)']);
+0062 xlabel('Growth rate (1/h)');
+0063 targetValues = [targetLowerBound; targetUpperBound];
+0064 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/runRobustnessAnalysis.html b/doc/core/runRobustnessAnalysis.html new file mode 100644 index 000000000..7a7187156 --- /dev/null +++ b/doc/core/runRobustnessAnalysis.html @@ -0,0 +1,140 @@ + + + + Description of runRobustnessAnalysis + + + + + + + + + +
Home > core > runRobustnessAnalysis.m
+ + + +

runRobustnessAnalysis +

+ +

PURPOSE ^

+
runRobustnessAnalysis
+ +

SYNOPSIS ^

+
function [controlFlux, objFlux] = runRobustnessAnalysis(model, controlRxn, nPoints, objRxn, plotRedCost)
+ +

DESCRIPTION ^

+
 runRobustnessAnalysis
+   Performs robustness analysis for a reaction of interest and an objective
+   of interest. Modified from the COBRA robustnessAnalysis function.
+
+ Input:
+   model           a model structure
+   controlRxn      reaction of interest whose value is to be controlled
+   nPoints         number of points to show on plot (optional, default 20)
+   objRxn          reaction identifier of objective to be maximized (optional,
+                   default it uses the objective defined in the model)
+   plotRedCost     logical whether reduced cost should also be plotted
+                   (optional, default false)
+
+ Output:
+   controlFlux     flux values of the reaction of interest, ranging from
+                   its minimum to its maximum value
+   objFlux         optimal values of objective reaction at each control
+                   reaction flux value
+
+ Modified from COBRA Toolbox robustnessAnalysis.m
+
+ Usage: runRobustnessAnalysis(model, controlRxn, nPoints, objRxn)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function [controlFlux, objFlux] = runRobustnessAnalysis(model, controlRxn, nPoints, objRxn, plotRedCost)
+0002 % runRobustnessAnalysis
+0003 %   Performs robustness analysis for a reaction of interest and an objective
+0004 %   of interest. Modified from the COBRA robustnessAnalysis function.
+0005 %
+0006 % Input:
+0007 %   model           a model structure
+0008 %   controlRxn      reaction of interest whose value is to be controlled
+0009 %   nPoints         number of points to show on plot (optional, default 20)
+0010 %   objRxn          reaction identifier of objective to be maximized (optional,
+0011 %                   default it uses the objective defined in the model)
+0012 %   plotRedCost     logical whether reduced cost should also be plotted
+0013 %                   (optional, default false)
+0014 %
+0015 % Output:
+0016 %   controlFlux     flux values of the reaction of interest, ranging from
+0017 %                   its minimum to its maximum value
+0018 %   objFlux         optimal values of objective reaction at each control
+0019 %                   reaction flux value
+0020 %
+0021 % Modified from COBRA Toolbox robustnessAnalysis.m
+0022 %
+0023 % Usage: runRobustnessAnalysis(model, controlRxn, nPoints, objRxn)
+0024 
+0025 if nargin < 3
+0026     nPoints = 20;
+0027 end
+0028 if nargin < 4
+0029     baseModel = model;
+0030 else
+0031     baseModel = setParam(model,'obj',objRxn,1);
+0032 end
+0033 if nargin < 5
+0034     plotRedCost = false;
+0035 end
+0036 
+0037 if any(ismember(model.rxns,controlRxn))
+0038     controlRxnIdx = getIndexes(model,controlRxn,'rxns');
+0039     tmpModel = setParam(model,'obj',controlRxnIdx,1);
+0040     solMax = solveLP(tmpModel);
+0041     solMax = solMax.x(logical(tmpModel.c));
+0042     tmpModel.c = -tmpModel.c;
+0043     solMin = solveLP(tmpModel);
+0044     solMin = solMin.x(logical(tmpModel.c));
+0045 else
+0046     error('Control reaction does not exist!');
+0047 end
+0048 
+0049 objFlux = zeros(nPoints,1);
+0050 redCost = zeros(nPoints,1);
+0051 controlFlux = linspace(solMin,solMax,nPoints)';
+0052 
+0053 
+0054 PB = ProgressBar2(length(controlFlux),'Running robustness analysis','cli');
+0055 for i=1:length(controlFlux)
+0056     modelControlled = setParam(baseModel,'eq',controlRxnIdx,controlFlux(i));
+0057     solControlled = solveLP(modelControlled);
+0058     objFlux(i) = solControlled.x(logical(modelControlled.c));
+0059     redCost(i) = solControlled.rCost(controlRxnIdx);
+0060     count(PB);
+0061 end
+0062 
+0063 if plotRedCost
+0064     yyaxis right
+0065     plot(controlFlux,redCost)
+0066     ylabel([strrep(controlRxn,'_','-') ' reduced cost']);
+0067     yyaxis left
+0068 end
+0069 plot(controlFlux,objFlux)
+0070 xlabel(strrep(controlRxn,'_','-'));
+0071 ylabel('Objective');
+0072 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/runSimpleOptKnock.html b/doc/core/runSimpleOptKnock.html new file mode 100644 index 000000000..048f89006 --- /dev/null +++ b/doc/core/runSimpleOptKnock.html @@ -0,0 +1,198 @@ + + + + Description of runSimpleOptKnock + + + + + + + + + +
Home > core > runSimpleOptKnock.m
+ + + +

runSimpleOptKnock +

+ +

PURPOSE ^

+
runSimpleOptKnock
+ +

SYNOPSIS ^

+
function out = runSimpleOptKnock(model, targetRxn, biomassRxn, deletions, genesOrRxns, maxNumKO, minGrowth)
+ +

DESCRIPTION ^

+
 runSimpleOptKnock
+   Simple OptKnock algorithm that checks all gene or reaction deletions
+   for growth-coupled metabolite production, by testing all possible
+   combinations. This is not defined as MILP, and is therefore slow (but
+   simple).
+
+ Input:
+    model          a model structure
+    targetRxn      identifier of target reaction
+    biomassRxn     identifier of biomass reaction
+    deletions      cell array with gene or reaction identifiers that
+                   should be considered for knockout
+                   (optional, default = model.rxns)
+    genesOrRxns    string indicating whether deletions parameter is given
+                   with 'genes' or 'rxns' identifiers (optional, default
+                   'rxns')
+    maxNumKO       numeric with maximum number of simulatenous knockout
+                   (optional, default 1)
+    minGrowth      numeric of minimum growth rate (optional, default 0.05)
+
+ Output:
+    out            structure with deletions strategies that result in
+                   growth-coupled production
+       KO          cell array with gene(s) or reaction(s) to be deleted
+       growthRate  vector with growth rates after deletion
+       prodRate    vector with production rates after deletion
+
+ Usage: out = runSimpleOptKnock(model, targetRxn, biomassRxn, deletions,...
+                   genesOrRxns, maxNumKO, minGrowth)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 function out = runSimpleOptKnock(model, targetRxn, biomassRxn, deletions, genesOrRxns, maxNumKO, minGrowth)
+0002 % runSimpleOptKnock
+0003 %   Simple OptKnock algorithm that checks all gene or reaction deletions
+0004 %   for growth-coupled metabolite production, by testing all possible
+0005 %   combinations. This is not defined as MILP, and is therefore slow (but
+0006 %   simple).
+0007 %
+0008 % Input:
+0009 %    model          a model structure
+0010 %    targetRxn      identifier of target reaction
+0011 %    biomassRxn     identifier of biomass reaction
+0012 %    deletions      cell array with gene or reaction identifiers that
+0013 %                   should be considered for knockout
+0014 %                   (optional, default = model.rxns)
+0015 %    genesOrRxns    string indicating whether deletions parameter is given
+0016 %                   with 'genes' or 'rxns' identifiers (optional, default
+0017 %                   'rxns')
+0018 %    maxNumKO       numeric with maximum number of simulatenous knockout
+0019 %                   (optional, default 1)
+0020 %    minGrowth      numeric of minimum growth rate (optional, default 0.05)
+0021 %
+0022 % Output:
+0023 %    out            structure with deletions strategies that result in
+0024 %                   growth-coupled production
+0025 %       KO          cell array with gene(s) or reaction(s) to be deleted
+0026 %       growthRate  vector with growth rates after deletion
+0027 %       prodRate    vector with production rates after deletion
+0028 %
+0029 % Usage: out = runSimpleOptKnock(model, targetRxn, biomassRxn, deletions,...
+0030 %                   genesOrRxns, maxNumKO, minGrowth)
+0031 
+0032 if nargin < 4
+0033     params.deletions = model.rxns;
+0034 else
+0035     params.deletions = deletions;
+0036 end
+0037 if nargin < 5
+0038     params.genesOrRxns = 'rxns';
+0039 else
+0040     params.genesOrRxns = genesOrRxns;
+0041 end
+0042 if nargin < 6
+0043     params.maxNumKO = 1;
+0044 else
+0045     params.maxNumKO = maxNumKO;
+0046 end
+0047 if nargin < 7
+0048     params.minGrowth = 0.05;
+0049 else
+0050     params.minGrowth = minGrowth;
+0051 end
+0052 
+0053 % Number of deletions
+0054 out.KO         = cell(0,params.maxNumKO); % The KO genes/rxns
+0055 out.growthRate = zeros(0);
+0056 out.prodRate   = zeros(0);
+0057 out.score      = zeros(0);
+0058 
+0059 params.biomassIdx  = getIndexes(model,biomassRxn,'rxns');
+0060 params.targetIdx   = getIndexes(model,targetRxn,'rxns');
+0061 
+0062 model = setParam(model,'obj',params.biomassIdx,1);
+0063 [solWT, hsSol] = solveLP(model);
+0064 WT.minScore = solWT.x(params.targetIdx)*solWT.f;
+0065 
+0066 fprintf('Running simple OptKnock analysis...   0%% complete');
+0067 KO=zeros(1,params.maxNumKO);
+0068 [~,~,out,~] = knockoutIteration(model,params,WT,out,params.maxNumKO,KO,[],hsSol);
+0069 
+0070 if size(out.KO,2)>1
+0071     singleKO = cellfun(@isempty,out.KO(:,1));
+0072     if any(singleKO)
+0073         singleKO = out.KO{singleKO,2};
+0074         singleKO = strcmp(out.KO(:,1),singleKO);
+0075         out.KO(singleKO,:) = [];
+0076         out.growthRate(singleKO,:) = [];
+0077         out.prodRate(singleKO,:) = [];
+0078         out.score(singleKO,:) = [];
+0079     end
+0080 end
+0081 
+0082 
+0083 fprintf('\b\b\b\b\b\b\b\b\b\b\b\b\bCOMPLETE\n');
+0084 end
+0085 
+0086 function [model,iteration,out,KO,hsSol] = knockoutIteration(model,params,WT,out,iteration,KO,minScore,hsSol)
+0087 if nargin<7 || isempty(minScore)
+0088     minScore = WT.minScore;
+0089 end
+0090 iteration = iteration - 1;
+0091 for i = 1:numel(params.deletions)
+0092     if iteration+1==params.maxNumKO
+0093         progress=pad(num2str(floor(i/numel(params.deletions)*100)),3,'left');
+0094         fprintf('\b\b\b\b\b\b\b\b\b\b\b\b\b%s%% complete',progress);
+0095     end
+0096     KO(iteration+1)=i;
+0097     switch params.genesOrRxns
+0098         case 'rxns'
+0099             modelKO = setParam(model,'eq',params.deletions{i},0);
+0100         case 'genes'
+0101             modelKO = removeGenes(model,params.deletions{i},false,false,false);
+0102     end
+0103     solKO = solveLP(modelKO,0,[],hsSol);
+0104     if ~isempty(solKO.f)
+0105         growthRate = solKO.f;
+0106         prodRate   = solKO.x(params.targetIdx);
+0107         prodRate(prodRate<1e-10)=0; % Filter out results from solver tolerance
+0108         if growthRate > params.minGrowth
+0109             if growthRate*prodRate > minScore*1.01
+0110                 out.KO(end+1,find(KO)) = transpose(params.deletions(KO(find(KO))));
+0111                 out.growthRate(end+1,1) = growthRate;
+0112                 out.prodRate(end+1,1)   = prodRate;
+0113                 out.score(end+1,1)      = growthRate*prodRate;
+0114             end
+0115             if iteration>0
+0116                 [~,~,out] = knockoutIteration(modelKO,params,WT,out,iteration,KO,growthRate*prodRate,hsSol);
+0117             end
+0118         end
+0119     end
+0120 end
+0121 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/setExchangeBounds.html b/doc/core/setExchangeBounds.html new file mode 100644 index 000000000..315190cf3 --- /dev/null +++ b/doc/core/setExchangeBounds.html @@ -0,0 +1,309 @@ + + + + Description of setExchangeBounds + + + + + + + + + +
Home > core > setExchangeBounds.m
+ + + +

setExchangeBounds +

+ +

PURPOSE ^

+
setExchangeBounds
+ +

SYNOPSIS ^

+
function [exchModel,unusedMets] = setExchangeBounds(model,mets,lb,ub,closeOthers,mediaOnly)
+ +

DESCRIPTION ^

+
 setExchangeBounds
+   Define the exchange flux bounds for a given set of metabolites.
+
+ Input:
+   model         a model structure
+   mets          a cell array of metabolite names (case insensitive) or 
+                 metabolite IDs, or a vector of metabolite indices
+                 (optional, default all exchanged metabolites)
+   lb            lower bound of exchange flux. Can be either a vector of
+                 bounds corresponding to each of the provided metabolites,
+                 or a single value that will be applied to all.
+                 (optional, default to model.annotation.defaultLB if it exists,
+                 otherwise -1000)
+   ub            upper bound of exchange flux. Can be either a vector of
+                 bounds corresponding to each of the provided metabolites,
+                 or a single value that will be applied to all.
+                 (optional, default to model.annotation.defaultUB if it exists,
+                 otherwise 1000)
+   closeOthers   close exchange reactions for all other exchanged 
+                 metabolites not present in the provided list. This will
+                 prevent IMPORT of the metabolites, but their EXPORT will
+                 not be modified.
+                 (optional, default true)
+   mediaOnly     only consider exchange reactions involving exchange to or
+                 from the extracellular (media) compartment. Reactions
+                 such as "sink" reactions that exchange metabolites
+                 directly with an intracellular compartment will therefore
+                 be ignored even though "getExchangeRxns" identifies such
+                 such reactions as exchange reactions.
+                 Note: The function will attempt to identify the
+                 extracellular compartment by the "compNames" field, and
+                 also requires the "metComps" field to be present,
+                 otherwise the mediaOnly flag will be ignored.
+                 (optional, default false)
+
+ Output:
+   exchModel     a model structure with updated exchange flux bounds for
+                 the provided set of metabolites
+   unusedMets    metabolites provided by the user that were not used
+                 because they are not involved in any exchange reactions
+                 in the model
+
+ NOTE: Exchange reactions involving more than one metabolite will be
+ ignored.
+
+ Usage: exchModel = setExchangeBounds(model,mets,lb,ub,closeOthers,mediaOnly);
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function [exchModel,unusedMets] = setExchangeBounds(model,mets,lb,ub,closeOthers,mediaOnly)
+0002 % setExchangeBounds
+0003 %   Define the exchange flux bounds for a given set of metabolites.
+0004 %
+0005 % Input:
+0006 %   model         a model structure
+0007 %   mets          a cell array of metabolite names (case insensitive) or
+0008 %                 metabolite IDs, or a vector of metabolite indices
+0009 %                 (optional, default all exchanged metabolites)
+0010 %   lb            lower bound of exchange flux. Can be either a vector of
+0011 %                 bounds corresponding to each of the provided metabolites,
+0012 %                 or a single value that will be applied to all.
+0013 %                 (optional, default to model.annotation.defaultLB if it exists,
+0014 %                 otherwise -1000)
+0015 %   ub            upper bound of exchange flux. Can be either a vector of
+0016 %                 bounds corresponding to each of the provided metabolites,
+0017 %                 or a single value that will be applied to all.
+0018 %                 (optional, default to model.annotation.defaultUB if it exists,
+0019 %                 otherwise 1000)
+0020 %   closeOthers   close exchange reactions for all other exchanged
+0021 %                 metabolites not present in the provided list. This will
+0022 %                 prevent IMPORT of the metabolites, but their EXPORT will
+0023 %                 not be modified.
+0024 %                 (optional, default true)
+0025 %   mediaOnly     only consider exchange reactions involving exchange to or
+0026 %                 from the extracellular (media) compartment. Reactions
+0027 %                 such as "sink" reactions that exchange metabolites
+0028 %                 directly with an intracellular compartment will therefore
+0029 %                 be ignored even though "getExchangeRxns" identifies such
+0030 %                 such reactions as exchange reactions.
+0031 %                 Note: The function will attempt to identify the
+0032 %                 extracellular compartment by the "compNames" field, and
+0033 %                 also requires the "metComps" field to be present,
+0034 %                 otherwise the mediaOnly flag will be ignored.
+0035 %                 (optional, default false)
+0036 %
+0037 % Output:
+0038 %   exchModel     a model structure with updated exchange flux bounds for
+0039 %                 the provided set of metabolites
+0040 %   unusedMets    metabolites provided by the user that were not used
+0041 %                 because they are not involved in any exchange reactions
+0042 %                 in the model
+0043 %
+0044 % NOTE: Exchange reactions involving more than one metabolite will be
+0045 % ignored.
+0046 %
+0047 % Usage: exchModel = setExchangeBounds(model,mets,lb,ub,closeOthers,mediaOnly);
+0048 
+0049 
+0050 % handle input arguments
+0051 if nargin < 2
+0052     mets = [];
+0053 elseif ~islogical(mets) || ~isnumeric(mets)
+0054     mets=convertCharArray(mets);
+0055 end 
+0056 
+0057 if nargin < 3 || isempty(lb)
+0058     if isfield(model,'annotation') && isfield(model.annotation,'defaultLB')
+0059         lb = model.annotation.defaultLB;
+0060     else
+0061         lb = -1000;
+0062     end
+0063 end
+0064 
+0065 if nargin < 4 || isempty(ub)
+0066     if isfield(model,'annotation') && isfield(model.annotation,'defaultUB')
+0067         ub = model.annotation.defaultUB;
+0068     else
+0069         ub = 1000;
+0070     end
+0071 end
+0072 
+0073 if nargin < 5 || isempty(closeOthers)
+0074     closeOthers = true;
+0075 end
+0076 
+0077 if nargin < 6
+0078     mediaOnly = false;
+0079 elseif mediaOnly
+0080     if ~all(isfield(model,{'compNames','metComps'}))
+0081         error('mediaOnly option requires the "compNames" and "metComps" model fields.');
+0082     end
+0083 end
+0084 
+0085 
+0086 % for models with an "unconstrained" field, generate a version of the model
+0087 % where all the unconstrained metabolites have stoichiometric coeffs set to
+0088 % zero, but remain in the model to avoid index changes
+0089 model_temp = model;
+0090 if isfield(model,'unconstrained')
+0091     model_temp.S(model_temp.unconstrained == 1,:) = 0;
+0092 end
+0093 
+0094 % find exchange rxns, ignoring those involving more than one metabolite
+0095 [~,exchRxnInd] = getExchangeRxns(model);
+0096 exchRxnInd(sum(model_temp.S(:,exchRxnInd) ~= 0,1) > 1) = [];
+0097 
+0098 % find all exchanged metabolites
+0099 exchMetInd = find(any(model_temp.S(:,exchRxnInd) ~= 0,2));
+0100 
+0101 if ( mediaOnly )
+0102     % ignore exchanged metabolites in non-extracellular compartments and
+0103     % any exchange reactions involving these metabolites
+0104     [~,extCompInd] = ismember('extracellular',lower(model.compNames));
+0105     if extCompInd > 0
+0106         ignoreMet = (model.metComps(exchMetInd) ~= extCompInd);
+0107     else
+0108         error('Could not find any compartments named "extracellular".');
+0109     end
+0110     ignoreRxn = any(model.S(exchMetInd(ignoreMet),exchRxnInd) ~= 0,1);
+0111     exchMetInd(ignoreMet) = [];
+0112     exchRxnInd(ignoreRxn) = [];
+0113 end
+0114 
+0115 % Check that all exchange reactions are formulated in the same direction.
+0116 % If not, this means that negative flux indicates import for some exchange
+0117 % reactions, but indicates export for others. Therefore, the LB and UB
+0118 % would need to be specified differently depending on the exchange reaction
+0119 % direction, which is error-prone.
+0120 if all(all(model.S(exchMetInd,exchRxnInd) <= 0))
+0121     importDir = 'backward';
+0122 elseif all(all(model.S(exchMetInd,exchRxnInd) >= 0))
+0123     importDir = 'forward';
+0124 else
+0125     fprintf('WARNING: Some exchange reactions differ in direction, and therefore have opposite meanings of LB and UB.\n');
+0126     if closeOthers
+0127         fprintf('         Therefore, the "closeOthers" option will be set to FALSE.\n');
+0128     end
+0129     closeOthers = false;
+0130 end
+0131 
+0132 % prepare exchanged metabolites and bounds
+0133 if ~isempty(mets)
+0134     
+0135     % prepare lb and ub variables
+0136     if numel(lb) == 1
+0137         lb = lb*ones(size(mets));
+0138     elseif numel(lb) ~= numel(mets)
+0139         error('lb must be a single value or a vector of equal length as mets');
+0140     end
+0141     if numel(ub) == 1
+0142         ub = ub*ones(size(mets));
+0143     elseif numel(ub) ~= numel(mets)
+0144         error('ub must be a single value or a vector of equal length as mets');
+0145     end
+0146     
+0147     % map provided mets to exchanged metabolites
+0148     if isnumeric(mets)
+0149         % mets are provided as indices
+0150         [isExch,metInd] = ismember(mets,exchMetInd);    
+0151     elseif sum(ismember(lower(mets),lower(model.metNames))) > sum(ismember(mets,model.mets))
+0152         % assume that mets are provided as names
+0153         [isExch,metInd] = ismember(lower(mets),lower(model.metNames(exchMetInd)));
+0154     else
+0155         % assume that mets are provided as met IDs
+0156         [isExch,metInd] = ismember(mets,model.mets(exchMetInd));
+0157     end
+0158     
+0159     % get exchanged met indices and determine unused (non-exchanged) mets
+0160     unusedMets = mets(~isExch);
+0161     exchMetInd = exchMetInd(metInd(isExch));
+0162     
+0163     % update bound vectors
+0164     lb = lb(isExch);
+0165     ub = ub(isExch);
+0166     
+0167 else
+0168     % if no mets were provided, use all exchanged mets
+0169     if numel(lb) > 1 || numel(ub) > 1
+0170         error('Only one upper and one lower bound may be provide if metabolites are not specified.');
+0171     else
+0172         lb = lb*ones(size(exchMetInd));
+0173         ub = ub*ones(size(exchMetInd));
+0174     end
+0175     unusedMets = {};
+0176 end
+0177 
+0178 % check that at least one exchanged metabolite matches
+0179 if isempty(exchMetInd)
+0180     fprintf('None of the provided metabolites were found in any exchange reactions.\n');
+0181     exchModel = model;
+0182     return
+0183 end
+0184 
+0185 % determine which metabolite is exchanged in each exchange reaction
+0186 [metInd,rxnInd] = find(model_temp.S(exchMetInd,exchRxnInd) ~= 0);
+0187 
+0188 % check for any metabolites that are exchanged in more than one reaction
+0189 [tbl,i,~] = unique(metInd,'first');
+0190 repeatedInds = find(not(ismember(1:numel(tbl),i)));
+0191 multiMetInd = exchMetInd(metInd(repeatedInds));
+0192 if ~isempty(multiMetInd)
+0193     fprintf('WARNING: The following metabolites are involved in more than one exchange reaction:\n');
+0194     fprintf('\t%s\n',model.metNames{multiMetInd(1:min(numel(multiMetInd),10))});
+0195     if numel(multiMetInd) > 10
+0196         fprintf('\t... and %u more.\n',numel(multiMetInd)-10);
+0197     end
+0198 end
+0199 
+0200 % set exchange reaction bounds
+0201 model = setParam(model,'lb',exchRxnInd(rxnInd),lb(metInd));
+0202 model = setParam(model,'ub',exchRxnInd(rxnInd),ub(metInd));
+0203 
+0204 if closeOthers
+0205     % constrain import of all other exchange reactions to zero
+0206     constrainInd = setdiff(exchRxnInd,exchRxnInd(rxnInd));
+0207     if strcmp(importDir,'backward')
+0208         model = setParam(model,'lb',constrainInd,0);
+0209     else
+0210         model = setParam(model,'ub',constrainInd,0);
+0211     end
+0212 end
+0213 
+0214 % assign output model
+0215 exchModel = model;
+0216 
+0217
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/setParam.html b/doc/core/setParam.html new file mode 100644 index 000000000..313197877 --- /dev/null +++ b/doc/core/setParam.html @@ -0,0 +1,202 @@ + + + + Description of setParam + + + + + + + + + +
Home > core > setParam.m
+ + + +

setParam +

+ +

PURPOSE ^

+
setParam
+ +

SYNOPSIS ^

+
function model=setParam(model, paramType, rxnList, params, var)
+ +

DESCRIPTION ^

+
 setParam
+   Sets parameters for reactions
+
+ Input:
+   model       a model structure
+   paramType   the type of parameter to set:
+               'lb'    lower bound
+               'ub'    upper bound
+               'eq'    both upper and lower bound (equality constraint)
+               'obj'   objective coefficient
+               'rev'   reversibility (only changes the model.rev fields,
+                       does not affect model.lb and model.ub) 
+               'var'   variance around measured bound
+               'unc'   unconstrained, set lower and upper bound to the
+                       default values (-1000 and 1000, or any other values
+                       that are defined in model.annotation.defaultLB and
+                       .defaultUB)
+   rxnList     a cell array of reaction IDs or a vector with their
+               corresponding indexes
+   params      a vector of the corresponding values
+   var         percentage of variance around measured value, if 'var' is
+               set as paramType. Defining 'var' as 5 results in lb and ub
+               at 97.5% and 102.5% of the provide params value (if params
+               value is negative, then lb and ub are 102.5% and 97.5%).
+
+ Output:
+   model       an updated model structure
+
+ Usage: model = setParam(model, paramType, rxnList, params, var)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function model=setParam(model, paramType, rxnList, params, var)
+0002 % setParam
+0003 %   Sets parameters for reactions
+0004 %
+0005 % Input:
+0006 %   model       a model structure
+0007 %   paramType   the type of parameter to set:
+0008 %               'lb'    lower bound
+0009 %               'ub'    upper bound
+0010 %               'eq'    both upper and lower bound (equality constraint)
+0011 %               'obj'   objective coefficient
+0012 %               'rev'   reversibility (only changes the model.rev fields,
+0013 %                       does not affect model.lb and model.ub)
+0014 %               'var'   variance around measured bound
+0015 %               'unc'   unconstrained, set lower and upper bound to the
+0016 %                       default values (-1000 and 1000, or any other values
+0017 %                       that are defined in model.annotation.defaultLB and
+0018 %                       .defaultUB)
+0019 %   rxnList     a cell array of reaction IDs or a vector with their
+0020 %               corresponding indexes
+0021 %   params      a vector of the corresponding values
+0022 %   var         percentage of variance around measured value, if 'var' is
+0023 %               set as paramType. Defining 'var' as 5 results in lb and ub
+0024 %               at 97.5% and 102.5% of the provide params value (if params
+0025 %               value is negative, then lb and ub are 102.5% and 97.5%).
+0026 %
+0027 % Output:
+0028 %   model       an updated model structure
+0029 %
+0030 % Usage: model = setParam(model, paramType, rxnList, params, var)
+0031 
+0032 paramType=convertCharArray(paramType);
+0033 if ~any(strcmpi(paramType,{'lb','ub','eq','obj','rev','var','unc'}))
+0034     EM=['Incorrect parameter type: "' paramType{1} '"'];
+0035     dispEM(EM);
+0036 end
+0037 if isnumeric(rxnList) || islogical(rxnList)
+0038     rxnList=model.rxns(rxnList);
+0039 else
+0040     rxnList=convertCharArray(rxnList);
+0041 end
+0042 if isempty(rxnList)
+0043     return;
+0044 end
+0045 
+0046 %Allow to set several parameters to the same value
+0047 if numel(rxnList)~=numel(params) && numel(params)~=1
+0048     EM='The number of parameter values and the number of reactions must be the same';
+0049     dispEM(EM);
+0050 end
+0051 
+0052 if length(rxnList)>1
+0053     if length(paramType)==1
+0054         paramType(1:length(rxnList))=paramType;
+0055     end
+0056     if length(params)==1
+0057         params(1:length(rxnList))=params;
+0058     end
+0059 end
+0060 
+0061 %Find the indexes for the reactions in rxnList. Do not use getIndexes
+0062 %as we do not want to throw errors if matches fail
+0063 indexes=zeros(numel(rxnList),1);
+0064 
+0065 [Lia,Locb] = ismember(rxnList,model.rxns);
+0066 indexes(Lia) = Locb;
+0067 if any(~Lia)
+0068     params(~Lia)=[];
+0069     indexes(~Lia)=[];
+0070     paramType(~Lia)=[];
+0071     dispEM('Reactions not present in model, will be ignored:',false,rxnList(~Lia));
+0072 end
+0073 
+0074 %Change the parameters
+0075 if ~isempty(indexes)
+0076     if contains(paramType,'obj')
+0077         model.c=zeros(numel(model.c),1); % parameter is changed, not added
+0078     end
+0079     for j=1:length(paramType)
+0080         if strcmpi(paramType{j},'eq')
+0081             model.lb(indexes(j))=params(j);
+0082             model.ub(indexes(j))=params(j);
+0083         end
+0084         if strcmpi(paramType{j},'lb')
+0085             model.lb(indexes(j))=params(j);
+0086         end
+0087         if strcmpi(paramType{j},'ub')
+0088             model.ub(indexes(j))=params(j);
+0089         end
+0090         if strcmpi(paramType{j},'obj')
+0091             model.c(indexes(j))=params(j);
+0092         end
+0093         if strcmpi(paramType{j},'rev')
+0094             %Non-zero values are interpreted as reversible
+0095             model.rev(indexes(j))=params(j)~=0;
+0096         end
+0097         if strcmpi(paramType{j},'var')
+0098             if params(j) < 0
+0099                 model.lb(indexes(j)) = params(j) * (1+var/200);
+0100                 model.ub(indexes(j)) = params(j) * (1-var/200);
+0101             else
+0102                 model.lb(indexes(j)) = params(j) * (1-var/200);
+0103                 model.ub(indexes(j)) = params(j) * (1+var/200);
+0104             end
+0105         end
+0106         if strcmpi(paramType{j},'unc')
+0107             if isfield(model.annotation,'defaultLB')
+0108                 lb = model.annotation.defaultLB;
+0109             else
+0110                 lb = -1000;
+0111             end
+0112             if isfield(model.annotation,'defaultUB')
+0113                 ub = model.annotation.defaultUB;
+0114             else
+0115                 ub = 1000;
+0116             end
+0117             model.lb(indexes(j)) = lb;
+0118             model.ub(indexes(j)) = ub;
+0119         end
+0120     end
+0121 end
+0122 if any(ismember(paramType,{'lb','ub','unc'}))
+0123     invalidBound = model.lb(indexes) > model.ub(indexes);
+0124     if any(invalidBound)
+0125         error(['Invalid set of bounds for reaction(s): ', strjoin(model.rxns(indexes(invalidBound)),', '), '.'])
+0126     end
+0127 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/simplifyModel.html b/doc/core/simplifyModel.html new file mode 100644 index 000000000..b47bde2de --- /dev/null +++ b/doc/core/simplifyModel.html @@ -0,0 +1,403 @@ + + + + Description of simplifyModel + + + + + + + + + +
Home > core > simplifyModel.m
+ + + +

simplifyModel +

+ +

PURPOSE ^

+
simplifyModel
+ +

SYNOPSIS ^

+
function [reducedModel, deletedReactions, deletedMetabolites]=simplifyModel(model,deleteUnconstrained, deleteDuplicates, deleteZeroInterval, deleteInaccessible, deleteMinMax, groupLinear, constrainReversible, reservedRxns, suppressWarnings)
+ +

DESCRIPTION ^

+
 simplifyModel
+   Simplifies a model by deleting reactions/metabolites
+
+   model                 a model structure
+   deleteUnconstrained   delete metabolites marked as unconstrained (optional, default true)
+   deleteDuplicates      delete all but one of duplicate reactions (optional, default false)
+   deleteZeroInterval    delete reactions that are constrained to zero flux (optional, default false)
+   deleteInaccessible    delete dead end reactions (optional, default false)
+   deleteMinMax          delete reactions that cannot carry a flux by trying
+                         to minimize/maximize the flux through that
+                         reaction. May be time consuming (optional, default false)
+   groupLinear           group linearly dependent pathways (optional, default false)
+   constrainReversible   check if there are reversible reactions which can
+                         only carry flux in one direction, and if so
+                         constrain them to be irreversible. This tends to
+                         allow for more reactions grouped when using
+                         groupLinear (optional, default false)
+   reservedRxns          cell array with reaction IDs that are not allowed to be
+                         removed (optional)
+   suppressWarnings      true if warnings should be suppressed (optional,
+                         default false)
+
+   reducedModel          an updated model structure
+   deletedReactions      a cell array with the IDs of all deleted reactions
+   deletedMetabolites    a cell array with the IDs of all deleted
+                         metabolites
+
+   This function is for reducing the model size by removing
+   reactions and associated metabolites that cannot carry flux. It can also
+   be used for identifying different types of gaps.
+
+ Usage: [reducedModel, deletedReactions, deletedMetabolites]=simplifyModel(model,...
+           deleteUnconstrained, deleteDuplicates, deleteZeroInterval,...
+           deleteInaccessible, deleteMinMax, groupLinear,...
+           constrainReversible, reservedRxns, suppressWarnings)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function [reducedModel, deletedReactions, deletedMetabolites]=simplifyModel(model,...
+0002     deleteUnconstrained, deleteDuplicates, deleteZeroInterval, deleteInaccessible, deleteMinMax, groupLinear, constrainReversible, reservedRxns, suppressWarnings)
+0003 % simplifyModel
+0004 %   Simplifies a model by deleting reactions/metabolites
+0005 %
+0006 %   model                 a model structure
+0007 %   deleteUnconstrained   delete metabolites marked as unconstrained (optional, default true)
+0008 %   deleteDuplicates      delete all but one of duplicate reactions (optional, default false)
+0009 %   deleteZeroInterval    delete reactions that are constrained to zero flux (optional, default false)
+0010 %   deleteInaccessible    delete dead end reactions (optional, default false)
+0011 %   deleteMinMax          delete reactions that cannot carry a flux by trying
+0012 %                         to minimize/maximize the flux through that
+0013 %                         reaction. May be time consuming (optional, default false)
+0014 %   groupLinear           group linearly dependent pathways (optional, default false)
+0015 %   constrainReversible   check if there are reversible reactions which can
+0016 %                         only carry flux in one direction, and if so
+0017 %                         constrain them to be irreversible. This tends to
+0018 %                         allow for more reactions grouped when using
+0019 %                         groupLinear (optional, default false)
+0020 %   reservedRxns          cell array with reaction IDs that are not allowed to be
+0021 %                         removed (optional)
+0022 %   suppressWarnings      true if warnings should be suppressed (optional,
+0023 %                         default false)
+0024 %
+0025 %   reducedModel          an updated model structure
+0026 %   deletedReactions      a cell array with the IDs of all deleted reactions
+0027 %   deletedMetabolites    a cell array with the IDs of all deleted
+0028 %                         metabolites
+0029 %
+0030 %   This function is for reducing the model size by removing
+0031 %   reactions and associated metabolites that cannot carry flux. It can also
+0032 %   be used for identifying different types of gaps.
+0033 %
+0034 % Usage: [reducedModel, deletedReactions, deletedMetabolites]=simplifyModel(model,...
+0035 %           deleteUnconstrained, deleteDuplicates, deleteZeroInterval,...
+0036 %           deleteInaccessible, deleteMinMax, groupLinear,...
+0037 %           constrainReversible, reservedRxns, suppressWarnings)
+0038 
+0039 if nargin<2
+0040     deleteUnconstrained=true;
+0041 end
+0042 if nargin<3
+0043     deleteDuplicates=false;
+0044 end
+0045 if nargin<4
+0046     deleteZeroInterval=false;
+0047 end
+0048 if nargin<5
+0049     deleteInaccessible=false;
+0050 end
+0051 if nargin<6
+0052     deleteMinMax=false;
+0053 end
+0054 if nargin<7
+0055     groupLinear=false;
+0056 end
+0057 if nargin<8
+0058     constrainReversible=false;
+0059 end
+0060 if nargin<9
+0061     reservedRxns=[];
+0062 else
+0063     reservedRxns=convertCharArray(reservedRxns);
+0064 end
+0065 if nargin<10
+0066     suppressWarnings=false;
+0067 end
+0068 
+0069 reducedModel=model;
+0070 deletedReactions={};
+0071 deletedMetabolites={};
+0072 
+0073 if deleteUnconstrained==true
+0074     if isfield(reducedModel,'unconstrained')
+0075         %Remove unbalanced metabolites
+0076         deletedMetabolites=reducedModel.mets(reducedModel.unconstrained~=0);
+0077         reducedModel=removeMets(reducedModel,reducedModel.unconstrained~=0,false,false,false,true);
+0078         reducedModel=rmfield(reducedModel,'unconstrained');
+0079     end
+0080 end
+0081 
+0082 if deleteDuplicates==true
+0083     %Delete all but the last occurrence of duplicate reactions. The
+0084     %reactions must have the same bounds, reversibility, and objective
+0085     %coefficient to be regarded as duplicate
+0086     [reducedModel, rxnsToDelete, ~]=contractModel(reducedModel);
+0087     deletedReactions=[deletedReactions; rxnsToDelete];
+0088 end
+0089 
+0090 if deleteZeroInterval==true
+0091     %Find all reactions where both LB and UB are 0
+0092     zeroIntervalReactions=and(reducedModel.lb==0,reducedModel.ub==0);
+0093     
+0094     rxnsToDelete=setdiff(reducedModel.rxns(zeroIntervalReactions),reservedRxns);
+0095     deletedReactions=[deletedReactions; rxnsToDelete];
+0096     
+0097     %Remove reactions
+0098     reducedModel=removeReactions(reducedModel,rxnsToDelete);
+0099     
+0100     %Find metabolites that no longer are used and delete them
+0101     notInUse=sum(reducedModel.S~=0,2)==0;
+0102     deletedMetabolites=[deletedMetabolites;reducedModel.mets(notInUse)];
+0103     
+0104     %Remove metabolites
+0105     reducedModel=removeMets(reducedModel,notInUse);
+0106 end
+0107 
+0108 if deleteInaccessible==true
+0109     %Print a warning if exchange metabolites haven't been deleted yet. This
+0110     %often means that the only allowed products are the metabolites that
+0111     %are taken up be the system
+0112     if isfield(reducedModel,'unconstrained') && suppressWarnings==false
+0113         EM='Removing dead-end reactions before removing exchange metabolites';
+0114         dispEM(EM,false);
+0115     end
+0116     
+0117     while true
+0118         %Find all metabolites that are only reactants or only products.
+0119         %Delete those metabolites and reactions. This is done until no more
+0120         %such reactions are found
+0121         
+0122         %Construct a stoichiometric matrix where all reactions are written
+0123         %as reversible
+0124         
+0125         %Add fake exchange reactions if model.b~=0
+0126         in=any(reducedModel.b<0,2);
+0127         out=any(reducedModel.b>0,2);
+0128         I=speye(numel(reducedModel.mets));
+0129         revS=[reducedModel.S,reducedModel.S(:,reducedModel.lb<0)*-1 I(:,in) I(:,out)*-1];
+0130         
+0131         metUsage=sum(abs(revS')>0);
+0132         onlyProducts=sum(revS'>0) == metUsage;
+0133         onlyReactants=sum(revS'<0) == metUsage;
+0134         
+0135         %Also remove metabolites that only participate in one reversible
+0136         %reaction Don't remove the ones in one reversible reaction if is
+0137         %also has a non-zero coefficient in model.b
+0138         notInUse=onlyProducts | onlyReactants | (sum(abs(reducedModel.S')>0)<=1 & (~in & ~out)');
+0139         deletedRxn=false;
+0140         if any(notInUse)
+0141             %Find their corresponding reactions
+0142             rxnsNotInUse=sum(abs(reducedModel.S(notInUse,:))>0,1)>0;
+0143             rxnsToDelete=setdiff(reducedModel.rxns(rxnsNotInUse),reservedRxns);
+0144             deletedReactions=[deletedReactions; rxnsToDelete];
+0145             
+0146             %Remove reactions
+0147             reducedModel=removeReactions(reducedModel,rxnsToDelete);
+0148             
+0149             %Remove metabolites. Recalculate since it could be that some
+0150             %cannot be deleted due to reserved rxns
+0151             notInUse=sum(reducedModel.S~=0,2)==0;
+0152             deletedMetabolites=[deletedMetabolites; reducedModel.mets(notInUse)];
+0153             reducedModel=removeMets(reducedModel,notInUse);
+0154             
+0155             %It could happen that it just finds reserved reactions and gets
+0156             %stuck
+0157             if ~isempty(rxnsToDelete)
+0158                 deletedRxn=true;
+0159             end
+0160         else
+0161             break;
+0162         end
+0163         if deletedRxn==false
+0164             break;
+0165         end
+0166     end
+0167 end
+0168 
+0169 if deleteMinMax==true
+0170     %Get reactions that can't carry fluxes. This should be done
+0171     %algebraically if possible
+0172     I=~haveFlux(reducedModel);
+0173     
+0174     %Remove reactions
+0175     rxnsToDelete=setdiff(reducedModel.rxns(I),reservedRxns);
+0176     deletedReactions=[deletedReactions; rxnsToDelete];
+0177     reducedModel=removeReactions(reducedModel,rxnsToDelete);
+0178     
+0179     %Remove metabolites
+0180     notInUse=sum(reducedModel.S~=0,2)==0;
+0181     deletedMetabolites=[deletedMetabolites; reducedModel.mets(notInUse)];
+0182     reducedModel=removeMets(reducedModel,notInUse);
+0183 end
+0184 
+0185 if constrainReversible==true
+0186     revs=find(reducedModel.rev);
+0187     [I,J]=getAllowedBounds(reducedModel,revs);
+0188     
+0189     I=abs(I);
+0190     J=abs(J);
+0191     
+0192     %Get the "small" values
+0193     K=I<10^-10;
+0194     L=J<10^-10;
+0195     
+0196     %Keep the values where only one direction is zero (small)
+0197     I(K==L)=[];
+0198     J(K==L)=[];
+0199     revs(K==L)=[];
+0200     
+0201     %Change the reversibility of the remaining reactions
+0202     reducedModel.rev(revs(J>10^-10))=0; %Ignore reverse direction
+0203     reducedModel.lb(revs(J>10^-10))=0;
+0204     
+0205     toSwitch=revs(I>10^-10);
+0206     reducedModel.rev(toSwitch)=0; %Change directionality
+0207     reducedModel.ub(toSwitch)=reducedModel.lb(toSwitch)*-1;
+0208     reducedModel.lb(toSwitch)=0;
+0209     reducedModel.S(:,toSwitch)=reducedModel.S(:,toSwitch).*-1;
+0210     reducedModel.c(toSwitch)=reducedModel.c(toSwitch)*-1;
+0211 end
+0212 if groupLinear==true
+0213     if  suppressWarnings==false
+0214         fprintf('NOTE: You have chosen to group linear reactions. This option does not keep track of gene/reaction associations when reactions are merged. Deleting all gene information\n');
+0215     end
+0216     
+0217     reducedModel.genes={};
+0218     reducedModel.rxnGeneMat=sparse(numel(reducedModel.rxns),0);
+0219     reducedModel.grRules(:)={''};
+0220     
+0221     if isfield(reducedModel,'geneShortNames')
+0222         reducedModel.geneShortNames={};
+0223     end
+0224     if isfield(reducedModel,'proteins')
+0225         reducedModel.proteins={};
+0226     end
+0227     if isfield(reducedModel,'geneMiriams')
+0228         reducedModel.geneMiriams={};
+0229     end
+0230     if isfield(reducedModel,'geneComps')
+0231         reducedModel.geneComps=[];
+0232     end
+0233     
+0234     %Convert the model to irreversible
+0235     irrevModel=convertToIrrev(reducedModel);
+0236     
+0237     %Loop through and iteratively group linear reactions
+0238     while 1
+0239         %Get the banned reaction indexes. Note that the indexes will change
+0240         %in each iteration, but the names will not as they won't be merged
+0241         %with any other reaction
+0242         bannedIndexes=getIndexes(irrevModel,reservedRxns,'rxns');
+0243         
+0244         %Select all metabolites that are only present as reactants/products
+0245         %in one reaction
+0246         singleNegative=find(sum(irrevModel.S'<0)==1);
+0247         singlePositive=find(sum(irrevModel.S'>0)==1);
+0248         
+0249         %Retrieve the common metabolites
+0250         common=intersect(singleNegative,singlePositive);
+0251         
+0252         mergedSome=false;
+0253         
+0254         %Loop through each of them and see if the reactions should be
+0255         %merged
+0256         for i=1:numel(common)
+0257             involvedRxns=find(irrevModel.S(common(i),:));
+0258             
+0259             %Check so that one or both of the reactions haven't been merged
+0260             %already
+0261             if numel(involvedRxns)==2 && isempty(intersect(bannedIndexes,involvedRxns))
+0262                 %Calculate how many times the second reaction has to be
+0263                 %multiplied before being merged with the first
+0264                 stoichRatio=abs(irrevModel.S(common(i),involvedRxns(1))/irrevModel.S(common(i),involvedRxns(2)));
+0265                 
+0266                 %Add the second to the first
+0267                 irrevModel.S(:,involvedRxns(1))=irrevModel.S(:,involvedRxns(1))+irrevModel.S(:,involvedRxns(2))*stoichRatio;
+0268                 
+0269                 %Clear the second reaction
+0270                 irrevModel.S(:,involvedRxns(2))=0;
+0271                 
+0272                 %This is to prevent numerical issues. It should be 0
+0273                 %already
+0274                 irrevModel.S(common(i),involvedRxns(1))=0;
+0275                 
+0276                 %At this point the second reaction is certain to be deleted
+0277                 %in a later step and can therefore be ignored
+0278                 
+0279                 %Recalculate the bounds for the new reaction. This can be
+0280                 %problematic since the scale of the bounds may change
+0281                 %dramatically. Let the most constraining reaction determine
+0282                 %the new bound
+0283                 lb1=irrevModel.lb(involvedRxns(1));
+0284                 lb2=irrevModel.lb(involvedRxns(2));
+0285                 ub1=irrevModel.ub(involvedRxns(1));
+0286                 ub2=irrevModel.ub(involvedRxns(2));
+0287                 
+0288                 if lb2~=-inf
+0289                     irrevModel.lb(involvedRxns(1))=max(lb1,lb2/stoichRatio);
+0290                 end
+0291                 if ub2~=inf
+0292                     irrevModel.ub(involvedRxns(1))=min(ub1,ub2/stoichRatio);
+0293                 end
+0294                 
+0295                 %Then recalculate the objective coefficient. The resulting
+0296                 %coefficient is the weighted sum of the previous
+0297                 irrevModel.c(involvedRxns(1))=irrevModel.c(involvedRxns(1))+irrevModel.c(involvedRxns(2))*stoichRatio;
+0298                 
+0299                 %Iterate again
+0300                 mergedSome=true;
+0301             end
+0302         end
+0303         
+0304         %All possible reactions merged
+0305         if mergedSome==false
+0306             break;
+0307         end
+0308         
+0309         %Now delete all reactions that involve no metabolites
+0310         I=find(sum(irrevModel.S~=0)==0);
+0311         
+0312         %Remove reactions
+0313         irrevModel=removeReactions(irrevModel,I);
+0314         
+0315         %Remove metabolites
+0316         notInUse=sum(irrevModel.S~=0,2)==0;
+0317         irrevModel=removeMets(irrevModel,notInUse);
+0318     end
+0319     
+0320     reducedModel=irrevModel;
+0321 end
+0322 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/sortModel.html b/doc/core/sortModel.html new file mode 100644 index 000000000..b14269dfc --- /dev/null +++ b/doc/core/sortModel.html @@ -0,0 +1,249 @@ + + + + Description of sortModel + + + + + + + + + +
Home > core > sortModel.m
+ + + +

sortModel +

+ +

PURPOSE ^

+
sortModel
+ +

SYNOPSIS ^

+
function model=sortModel(model,sortReversible,sortMetName,sortReactionOrder)
+ +

DESCRIPTION ^

+
 sortModel
+   Sorts a model based on metabolite names and compartments
+
+   model             a model structure
+   sortReversible    sorts the reversible reactions so the the metabolite
+                     that is first in lexiographical order is a reactant
+                     (optional, default true)
+   sortMetName       sort the metabolite names in the equation, also uses
+                     compartment abbreviation (optional, default false)
+   sortReactionOrder sorts the reaction order within each subsystem so that
+                     reactions consuming some metabolite comes efter
+                     reactions producing it. This overrides the
+                     sortReversible option and reactions are sorted so that
+                     the production direction matches the consumption
+                     direction (optional, default false)
+
+   model             an updated model structure
+
+ Usage: model=sortModel(model,sortReversible,sortMetName,sortReactionOrder)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function model=sortModel(model,sortReversible,sortMetName,sortReactionOrder)
+0002 % sortModel
+0003 %   Sorts a model based on metabolite names and compartments
+0004 %
+0005 %   model             a model structure
+0006 %   sortReversible    sorts the reversible reactions so the the metabolite
+0007 %                     that is first in lexiographical order is a reactant
+0008 %                     (optional, default true)
+0009 %   sortMetName       sort the metabolite names in the equation, also uses
+0010 %                     compartment abbreviation (optional, default false)
+0011 %   sortReactionOrder sorts the reaction order within each subsystem so that
+0012 %                     reactions consuming some metabolite comes efter
+0013 %                     reactions producing it. This overrides the
+0014 %                     sortReversible option and reactions are sorted so that
+0015 %                     the production direction matches the consumption
+0016 %                     direction (optional, default false)
+0017 %
+0018 %   model             an updated model structure
+0019 %
+0020 % Usage: model=sortModel(model,sortReversible,sortMetName,sortReactionOrder)
+0021 
+0022 if nargin<2
+0023     sortReversible=true;
+0024 end
+0025 if nargin<3
+0026     sortMetName=false;
+0027 end
+0028 if nargin<4
+0029     sortReactionOrder=false;
+0030 end
+0031 
+0032 if sortMetName==true
+0033     %Assuming that metComps are the indexes. Should be changed at one point
+0034     [~, metIndexes]=sort(strcat(model.metNames,'[',model.comps(model.metComps),']'));
+0035     model=permuteModel(model,metIndexes,'mets');
+0036 end
+0037 
+0038 if sortReversible==true && sortReactionOrder==false
+0039     %Get all reversible reactions
+0040     revIndexes=find(model.rev);
+0041     
+0042     %Loop through them
+0043     for i=1:numel(revIndexes)
+0044         %Create a cell array with all the metabolite names
+0045         mets=find(model.S(:,revIndexes(i)));
+0046         metNames=strcat(model.metNames(mets),model.comps(model.metComps(mets)));
+0047         
+0048         if iscellstr(metNames)
+0049             [~, indexes]=sort(metNames);
+0050             
+0051             if model.S(mets(indexes(1)),revIndexes(i))>0
+0052                 model.S(:,revIndexes(i))=model.S(:,revIndexes(i))*-1;
+0053             end
+0054         end
+0055     end
+0056 end
+0057 
+0058 if sortReactionOrder==true
+0059     %Check if the model has sub-systems, otherwise throw an error
+0060     if ~isfield(model,'subSystems')
+0061         EM='The model must contain a subSystems field in order to sort reaction order';
+0062         dispEM(EM);
+0063     end
+0064     
+0065     subsystemsUnique='';
+0066     subsystemsConcatenated='';
+0067     for i=1:numel(model.subSystems)
+0068         if ~iscell(model.subSystems{i})
+0069             model.subSystems{i} = {model.subSystems{i}};
+0070         end    
+0071         subsystemsConcatenated{i,1}=strjoin(model.subSystems{i,1},';');
+0072         if ~isempty(model.subSystems{i,1})
+0073             for j=1:numel(model.subSystems{i,1})
+0074                 subsystemsUnique{numel(subsystemsUnique)+1,1}=model.subSystems{i,1}{1,j};
+0075             end
+0076         end
+0077     end
+0078     subsystemsUnique=unique(subsystemsUnique);
+0079     for i=1:numel(subsystemsUnique)
+0080         %Get all reactions for that subsystem
+0081         rxns=find(~cellfun(@isempty,regexp(subsystemsConcatenated,subsystemsUnique(i))));
+0082         
+0083         %Temporarily ignore large subsystems because of inefficient
+0084         %implementation
+0085         if numel(rxns)<2 || numel(rxns)>250
+0086             continue;
+0087         end
+0088         
+0089         nRxns=numel(rxns);
+0090         revRxns=rxns(model.rev(rxns)~=0);
+0091         
+0092         %This variable will hold the current reversibility directions of
+0093         %the reversible reactions. 1 means the same direction as in the
+0094         %original model and -1 means the opposite direction.
+0095         oldRev=ones(numel(revRxns),1);
+0096         
+0097         %The problem could probably be solved analytically but a simple
+0098         %random method is implemented here instead. Two reactions are
+0099         %chosen randomly and their positions are switched. A score is
+0100         %calculated based on the number of metabolites that are produced
+0101         %before they are consumed. If the perturbed model has a better or
+0102         %equal score than the original the reaction order is switched. If
+0103         %no increase in score has been seen after 1000*rxnsInSubsystem then
+0104         %the optimization is terminated
+0105         
+0106         rxnOrder=1:nRxns;
+0107         oldScore=-inf;
+0108         counter=0;
+0109         firstIter=true;
+0110         while 1==1
+0111             counter=counter+1;
+0112             if counter==100*nRxns
+0113                 break;
+0114             end
+0115             
+0116             newRxnOrder=rxnOrder;
+0117             rev=oldRev;
+0118             
+0119             if firstIter==false
+0120                 y=randperm(nRxns,2);
+0121                 
+0122                 %Switch the order
+0123                 newRxnOrder(y(1))=rxnOrder(y(2));
+0124                 newRxnOrder(y(2))=rxnOrder(y(1));
+0125                 
+0126                 %With a 50% chance, also switch the reversibility of one of
+0127                 %the reactions
+0128                 if rand()>0.5 && numel(rev)>1
+0129                     n=randperm(numel(rev),1);
+0130                     rev(n)=rev(n)*-1;
+0131                 end
+0132             end
+0133             firstIter=false;
+0134             
+0135             tempS=model.S;
+0136             
+0137             %Switch the directionalities
+0138             for j=1:numel(rev)
+0139                 if rev(j)==-1
+0140                     tempS(:,revRxns(j))=tempS(:,revRxns(j)).*-1;
+0141                 end
+0142             end
+0143             
+0144             %Get the metabolites that are involved and when they are
+0145             %produced/consumed
+0146             s=tempS(:,newRxnOrder);
+0147             
+0148             %Remove mets that aren't used in both directions
+0149             s=s(any(s,2),:);
+0150             
+0151             %Add so that all mets are produced and consumed in the end
+0152             s=[s ones(size(s,1),1) ones(size(s,1),1)*-1];
+0153             
+0154             %For each metabolite, find the reaction where it's first
+0155             %produced and the reaction where it's first consumed
+0156             s1=s>0;
+0157             r1=arrayfun(@(x) find(s1(x,:),1,'first'),1:size(s1,1));
+0158             s2=s<0;
+0159             r2=arrayfun(@(x) find(s2(x,:),1,'first'),1:size(s2,1));
+0160             
+0161             score=sum(r1<r2);
+0162             
+0163             if score>=oldScore
+0164                 if score>oldScore
+0165                     counter=0;
+0166                 end
+0167                 oldScore=score;
+0168                 oldRev=rev;
+0169                 rxnOrder=newRxnOrder;
+0170             end
+0171         end
+0172         
+0173         %Update the model for this subsystem
+0174         for j=1:numel(oldRev)
+0175             if oldRev(j)==-1
+0176                 model.S(:,revRxns(j))=model.S(:,revRxns(j)).*-1;
+0177             end
+0178         end
+0179         order=1:numel(model.rxns);
+0180         order(rxns)=rxns(rxnOrder);
+0181         model=permuteModel(model, order, 'rxns');
+0182     end
+0183 end
+0184 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/core/standardizeGrRules.html b/doc/core/standardizeGrRules.html new file mode 100644 index 000000000..b58d66bd5 --- /dev/null +++ b/doc/core/standardizeGrRules.html @@ -0,0 +1,236 @@ + + + + Description of standardizeGrRules + + + + + + + + + +
Home > core > standardizeGrRules.m
+ + + +

standardizeGrRules +

+ +

PURPOSE ^

+
standardizeGrRules
+ +

SYNOPSIS ^

+
function [grRules,rxnGeneMat,indexes2check] = standardizeGrRules(model,embedded)
+ +

DESCRIPTION ^

+
 standardizeGrRules
+   Standardizes gene-rxn rules in a model according to the following
+       - No overall containing brackets
+       - Just enzyme complexes are enclosed into brackets
+       - ' and ' & ' or ' strings are strictly set to lowercases
+
+   A rxnGeneMat matrix consistent with the standardized grRules is created.
+
+   model        a model structure
+   embedded     true if this function is called inside of another 
+                RAVEN function (optional, default false)
+
+   grRules      [nRxns x 1] cell array with the standardized grRules
+   rxnGeneMat   [nRxns x nGenes]Sparse matrix consitent with the
+                standardized grRules
+   
+   If this function is going to be used in a model reconstruction or
+   modification pipeline it is recommended to run this function just
+   at the beginning of the process.
+
+ Usage: [grRules,rxnGeneMat,indexes2check]=standardizeGrRules(model,embedded)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 function [grRules,rxnGeneMat,indexes2check] = standardizeGrRules(model,embedded)
+0002 % standardizeGrRules
+0003 %   Standardizes gene-rxn rules in a model according to the following
+0004 %       - No overall containing brackets
+0005 %       - Just enzyme complexes are enclosed into brackets
+0006 %       - ' and ' & ' or ' strings are strictly set to lowercases
+0007 %
+0008 %   A rxnGeneMat matrix consistent with the standardized grRules is created.
+0009 %
+0010 %   model        a model structure
+0011 %   embedded     true if this function is called inside of another
+0012 %                RAVEN function (optional, default false)
+0013 %
+0014 %   grRules      [nRxns x 1] cell array with the standardized grRules
+0015 %   rxnGeneMat   [nRxns x nGenes]Sparse matrix consitent with the
+0016 %                standardized grRules
+0017 %
+0018 %   If this function is going to be used in a model reconstruction or
+0019 %   modification pipeline it is recommended to run this function just
+0020 %   at the beginning of the process.
+0021 %
+0022 % Usage: [grRules,rxnGeneMat,indexes2check]=standardizeGrRules(model,embedded)
+0023 
+0024 %Preallocate fields
+0025 n          = length(model.rxns);
+0026 [g,~]      = size(model.genes);
+0027 rxnGeneMat = sparse(n,g);
+0028 grRules    = cell(n,1);
+0029 genes      = model.genes;
+0030 if nargin<2
+0031     embedded = false;
+0032 end
+0033 
+0034 if isfield(model,'grRules')
+0035     originalGrRules=model.grRules; 
+0036     originalGrRules=grRulesPreparation(originalGrRules);
+0037     %Search for potential logical errors in the grRules field
+0038     indexes2check = findPotentialErrors(originalGrRules,embedded,model);
+0039     
+0040     for i=1:length(originalGrRules)
+0041         originalSTR = originalGrRules{i};
+0042         grRules{i,:}  = originalSTR;
+0043         %Non-empty grRules are splitted in all their different isoenzymes
+0044         genesSets   = getSimpleGeneSets(originalSTR);
+0045         rxnGeneMat  = modifyRxnGeneMat(genesSets,genes,rxnGeneMat,i);
+0046         %standardize the non-conflicting grRules
+0047         if ~ismember(i,indexes2check)
+0048             newSTR = [];
+0049             if ~isempty(genesSets)
+0050                 %For each simple genes set in the rule
+0051                 for j=1:length(genesSets)
+0052                     simpleSet  = genesSets{j};
+0053                     %Enclose simpleSet in brackets
+0054                     if length(genesSets)>1
+0055                         if ~isempty(strfind(simpleSet,' and '))
+0056                             simpleSet = horzcat('(',simpleSet,')');
+0057                         end
+0058                     end
+0059                     %Separate genesSets in the substring (in case of
+0060                     %isoenzymes)
+0061                     if j<length(genesSets)
+0062                         newSTR = [newSTR, simpleSet, ' or '];
+0063                         %Add the last simpleSet
+0064                     else
+0065                         newSTR = [newSTR, simpleSet];
+0066                     end
+0067                 end
+0068                 %Update grRule
+0069                 grRules{i} = char(newSTR);
+0070             end
+0071         end
+0072     end
+0073 else
+0074     error('The model does not have a grRules field.')
+0075 end
+0076 
+0077 end
+0078 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+0079 %Function that gets a cell array with all the simple geneSets in a given
+0080 %grRule string
+0081 function genesSets = getSimpleGeneSets(originalSTR)
+0082 genesSets  = [];
+0083 %If gene rule is not empty split in all its different isoenzymes
+0084 if ~isempty(originalSTR)
+0085     originalSTR = strtrim(originalSTR);
+0086     %Remove all brackets
+0087     originalSTR = strrep(originalSTR,'(','');
+0088     originalSTR = strrep(originalSTR,')','');
+0089     %Split all the different genesSets
+0090     genesSets  = transpose(strsplit(originalSTR,' or '));
+0091 end
+0092 end
+0093 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+0094 %Function that gets a cell array of simple genes sets (single genes or
+0095 %enzyme complexes) associated with the i-th reaction and modifies the
+0096 %correspondent row in the rxnGeneMat accordingly.
+0097 function rxnGeneMat = modifyRxnGeneMat(genesSets,modelGenes,rxnGeneMat,i)
+0098 
+0099 if ~isempty(genesSets)
+0100     for j=1:length(genesSets)
+0101         simpleSet  = genesSets{j};
+0102         %        rxnGeneMat = modifyRxnGeneMat(simpleSet,model.genes,rxnGeneMat,i);
+0103         %Get individual genes
+0104         STR   = strrep(simpleSet,') and (',' and ');
+0105         genes = strsplit(STR,' ');
+0106         for k=1:length(genes)
+0107             if ~strcmpi(genes(k),' and ')
+0108                 %Get gene index
+0109                 genePos = find(strcmpi(modelGenes,genes(k)));
+0110                 if ~isempty(genePos)
+0111                     rxnGeneMat(i,genePos) = 1;
+0112                     %else
+0113                     %In this case the gene should be added to the
+0114                     %genes field (and to all of its dependencies)
+0115                 end
+0116             end
+0117         end
+0118     end
+0119 end
+0120 end
+0121 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+0122 %Function that gets the model field grRules and returns the indexes of the
+0123 %rules in which the pattern ") and (" is present.
+0124 function indexes2check = findPotentialErrors(grRules,embedded,model)
+0125 indxs_l       = find(~cellfun(@isempty,strfind(grRules,') and (')));
+0126 indxs_l_L     = find(~cellfun(@isempty,strfind(grRules,') and')));
+0127 indxs_l_R     = find(~cellfun(@isempty,strfind(grRules,'and (')));
+0128 indexes2check = vertcat(indxs_l,indxs_l_L,indxs_l_R);
+0129 indexes2check = unique(indexes2check);
+0130 
+0131 if ~isempty(indexes2check)
+0132     
+0133     if ~embedded
+0134         STR = 'Potentially problematic ") AND (", ") AND" or "AND ("relat';
+0135         STR = [STR,'ionships found in\n\n'];
+0136         for i=1:length(indexes2check)
+0137             index = indexes2check(i);
+0138             STR = [STR '  - grRule #' model.rxns{index} ': ' grRules{index} '\n'];
+0139         end
+0140         STR = [STR,'\n This kind of relationships should only be present '];
+0141         STR = [STR,'in  reactions catalysed by complexes of isoenzymes e'];
+0142         STR = [STR,'.g.\n\n  - (G1 or G2) and (G3 or G4)\n\n For these c'];
+0143         STR = [STR,'ases modify the grRules manually, writing all the po'];
+0144         STR = [STR,'ssible combinations e.g.\n\n  - (G1 and G3) or (G1 a'];
+0145         STR = [STR,'nd G4) or (G2 and G3) or (G2 and G4)\n\n For other c'];
+0146         STR = [STR,'ases modify the correspondent grRules avoiding:\n\n '];
+0147         STR = [STR,' 1) Overall container brackets, e.g.\n        "(G1 a'];
+0148         STR = [STR,'nd G2)" should be "G1 and G2"\n\n  2) Single unit en'];
+0149         STR = [STR,'zymes enclosed into brackets, e.g.\n        "(G1)" s'];
+0150         STR = [STR,'hould be "G1"\n\n  3) The use of uppercases for logi'];
+0151         STR = [STR,'cal operators, e.g.\n        "G1 OR G2" should be "G'];
+0152         STR = [STR,'1 or G2"\n\n  4) Unbalanced brackets, e.g.\n        '];
+0153         STR = [STR,'"((G1 and G2) or G3" should be "(G1 and G2) or G3"\n'];
+0154         warning(sprintf(STR))
+0155     end
+0156 end
+0157 end
+0158 
+0159 function grRules = grRulesPreparation(grRules)
+0160 %Remove unnecessary blanks
+0161 grRules=strrep(grRules,'  ',' ');
+0162 grRules=strrep(grRules,'( ','(');
+0163 grRules=strrep(grRules,' )',')');
+0164 % Make sure that AND and OR strings are in lowercase
+0165 grRules=strrep(grRules,' AND ',' and ');
+0166 grRules=strrep(grRules,' OR ',' or ');
+0167 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/demoicon.gif b/doc/demoicon.gif new file mode 100644 index 0000000000000000000000000000000000000000..c89e7acbc2a74f36f35d2ba23cdd095366563205 GIT binary patch literal 214 zcmZ?wbhEHb6krfwIKlt||NsBz;1LK4_4@xG$Oe)@|Nlq*|KIZe|D6B-*Z%*1?f?IK z|Nno#cAjDHE{X4-EuTMj+Ph8S`+Kir`@EcN1dbivDF(pUKia5*{N xtO-?WJ(Rf1$C7KR)AZ0H0j(>SR=H$6kJ)6-DZGJ)<+b45x|97Z4cdwf)&TUlSJMCh literal 0 HcmV?d00001 diff --git a/doc/down.png b/doc/down.png new file mode 100644 index 0000000000000000000000000000000000000000..d41104a26f3d09deda6ab54281affd82c981abb1 GIT binary patch literal 133 zcmeAS@N?(olHy`uVBq!ia0vp^{2gTe~DWM4fiX0)Z literal 0 HcmV?d00001 diff --git a/doc/doxysearch.php b/doc/doxysearch.php new file mode 100644 index 000000000..36112a426 --- /dev/null +++ b/doc/doxysearch.php @@ -0,0 +1,329 @@ +$word, + "match"=>$w, + "index"=>$statIdx, + "full"=>strlen($w)==strlen($word), + "docs"=>array() + ); + } + $w = readString($file); + } + $totalFreq=0; + for ($count=$start;$count$idx,"freq"=>$freq,"rank"=>0.0); + $totalFreq+=$freq; + if ($statInfo["full"]) $totalfreq+=$freq; + } + // read name an url info for the doc + for ($i=0;$i<$numDocs;$i++) + { + fseek($file,$docInfo[$i]["idx"]); + $docInfo[$i]["name"]=readString($file); + $docInfo[$i]["url"]=readString($file); + } + $statInfo["docs"]=$docInfo; + } + for ($count=$start;$count$key, + "name"=>$di["name"], + "rank"=>$rank + ); + } + $docs[$key]["words"][] = array( + "word"=>$wordInfo["word"], + "match"=>$wordInfo["match"], + "freq"=>$di["freq"] + ); + } + } + return $docs; +} + +function normalize_ranking(&$docs) +{ + $maxRank = 0.0000001; + // compute maximal rank + foreach ($docs as $doc) + { + if ($doc["rank"]>$maxRank) + { + $maxRank=$doc["rank"]; + } + } + reset($docs); + // normalize rankings + while (list ($key, $val) = each ($docs)) + { + $docs[$key]["rank"]*=100/$maxRank; + } +} + +function filter_results($docs,&$requiredWords,&$forbiddenWords) +{ + $filteredDocs=array(); + while (list ($key, $val) = each ($docs)) + { + $words = &$docs[$key]["words"]; + $copy=1; // copy entry by default + if (sizeof($requiredWords)>0) + { + foreach ($requiredWords as $reqWord) + { + $found=0; + foreach ($words as $wordInfo) + { + $found = $wordInfo["word"]==$reqWord; + if ($found) break; + } + if (!$found) + { + $copy=0; // document contains none of the required words + break; + } + } + } + if (sizeof($forbiddenWords)>0) + { + foreach ($words as $wordInfo) + { + if (in_array($wordInfo["word"],$forbiddenWords)) + { + $copy=0; // document contains a forbidden word + break; + } + } + } + if ($copy) $filteredDocs[$key]=$docs[$key]; + } + return $filteredDocs; +} + +function compare_rank($a,$b) +{ + return ($a["rank"]>$b["rank"]) ? -1 : 1; +} + +function sort_results($docs,&$sorted) +{ + $sorted = $docs; + usort($sorted,"compare_rank"); + return $sorted; +} + +function report_results(&$docs) +{ + echo "\n"; + echo " \n"; + echo " \n"; + echo " \n"; + $numDocs = sizeof($docs); + if ($numDocs==0) + { + echo " \n"; + echo " \n"; + echo " \n"; + } + else + { + echo " \n"; + echo " \n"; + echo " \n"; + $num=1; + foreach ($docs as $doc) + { + echo " \n"; + echo " "; + echo "\n"; + echo " \n"; + echo " \n"; + echo " \n"; + $num++; + } + } + echo "

Search Results

".matches_text(0)."
".matches_text($numDocs); + echo "\n"; + echo "
$num.".$doc["name"]."
Matches: "; + foreach ($doc["words"] as $wordInfo) + { + $word = $wordInfo["word"]; + $matchRight = substr($wordInfo["match"],strlen($word)); + echo "$word$matchRight(".$wordInfo["freq"].") "; + } + echo "
\n"; +} + +function matches_text($num) +{ + if ($num==0) + { + return 'Sorry, no documents matching your query.'; + } + else if ($num==1) + { + return 'Found 1 document matching your query.'; + } + else // $num>1 + { + return 'Found '.$num.' documents matching your query. Showing best matches first.'; + } +} + +function main($idxfile) +{ + if(strcmp('4.1.0', phpversion()) > 0) + { + die("Error: PHP version 4.1.0 or above required!"); + } + if (!($file=fopen($idxfile,"rb"))) + { + die("Error: Search index file could NOT be opened!"); + } + if (readHeader($file)!="DOXS") + { + die("Error: Header of index file is invalid!"); + } + $query=""; + if (array_key_exists("query", $_GET)) + { + $query=$_GET["query"]; + } + $results = array(); + $requiredWords = array(); + $forbiddenWords = array(); + $foundWords = array(); + $word=strtolower(strtok($query," ")); + while ($word) // for each word in the search query + { + if (($word{0}=='+')) { $word=substr($word,1); $requiredWords[]=$word; } + if (($word{0}=='-')) { $word=substr($word,1); $forbiddenWords[]=$word; } + if (!in_array($word,$foundWords)) + { + $foundWords[]=$word; + search($file,$word,$results); + } + $word=strtolower(strtok(" ")); + } + $docs = array(); + combine_results($results,$docs); + // filter out documents with forbidden word or that do not contain + // required words + $filteredDocs = filter_results($docs,$requiredWords,$forbiddenWords); + // normalize rankings so they are in the range [0-100] + normalize_ranking($filteredDocs); + // sort the results based on rank + $sorted = array(); + sort_results($filteredDocs,$sorted); + // report results to the user + report_results($sorted); + fclose($file); +} + +?> diff --git a/doc/external/combineMetaCycKEGGModels.html b/doc/external/combineMetaCycKEGGModels.html new file mode 100644 index 000000000..c9cc74ad1 --- /dev/null +++ b/doc/external/combineMetaCycKEGGModels.html @@ -0,0 +1,380 @@ + + + + Description of combineMetaCycKEGGModels + + + + + + + + + +
Home > external > combineMetaCycKEGGModels.m
+ + + +

combineMetaCycKEGGModels +

+ +

PURPOSE ^

+
combineMetaCycKEGGModels
+ +

SYNOPSIS ^

+
function model=combineMetaCycKEGGModels(metacycModel,keggModel)
+ +

DESCRIPTION ^

+
 combineMetaCycKEGGModels
+    Combine MetaCyc and KEGG draft models into one model structure.
+
+    Input:
+    metacycModel    the reconstructed model from MetaCyc
+    keggModel       the reconstructed model from KEGG
+
+    Output:
+    model           a model structure generated by integrating information
+                   from draft models reconstructed using MetaCyc and KEGG
+                   databases. The 'rxnFrom/metFrom/geneFrom' fields are
+                   included to indicate the source.
+
+    Usage: model=combineMetaCycKEGGModels(metacycModel,keggModel)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function model=combineMetaCycKEGGModels(metacycModel,keggModel)
+0002 % combineMetaCycKEGGModels
+0003 %    Combine MetaCyc and KEGG draft models into one model structure.
+0004 %
+0005 %    Input:
+0006 %    metacycModel    the reconstructed model from MetaCyc
+0007 %    keggModel       the reconstructed model from KEGG
+0008 %
+0009 %    Output:
+0010 %    model           a model structure generated by integrating information
+0011 %                   from draft models reconstructed using MetaCyc and KEGG
+0012 %                   databases. The 'rxnFrom/metFrom/geneFrom' fields are
+0013 %                   included to indicate the source.
+0014 %
+0015 %    Usage: model=combineMetaCycKEGGModels(metacycModel,keggModel)
+0016 
+0017 %Just return the model
+0018 if nargin<2
+0019     disp('Missing input model');
+0020     return;
+0021 end
+0022 
+0023 %Add MetaCyc model as template
+0024 model=metacycModel;
+0025 model.id='COMBINED';
+0026 model.name='Combined model from MetaCyc and KEGG draft models';
+0027 
+0028 %Use MetaCyc model as template
+0029 model.rxnFrom=cell(numel(model.rxns),1);
+0030 model.rxnFrom(:)={'MetaCyc'};
+0031 model.metFrom=cell(numel(model.mets),1);
+0032 model.metFrom(:)={'MetaCyc'};
+0033 model.geneFrom=cell(numel(model.genes),1);
+0034 model.geneFrom(:)={'MetaCyc'};
+0035 model.grRulesKEGG=cell(numel(model.rxns),1);
+0036 model.grRulesKEGG(:)={''};
+0037 
+0038 %Remove the S and rxnGeneMat matrix
+0039 if isfield(model,'S')
+0040     model=rmfield(model,'S');
+0041 end
+0042 if isfield(model,'rxnGeneMat')
+0043     model=rmfield(model,'rxnGeneMat');
+0044 end
+0045 
+0046 %Arrange the genes related fields
+0047 
+0048 %Identify the shared genes between KEGG and MetaCyc
+0049 sharedGenes=intersect(keggModel.genes,model.genes);
+0050 [~, b]=ismember(sharedGenes,model.genes);
+0051 model.geneFrom(b)={'Both'};
+0052 
+0053 %Add unique genes from KEGG and update geneFrom
+0054 C=setdiff(keggModel.genes,model.genes);
+0055 model.genes=[model.genes;C];
+0056 geneFrom=cell(numel(C),1);
+0057 geneFrom(:)={'KEGG'};
+0058 model.geneFrom=[model.geneFrom;geneFrom];
+0059 
+0060 %Prepare for matching grRules
+0061 if isfield(keggModel,'grRules')
+0062     keggModel.grRules=strrep(keggModel.grRules,'(','');
+0063     keggModel.grRules=strrep(keggModel.grRules,')','');
+0064 end
+0065 
+0066 %Replace rxns in KEGG model with the corresponding ones in MetaCyc by
+0067 %updating values rxns field to MetaCyc version whenever possible
+0068 
+0069 %Collect the ones found in MetaCyc as mappedRxns
+0070 mappedRxns=[];
+0071 rxnsToMove=[];
+0072 grRulesToMove={}; %Storing the grRules to be moved to MetaCyc model
+0073 
+0074 %Read in dbLinks, note that linkMetaCycKEGGRxns need to be run in advance
+0075 load('metaCycRxns.mat');
+0076 num=0;
+0077 numToMove=0;
+0078 %Loop through the KEGG model and replace the rxn id from KEGG to MetaCyc
+0079 %version
+0080 for i=1:numel(keggModel.rxns)
+0081     [~, b]=ismember(rxnLinks.kegg,keggModel.rxns{i});
+0082     I=find(b);
+0083     
+0084     if numel(I)==1
+0085         %Find out the corresponding MetaCyc reactions
+0086         num=num+1;
+0087         %Record the mapped rxn index in KEGG model and remove them later
+0088         mappedRxns=[mappedRxns,i];
+0089         %keggModel.rxns{i}=rxnLinks.metacyc{I(1)};
+0090         
+0091         [c, d]=ismember(rxnLinks.metacyc{I(1)},model.rxns);
+0092         if c
+0093             model.rxnFrom{d}='Both';
+0094             %Combine the grRule info Check if KEGG grRules equals or a
+0095             %subset of MetaCyc grRules If not, save the KEGG grRules to a
+0096             %new field grRulesKEGG for manual curation
+0097             k=strfind(model.grRules{d},keggModel.grRules{i});
+0098             if isempty(k)
+0099                 if isempty(model.grRulesKEGG{d})
+0100                     model.grRulesKEGG{d}=keggModel.grRules{i};
+0101                 else
+0102                     model.grRulesKEGG{d}=strcat(model.grRulesKEGG{d},{' or '},keggModel.grRules{i});
+0103                 end
+0104             end
+0105         else
+0106             %For the KEGG rxns have MetaCyc version but not in MetaCyc
+0107             %draft model
+0108             [~, y]=ismember(rxnLinks.metacyc{I(1)},metaCycRxns.rxns);
+0109             
+0110             %Check if this reaction is repitetive and save the grRules
+0111             [Repeat, Index]=ismember(y,rxnsToMove);
+0112             if ~Repeat
+0113                 rxnsToMove=[rxnsToMove;y];  %Record rxns to be moved from KEGG to MetaCyc model
+0114                 if isempty(keggModel.grRules{i})
+0115                     %Rxns may have empty grRules (e.g. spontaneous) that
+0116                     %are identified and added back here
+0117                     grRulesToMove=[grRulesToMove;{''}];
+0118                 else
+0119                     grRulesToMove=[grRulesToMove;keggModel.grRules{i}];
+0120                 end
+0121                 numToMove=numToMove+1;
+0122             else
+0123                 %If this reaction has been recorded, append the grRules if
+0124                 %it is different
+0125                 k=strfind(grRulesToMove{Index},keggModel.grRules{i});
+0126                 if isempty(k)
+0127                     grRulesToMove{Index}=strcat(grRulesToMove{Index},{' or '},keggModel.grRules{i});
+0128                 end
+0129             end
+0130         end
+0131     else
+0132         %Here are the case of one KEGG rxn id link to several MetaCyc ids
+0133         %for j=2:numel(I) Ignore this issue for now, and resolve it later,
+0134         %because it never happened This case can be solved by adding above
+0135         %section into a loop below disp(I(j)); end
+0136     end
+0137 end
+0138 fprintf('NOTE: A total of %d reactions in the KEGG model were mapped to MetaCyc.\n',num);
+0139 fprintf('NOTE: %d reactions already in MetaCyc model, %d will be combined.\n',num-numToMove,numToMove);
+0140 
+0141 %Append mapped MetaCyc rxns in KEGG model that are absent from MetaCyc
+0142 %model
+0143 rxnFrom=cell(numel(rxnsToMove),1);
+0144 rxnFrom(:)={'KEGG'};
+0145 model.rxnFrom=[model.rxnFrom;rxnFrom];
+0146 model.rxns=[model.rxns;metaCycRxns.rxns(rxnsToMove)];
+0147 
+0148 rxnNames=metaCycRxns.rxnNames(rxnsToMove);
+0149 %Replace rxnNames with those from metaCycEnzymes
+0150 load('metaCycEnzymes.mat');
+0151 for i=1:numel(rxnsToMove)
+0152     [a, b]=ismember(metaCycRxns.rxns{rxnsToMove(i)},metaCycEnzymes.rxns);
+0153     if a
+0154         rxnNames{i}=metaCycEnzymes.rxnNames{b};
+0155     end
+0156 end
+0157 model.rxnNames=[model.rxnNames;rxnNames];
+0158 
+0159 model.eccodes=[model.eccodes;metaCycRxns.eccodes(rxnsToMove)];
+0160 model.subSystems=[model.subSystems;metaCycRxns.subSystems(rxnsToMove)];
+0161 model.rxnMiriams=[model.rxnMiriams;metaCycRxns.rxnMiriams(rxnsToMove)];
+0162 model.rxnReferences=[model.rxnReferences;metaCycRxns.rxnReferences(rxnsToMove)];
+0163 model.rev=[model.rev;metaCycRxns.rev(rxnsToMove)];
+0164 model.equations=[model.equations;metaCycRxns.equations(rxnsToMove)];
+0165 model.lb=[model.lb;metaCycRxns.lb(rxnsToMove)];
+0166 model.ub=[model.ub;metaCycRxns.ub(rxnsToMove)];
+0167 model.c=[model.c;metaCycRxns.c(rxnsToMove)];
+0168 model.grRules=[model.grRules;grRulesToMove];
+0169 %model.grRules=[model.grRules;keggModel.grRules(rxnsToMove(:,2))];
+0170 %model.grRulesKEGG=[model.grRulesKEGG;keggModel.grRules(rxnsToMove(:,2))];
+0171 rxnFields=cell(numel(rxnsToMove),1);
+0172 rxnFields(:)={''};
+0173 %model.rxnNotes=[model.rxnNotes;rxnFields];
+0174 model.grRulesKEGG=[model.grRulesKEGG;rxnFields];
+0175 
+0176 %Remove all mapped reactions from KEGG model
+0177 pureKeggModel=removeReactions(keggModel,mappedRxns,true,true);
+0178 fprintf('NOTE: A global KEGG model with %d reactions and %d metabolites was obtained.\n',numel(pureKeggModel.rxns),numel(pureKeggModel.mets));
+0179 
+0180 %Replace mets information in KEGG model with the corresponding ones in
+0181 %MetaCyc This includes updating all metabolite-related fields, except S
+0182 %matrix.
+0183 load('metaCycMets.mat');
+0184 
+0185 if ~isfield(pureKeggModel,'metCharges')
+0186     pureKeggModel.metCharges=NaN(numel(pureKeggModel.mets),1);
+0187 end
+0188 
+0189 num=0;
+0190 for i=1:numel(pureKeggModel.mets)
+0191     [a, b]=ismember(pureKeggModel.mets{i},metaCycMets.keggid);
+0192     if a
+0193         %For now only replace the met ids
+0194         num=num+1;
+0195         pureKeggModel.mets{i}=metaCycMets.mets{b};
+0196         %Record the replaced mets into a vector for later
+0197     end
+0198 end
+0199 fprintf('NOTE: A total of %d metabolites from the global KEGG model will be re-mapped to MetaCyc.\n',num);
+0200 
+0201 %Generate equations for pureKeggModel
+0202 equationStrings=constructEquations(pureKeggModel,'',false,false,false,true);
+0203 
+0204 %Add the pure KEGG reactions to MetaCyc model
+0205 rxnFrom=cell(numel(pureKeggModel.rxns),1);
+0206 rxnFrom(:)={'KEGG'};
+0207 model.rxnFrom=[model.rxnFrom;rxnFrom];
+0208 model.rxns=[model.rxns;pureKeggModel.rxns];
+0209 model.equations=[model.equations;equationStrings];
+0210 model.rxnNames=[model.rxnNames;pureKeggModel.rxnNames];
+0211 model.eccodes=[model.eccodes;pureKeggModel.eccodes];
+0212 model.subSystems=[model.subSystems;pureKeggModel.subSystems];
+0213 model.rxnMiriams=[model.rxnMiriams;pureKeggModel.rxnMiriams];
+0214 model.rev=[model.rev;pureKeggModel.rev];
+0215 model.lb=[model.lb;pureKeggModel.lb];
+0216 model.ub=[model.ub;pureKeggModel.ub];
+0217 model.c=[model.c;pureKeggModel.c];
+0218 model.grRules=[model.grRules;pureKeggModel.grRules];
+0219 rxnFields=cell(numel(pureKeggModel.rxns),1);
+0220 rxnFields(:)={''};
+0221 model.grRulesKEGG=[model.grRulesKEGG;rxnFields];
+0222 model.rxnReferences=[model.rxnReferences;rxnFields];
+0223 %model.rxnNotes=[model.rxnNotes;rxnFields];
+0224 
+0225 %It could also be that the metabolite and reaction names are empty for some
+0226 %reasons. In that case, use the ID instead
+0227 %I=cellfun(@isempty,model.metNames); model.metNames(I)=model.mets(I);
+0228 I=cellfun(@isempty,model.rxnNames);
+0229 model.rxnNames(I)=model.rxns(I);
+0230 
+0231 %Generate S matrix and mets
+0232 [S, mets, ~]=constructS(model.equations);
+0233 model.S=S;
+0234 model.mets=mets;
+0235 
+0236 %Remap metabolite information
+0237 if isfield(model,'metFrom')
+0238     model=rmfield(model,'metFrom');
+0239 end
+0240 model.metFrom=cell(numel(model.mets),1);
+0241 model.metFrom(:)={''};
+0242 
+0243 if isfield(model,'metNames')
+0244     model=rmfield(model,'metNames');
+0245 end
+0246 model.metNames=cell(numel(model.mets),1);
+0247 model.metNames(:)={''};
+0248 
+0249 if isfield(model,'metFormulas')
+0250     model=rmfield(model,'metFormulas');
+0251 end
+0252 model.metFormulas=cell(numel(model.mets),1);
+0253 model.metFormulas(:)={''};
+0254 
+0255 if ~isfield(model,'metCharges')
+0256     model=rmfield(model,'metCharges');
+0257 end
+0258 model.metCharges=NaN(numel(model.mets),1);
+0259 
+0260 if ~isfield(model,'inchis')
+0261     model=rmfield(model,'inchis');
+0262 end
+0263 model.inchis=cell(numel(model.mets),1);
+0264 model.inchis(:)={''};
+0265 
+0266 if ~isfield(model,'metMiriams')
+0267     model=rmfield(model,'metMiriams');
+0268 end
+0269 model.metMiriams=cell(numel(model.mets),1);
+0270 model.metMiriams(:)={''};
+0271 
+0272 keggMets=getMetsFromKEGG();
+0273 for i=1:numel(model.mets)
+0274     [a, b]=ismember(model.mets{i},metaCycMets.mets);
+0275     if a
+0276         %Replace the met related info
+0277         model.mets{i}=metaCycMets.mets{b};
+0278         model.metNames{i}=metaCycMets.metNames{b};
+0279         model.metFormulas{i}=metaCycMets.metFormulas{b};
+0280         model.metMiriams{i}=metaCycMets.metMiriams{b};
+0281         model.inchis{i}=metaCycMets.inchis{b};
+0282         model.metCharges(i,1)=metaCycMets.metCharges(b,1);
+0283         num=num+1;
+0284     else
+0285         [c, d]=ismember(model.mets{i},keggMets.mets);
+0286         if c
+0287             model.mets{i}=keggMets.mets{d};
+0288             model.metNames{i}=keggMets.metNames{d};
+0289             model.metFormulas{i}=keggMets.metFormulas{d};
+0290             model.metMiriams{i}=keggMets.metMiriams{d};
+0291             model.inchis{i}=keggMets.inchis{d};
+0292             num=num+1;
+0293         end
+0294     end
+0295     
+0296 end
+0297 
+0298 %It could also be that the metabolite and reaction names are empty for some
+0299 %reasons. In that case, use the ID instead
+0300 I=cellfun(@isempty,model.metNames);
+0301 model.metNames(I)=model.mets(I);
+0302 
+0303 %Add confidenceScores to model in a rough way
+0304 if isfield(model,'rxnConfidenceScores')
+0305     model=rmfield(model,'rxnConfidenceScores');
+0306 end
+0307 model.rxnConfidenceScores=NaN(numel(model.rxns),1);
+0308 model.rxnConfidenceScores(:)=2;
+0309 
+0310 %Put all metabolites in one compartment called 's' (for system). This is
+0311 %done just to be more compatible with the rest of the code
+0312 model.comps={'s'};
+0313 model.compNames={'System'};
+0314 model.metComps=ones(numel(model.mets),1);
+0315 model.b=zeros(numel(model.mets),1);
+0316 
+0317 %Create the new rxnGene matrix, get back to this later
+0318 model.rxnGeneMat=sparse(numel(model.rxns),numel(model.genes));
+0319 
+0320 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/external/getBlast.html b/doc/external/getBlast.html new file mode 100644 index 000000000..4c6294904 --- /dev/null +++ b/doc/external/getBlast.html @@ -0,0 +1,267 @@ + + + + Description of getBlast + + + + + + + + + +
Home > external > getBlast.m
+ + + +

getBlast +

+ +

PURPOSE ^

+
getBlast
+ +

SYNOPSIS ^

+
function [blastStructure,blastReport]=getBlast(organismID,fastaFile,modelIDs,refFastaFiles,developMode,hideVerbose)
+ +

DESCRIPTION ^

+
 getBlast
+   Performs a bidirectional BLAST between the organism of interest and a
+   set of template organisms
+
+   Input:
+   organismID      the id of the organism of interest. This should also
+                   match with the id supplied to getModelFromHomology
+   fastaFile       a FASTA file with the protein sequences for the
+                   organism of interest
+   modelIDs        a cell array of model ids. These must match the
+                   "model.id" fields in the "models" structure if the
+                   output is to be used with getModelFromHomology
+   refFastaFiles   a cell array with the paths to the corresponding FASTA
+                   files
+   developMode     true if blastReport should be generated that is used
+                   in the unit testing function for BLAST+ (optional, default
+                   false)
+   hideVerbose     true if no status messages should be printed (optional,
+                   default false)
+
+   Output:
+   blastStructure  structure containing the bidirectional homology
+                   measurements that can be used by getModelFromHomology
+   blastReport     structure containing MD5 hashes for FASTA database
+                   files and non-parsed BLAST output data. Will be blank
+                   if developMode is false.
+
+   NOTE: This function calls BLAST+ to perform a bidirectional homology
+   test between the organism of interest and a set of other organisms
+   using standard settings. The only filtering this function does is the
+   removal of hits with an E-value higher than 10e-5. The other homology
+   measurements can be implemented using getBlastFromExcel.
+
+ Usage: [blastStructure,blastReport]=getBlast(organismID,fastaFile,...
+    modelIDs,refFastaFiles,developMode,hideVerbose)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function [blastStructure,blastReport]=getBlast(organismID,fastaFile,...
+0002     modelIDs,refFastaFiles,developMode,hideVerbose)
+0003 % getBlast
+0004 %   Performs a bidirectional BLAST between the organism of interest and a
+0005 %   set of template organisms
+0006 %
+0007 %   Input:
+0008 %   organismID      the id of the organism of interest. This should also
+0009 %                   match with the id supplied to getModelFromHomology
+0010 %   fastaFile       a FASTA file with the protein sequences for the
+0011 %                   organism of interest
+0012 %   modelIDs        a cell array of model ids. These must match the
+0013 %                   "model.id" fields in the "models" structure if the
+0014 %                   output is to be used with getModelFromHomology
+0015 %   refFastaFiles   a cell array with the paths to the corresponding FASTA
+0016 %                   files
+0017 %   developMode     true if blastReport should be generated that is used
+0018 %                   in the unit testing function for BLAST+ (optional, default
+0019 %                   false)
+0020 %   hideVerbose     true if no status messages should be printed (optional,
+0021 %                   default false)
+0022 %
+0023 %   Output:
+0024 %   blastStructure  structure containing the bidirectional homology
+0025 %                   measurements that can be used by getModelFromHomology
+0026 %   blastReport     structure containing MD5 hashes for FASTA database
+0027 %                   files and non-parsed BLAST output data. Will be blank
+0028 %                   if developMode is false.
+0029 %
+0030 %   NOTE: This function calls BLAST+ to perform a bidirectional homology
+0031 %   test between the organism of interest and a set of other organisms
+0032 %   using standard settings. The only filtering this function does is the
+0033 %   removal of hits with an E-value higher than 10e-5. The other homology
+0034 %   measurements can be implemented using getBlastFromExcel.
+0035 %
+0036 % Usage: [blastStructure,blastReport]=getBlast(organismID,fastaFile,...
+0037 %    modelIDs,refFastaFiles,developMode,hideVerbose)
+0038 
+0039 if nargin<5
+0040     developMode = false;
+0041 end
+0042 if nargin<6
+0043     hideVerbose = false;
+0044 end
+0045 
+0046 %Everything should be cell arrays
+0047 organismID=convertCharArray(organismID);
+0048 fastaFile=convertCharArray(fastaFile);
+0049 modelIDs=convertCharArray(modelIDs);
+0050 refFastaFiles=convertCharArray(refFastaFiles);
+0051 
+0052 %Create blank structures for results
+0053 blastStructure=[];
+0054 blastReport.dbHashes.phr={};
+0055 blastReport.dbHashes.pot={};
+0056 blastReport.dbHashes.psq={};
+0057 blastReport.dbHashes.pto={};
+0058 blastReport.blastTxtOutput={};
+0059 
+0060 %Get the directory for RAVEN Toolbox
+0061 ravenPath=findRAVENroot();
+0062 
+0063 %Generate temporary names for BLAST databases and output files
+0064 tmpDB=tempname;
+0065 outFile=tempname;
+0066 if ispc && contains(tmpDB,' ')
+0067     warning(['MATLAB assigned ''%s'' as temporary file path, but it '...
+0068              'contains a space character, which is not compatible with '...
+0069              'BLAST. Instead, a temporary folder will be initiated at '...
+0070              '''C:\\tempRAVEN\\'' which should manually be removed when '...
+0071              'finished.'],tmpDB)
+0072     tmpDB=tempname('C:\tempRAVEN');
+0073     outFile=tempname('C:\tempRAVEN');
+0074 end
+0075 
+0076 %Check for existence of files. If no full path is specified for a file,
+0077 %assume that it is in the current folder
+0078 if isrow(refFastaFiles)
+0079     files=horzcat(fastaFile,refFastaFiles);
+0080 else
+0081     files=vertcat(fastaFile,refFastaFiles);
+0082 end
+0083 
+0084 files=checkFileExistence(files,2); %Copy files to temp dir
+0085 fastaFile = files(1);
+0086 refFastaFiles = files(2:end);
+0087 
+0088 %Identify the operating system
+0089 if isunix
+0090     if ismac
+0091         binEnd='.mac';
+0092     else
+0093         binEnd='';
+0094     end
+0095 elseif ispc
+0096     binEnd='.exe';
+0097     setenv('BLASTDB_LMDB_MAP_SIZE','1000000');
+0098 else
+0099     dispEM('Unknown OS, exiting.')
+0100     return
+0101 end
+0102 
+0103 %Run BLAST multi-threaded to use all logical cores assigned to MATLAB
+0104 cores = evalc('feature(''numcores'')');
+0105 cores = strsplit(cores, 'MATLAB was assigned: ');
+0106 cores = regexp(cores{2},'^\d*','match');
+0107 cores = cores{1};
+0108 
+0109 %Create a database for the new organism and blast each of the refFastaFiles
+0110 %against it
+0111 [status, message]=system(['"' fullfile(ravenPath,'software','blast+',['makeblastdb' binEnd]) '" -in "' fastaFile{1} '" -out "' fullfile(tmpDB, 'tmpDB') '" -dbtype prot']);
+0112 if developMode
+0113     blastReport.dbHashes.phr{numel(blastReport.dbHashes.phr)+1}=getMD5Hash(fullfile(tmpDB, 'tmpDB.phr'));
+0114     blastReport.dbHashes.pot{numel(blastReport.dbHashes.pot)+1}=getMD5Hash(fullfile(tmpDB, 'tmpDB.pot'));
+0115     blastReport.dbHashes.psq{numel(blastReport.dbHashes.psq)+1}=getMD5Hash(fullfile(tmpDB, 'tmpDB.psq'));
+0116     blastReport.dbHashes.pto{numel(blastReport.dbHashes.pto)+1}=getMD5Hash(fullfile(tmpDB, 'tmpDB.pto'));
+0117 end
+0118 if status~=0
+0119     error('makeblastdb did not run successfully, error:\n%s',strip(message))
+0120 end
+0121 
+0122 for i=1:numel(refFastaFiles)
+0123     if ~hideVerbose
+0124         fprintf(['BLASTing "' modelIDs{i} '" against "' organismID{1} '"..\n']);
+0125     end
+0126     [status, message]=system(['"' fullfile(ravenPath,'software','blast+',['blastp' binEnd]) '" -query "' refFastaFiles{i} '" -out "' outFile '_' num2str(i) '" -db "' fullfile(tmpDB, 'tmpDB') '" -evalue 10e-5 -outfmt "10 qseqid sseqid evalue pident length bitscore ppos" -num_threads "' cores '"']);
+0127     if developMode
+0128         blastReport.blastTxtOutput{numel(blastReport.blastTxtOutput)+1}=importdata([outFile '_' num2str(i)]);
+0129     end
+0130     if status~=0
+0131         error('blastp did not run successfully, error:\n%s',strip(message))
+0132     end
+0133 end
+0134 delete([tmpDB filesep 'tmpDB*']);
+0135 
+0136 %Then create a database for each of the reference organisms and blast the
+0137 %new organism against them
+0138 for i=1:numel(refFastaFiles)
+0139     if ~hideVerbose
+0140         fprintf(['BLASTing "' organismID{1} '" against "' modelIDs{i} '"..\n']);
+0141     end
+0142     [status, message]=system(['"' fullfile(ravenPath,'software','blast+',['makeblastdb' binEnd]) '" -in "' refFastaFiles{i} '" -out "' fullfile(tmpDB, 'tmpDB') '" -dbtype prot']);
+0143     if status~=0
+0144         error('makeblastdb did not run successfully, error:\n%s',strip(message))
+0145     end
+0146     [status, message]=system(['"' fullfile(ravenPath,'software','blast+',['blastp' binEnd]) '" -query "' fastaFile{1} '" -out "' outFile '_r' num2str(i) '" -db "' fullfile(tmpDB, 'tmpDB') '" -evalue 10e-5 -outfmt "10 qseqid sseqid evalue pident length bitscore ppos" -num_threads "' cores '"']);
+0147     if developMode
+0148         blastReport.dbHashes.phr{numel(blastReport.dbHashes.phr)+1}=getMD5Hash(fullfile(tmpDB, 'tmpDB.phr'));
+0149         blastReport.dbHashes.pot{numel(blastReport.dbHashes.pot)+1}=getMD5Hash(fullfile(tmpDB, 'tmpDB.pot'));
+0150         blastReport.dbHashes.psq{numel(blastReport.dbHashes.psq)+1}=getMD5Hash(fullfile(tmpDB, 'tmpDB.psq'));
+0151         blastReport.dbHashes.pto{numel(blastReport.dbHashes.pto)+1}=getMD5Hash(fullfile(tmpDB, 'tmpDB.pto'));
+0152         blastReport.blastTxtOutput{numel(blastReport.blastTxtOutput)+1}=importdata([outFile '_r' num2str(i)]);
+0153     end    
+0154     if status~=0
+0155         error('blastp did not run successfully, error:\n%s',strip(message))
+0156     end
+0157     delete([tmpDB filesep 'tmpDB*']);
+0158 end
+0159 
+0160 %Done with the BLAST, do the parsing of the text files
+0161 for i=1:numel(refFastaFiles)*2
+0162     tempStruct=[];
+0163     if i<=numel(refFastaFiles)
+0164         tempStruct.fromId=modelIDs{i};
+0165         tempStruct.toId=organismID{1};
+0166         A=readtable([outFile '_' num2str(i)],'Delimiter',',','Format','%s%s%f%f%f%f%f');
+0167     else
+0168         tempStruct.fromId=organismID{1};
+0169         tempStruct.toId=modelIDs{i-numel(refFastaFiles)};
+0170         A=readtable([outFile '_r' num2str(i-numel(refFastaFiles))],'Delimiter',',','Format','%s%s%f%f%f%f%f');
+0171     end
+0172     tempStruct.fromGenes=A{:,1};
+0173     tempStruct.toGenes=A{:,2};
+0174     tempStruct.evalue=table2array(A(:,3));
+0175     tempStruct.identity=table2array(A(:,4));
+0176     tempStruct.aligLen=table2array(A(:,5));
+0177     tempStruct.bitscore=table2array(A(:,6));
+0178     tempStruct.ppos=table2array(A(:,7));
+0179     blastStructure=[blastStructure tempStruct];
+0180 end
+0181 
+0182 %Remove the old tempfiles
+0183 delete([outFile '*']);
+0184 %Remove the temp fasta files
+0185 delete(files{:})
+0186 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/external/getBlastFromExcel.html b/doc/external/getBlastFromExcel.html new file mode 100644 index 000000000..68300fa40 --- /dev/null +++ b/doc/external/getBlastFromExcel.html @@ -0,0 +1,185 @@ + + + + Description of getBlastFromExcel + + + + + + + + + +
Home > external > getBlastFromExcel.m
+ + + +

getBlastFromExcel +

+ +

PURPOSE ^

+
getBlastFromExcel
+ +

SYNOPSIS ^

+
function blastStructure=getBlastFromExcel(models,blastFile,organismId)
+ +

DESCRIPTION ^

+
 getBlastFromExcel
+   Retrieves gene homology information from Excel files. Used as
+   input to getModelFromHomology.
+
+   Input:
+   models          a cell array of model structures
+   blastFile       Excel file with homology information
+   organismId      the id of the organism of interest (as described in the
+                   Excel file)
+
+   Output:
+   blastStructure  structure containing the information in the Excel
+                   sheets.
+
+   The Excel file should contain a number of spreadsheets which in turn
+   contain the bidirectional homology measurements between the genes in the
+   organisms. The first and second column headers in each sheet is the
+   "to" and "from" model ids (as defined in models or for the new organism).
+   The entries should correspond to the gene names in those models. The third,
+   fourth, fifth, sixth and seventh columns represent the E-value, alignment
+   length, identity, bitscore and percentage of positive-scoring matches for
+   each measurement (captions should be "E-value", "Alignment length",
+   "Identity", "Bitscore" and "PPOS").
+
+ Usage: blastStructure=getBlastFromExcel(models,blastFile,organismId)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function blastStructure=getBlastFromExcel(models,blastFile,organismId)
+0002 % getBlastFromExcel
+0003 %   Retrieves gene homology information from Excel files. Used as
+0004 %   input to getModelFromHomology.
+0005 %
+0006 %   Input:
+0007 %   models          a cell array of model structures
+0008 %   blastFile       Excel file with homology information
+0009 %   organismId      the id of the organism of interest (as described in the
+0010 %                   Excel file)
+0011 %
+0012 %   Output:
+0013 %   blastStructure  structure containing the information in the Excel
+0014 %                   sheets.
+0015 %
+0016 %   The Excel file should contain a number of spreadsheets which in turn
+0017 %   contain the bidirectional homology measurements between the genes in the
+0018 %   organisms. The first and second column headers in each sheet is the
+0019 %   "to" and "from" model ids (as defined in models or for the new organism).
+0020 %   The entries should correspond to the gene names in those models. The third,
+0021 %   fourth, fifth, sixth and seventh columns represent the E-value, alignment
+0022 %   length, identity, bitscore and percentage of positive-scoring matches for
+0023 %   each measurement (captions should be "E-value", "Alignment length",
+0024 %   "Identity", "Bitscore" and "PPOS").
+0025 %
+0026 % Usage: blastStructure=getBlastFromExcel(models,blastFile,organismId)
+0027 
+0028 if ~isfile(blastFile)
+0029     error('BLAST result file %s cannot be found',string(blastFile));
+0030 end
+0031 organismId=char(organismId);
+0032 
+0033 blastStructure=[];
+0034 
+0035 %Get a list of model IDs
+0036 organisms=cell(numel(models)+1,1);
+0037 organisms{1}=organismId;
+0038 for i=1:numel(models)
+0039     organisms{i+1}=models{i}.id;
+0040 end
+0041 
+0042 %Get all the spreadsheets in the file
+0043 [type, sheets]=xlsfinfo(blastFile);
+0044 
+0045 %Check if the file is a Microsoft Excel Spreadsheet
+0046 if ~any(regexp(type,'Excel Spreadsheet'))
+0047     EM='The file is not a Microsoft Excel Spreadsheet';
+0048     dispEM(EM);
+0049 end
+0050 
+0051 for i=1:numel(sheets)
+0052     %Check if the sheet has the right header and deal with organisms that
+0053     %are in "models"
+0054     [values,dataSheet]=xlsread(blastFile,i);
+0055     labels=dataSheet(1,:);
+0056     if strcmpi(labels{3},'E-value') && strcmpi(labels{4},'Alignment length') ...
+0057             && strcmpi(labels{5},'Identity') && strcmpi(labels{6},'Bitscore') ...
+0058             && strcmpi(labels{7},'PPOS')
+0059         %At least one of the organisms must have a model
+0060         fromID=find(strcmpi(labels{1},organisms));
+0061         toID=find(strcmpi(labels{2},organisms));
+0062         %Check that the organism ids exist and that one of them is the
+0063         %organism of interest
+0064         if any(fromID) && any(toID) && (toID==1 || fromID==1)
+0065             %Check that no gene ids are empty. This could for example be
+0066             %the case if the gene names are wrongly formatted as numbers
+0067             %instead of strings
+0068             emptyNames=cellfun(@isempty,dataSheet(2:end,1)) | cellfun(@isempty,dataSheet(2:end,2));
+0069             if any(emptyNames)
+0070                 if all(emptyNames)
+0071                     EM=['Only empty gene names in sheet from ' organisms{fromID} ' to ' organisms{toID}];
+0072                     dispEM(EM);
+0073                 else
+0074                     EM=['Empty gene names in sheet from ' organisms{fromID} ' to ' organisms{toID} '. Ignoring genes with empty names'];
+0075                     dispEM(EM,false);
+0076                 end
+0077             end
+0078             blastStructure(numel(blastStructure)+1).toId=organisms{toID};
+0079             blastStructure(numel(blastStructure)).fromId=organisms{fromID};
+0080             blastStructure(numel(blastStructure)).fromGenes=dataSheet(2:end,1);
+0081             blastStructure(numel(blastStructure)).toGenes=dataSheet(2:end,2);
+0082             blastStructure(numel(blastStructure)).evalue=values(:,1);
+0083             blastStructure(numel(blastStructure)).aligLen=values(:,2);
+0084             blastStructure(numel(blastStructure)).identity=values(:,3);
+0085             blastStructure(numel(blastStructure)).bitscore=values(:,4);
+0086             blastStructure(numel(blastStructure)).ppos=values(:,5);
+0087             
+0088             %Remove matches where any of the values is NaN. This would have
+0089             %been done anyways in getModelFromHomology, but it's neater to
+0090             %do it here
+0091             I=isnan(blastStructure(end).evalue) | isnan(blastStructure(end).aligLen) | isnan(blastStructure(end).identity);
+0092             blastStructure(end).fromGenes(I)=[];
+0093             blastStructure(end).toGenes(I)=[];
+0094             blastStructure(end).evalue(I)=[];
+0095             blastStructure(end).aligLen(I)=[];
+0096             blastStructure(end).identity(I)=[];
+0097             blastStructure(end).bitscore(I)=[];
+0098             blastStructure(end).ppos(I)=[];
+0099         else
+0100             if isempty(toID) || isempty(fromID)
+0101                 EM=['The data in sheet ' sheets{i} ' has no corresponding model. Ignoring sheet'];
+0102                 dispEM(EM,false);
+0103             else
+0104                 EM=['The data in sheet ' sheets{i} ' does not involve the organism of interest. Ignoring sheet'];
+0105                 dispEM(EM,false);
+0106             end
+0107         end
+0108     else
+0109         EM=['The data in sheet ' sheets{i} ' is not correctly formatted. Ignoring sheet'];
+0110         dispEM(EM,false);
+0111     end
+0112 end
+0113 
+0114 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/external/getDiamond.html b/doc/external/getDiamond.html new file mode 100644 index 000000000..16db1a0d2 --- /dev/null +++ b/doc/external/getDiamond.html @@ -0,0 +1,250 @@ + + + + Description of getDiamond + + + + + + + + + +
Home > external > getDiamond.m
+ + + +

getDiamond +

+ +

PURPOSE ^

+
getDiamond
+ +

SYNOPSIS ^

+
function [blastStructure,diamondReport]=getDiamond(organismID,fastaFile,modelIDs,refFastaFiles,developMode,hideVerbose)
+ +

DESCRIPTION ^

+
 getDiamond
+   Uses DIAMOND to perform a bidirectional BLAST between the organism
+   of interest and a set of template organisms
+
+   Input:
+   organismID      the id of the organism of interest. This should also
+                   match with the id supplied to getModelFromHomology
+   fastaFile       a FASTA file with the protein sequences for the
+                   organism of interest
+   modelIDs        a cell array of model ids. These must match the
+                   "model.id" fields in the "models" structure if the
+                   output is to be used with getModelFromHomology
+   refFastaFiles   a cell array with the paths to the corresponding FASTA
+                   files
+   developMode     true if blastReport should be generated that is used
+                   in the unit testing function for DIAMOND (optional, default
+                   false)
+   hideVerbose     true if no status messages should be printed (optional,
+                   default false)
+
+   Output:
+   blastStructure  structure containing the bidirectional homology
+                   measurements which are used by getModelFromHomology
+   diamondReport   structure containing MD5 hashes for FASTA database
+                   files and non-parsed BLAST output data. Will be blank
+                   if developMode is false.
+
+   NOTE: This function calls DIAMOND to perform a bidirectional homology
+   search between the organism of interest and a set of other organisms
+   using the '--more-sensitive' setting from DIAMOND. For the most
+   sensitive results, the use of getBlast() is adviced, however,
+   getDiamond() is a fast alternative (>15x faster). The blastStructure
+   generated is in the same format as those obtained from getBlast().
+
+ Usage: [blastStructure,diamondReport]=getDiamond(organismID,fastaFile,...
+    modelIDs,refFastaFiles,developMode,hideVerbose)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function [blastStructure,diamondReport]=getDiamond(organismID,fastaFile,...
+0002     modelIDs,refFastaFiles,developMode,hideVerbose)
+0003 % getDiamond
+0004 %   Uses DIAMOND to perform a bidirectional BLAST between the organism
+0005 %   of interest and a set of template organisms
+0006 %
+0007 %   Input:
+0008 %   organismID      the id of the organism of interest. This should also
+0009 %                   match with the id supplied to getModelFromHomology
+0010 %   fastaFile       a FASTA file with the protein sequences for the
+0011 %                   organism of interest
+0012 %   modelIDs        a cell array of model ids. These must match the
+0013 %                   "model.id" fields in the "models" structure if the
+0014 %                   output is to be used with getModelFromHomology
+0015 %   refFastaFiles   a cell array with the paths to the corresponding FASTA
+0016 %                   files
+0017 %   developMode     true if blastReport should be generated that is used
+0018 %                   in the unit testing function for DIAMOND (optional, default
+0019 %                   false)
+0020 %   hideVerbose     true if no status messages should be printed (optional,
+0021 %                   default false)
+0022 %
+0023 %   Output:
+0024 %   blastStructure  structure containing the bidirectional homology
+0025 %                   measurements which are used by getModelFromHomology
+0026 %   diamondReport   structure containing MD5 hashes for FASTA database
+0027 %                   files and non-parsed BLAST output data. Will be blank
+0028 %                   if developMode is false.
+0029 %
+0030 %   NOTE: This function calls DIAMOND to perform a bidirectional homology
+0031 %   search between the organism of interest and a set of other organisms
+0032 %   using the '--more-sensitive' setting from DIAMOND. For the most
+0033 %   sensitive results, the use of getBlast() is adviced, however,
+0034 %   getDiamond() is a fast alternative (>15x faster). The blastStructure
+0035 %   generated is in the same format as those obtained from getBlast().
+0036 %
+0037 % Usage: [blastStructure,diamondReport]=getDiamond(organismID,fastaFile,...
+0038 %    modelIDs,refFastaFiles,developMode,hideVerbose)
+0039 
+0040 if nargin<5
+0041     developMode = false;
+0042 end
+0043 if nargin<6
+0044     hideVerbose = false;
+0045 end
+0046 
+0047 %Everything should be cell arrays
+0048 organismID=convertCharArray(organismID);
+0049 fastaFile=convertCharArray(fastaFile);
+0050 modelIDs=convertCharArray(modelIDs);
+0051 refFastaFiles=convertCharArray(refFastaFiles);
+0052 
+0053 %Create blank structures for results
+0054 blastStructure=[];
+0055 diamondReport.dbHashes={};
+0056 diamondReport.diamondTxtOutput={};
+0057 
+0058 %Get the directory for RAVEN Toolbox.
+0059 ravenPath=findRAVENroot();
+0060 
+0061 %Generate temporary names for DIAMOND databases and output files
+0062 tmpDB=tempname;
+0063 outFile=tempname;
+0064 
+0065 %Check for existence of files. If no full path is specified for a file,
+0066 %assume that it is in the current folder
+0067 if isrow(refFastaFiles)
+0068     files=horzcat(fastaFile,refFastaFiles);
+0069 else
+0070     files=vertcat(fastaFile,refFastaFiles);
+0071 end
+0072 
+0073 files=checkFileExistence(files,2); %Copy files to temp dir
+0074 fastaFile = files(1);
+0075 refFastaFiles = files(2:end);
+0076 
+0077 %Identify the operating system
+0078 if isunix
+0079     if ismac
+0080         binEnd='.mac';
+0081     else
+0082         binEnd='';
+0083     end
+0084 elseif ispc
+0085     binEnd='.exe';
+0086 else
+0087     dispEM('Unknown OS, exiting.')
+0088     return
+0089 end
+0090 
+0091 %Run DIAMOND multi-threaded to use all logical cores assigned to MATLAB.
+0092 cores = evalc('feature(''numcores'')');
+0093 cores = strsplit(cores, 'MATLAB was assigned: ');
+0094 cores = regexp(cores{2},'^\d*','match');
+0095 cores = cores{1};
+0096 
+0097 %Create a database for the new organism and blast each of the refFastaFiles
+0098 %against it
+0099 [status, message]=system(['"' fullfile(ravenPath,'software','diamond',['diamond' binEnd]) '" makedb --in "' fastaFile{1} '" --db "' fullfile(tmpDB) '"']);
+0100 if developMode
+0101     diamondReport.dbHashes{numel(diamondReport.dbHashes)+1} = char(regexp(message,'[a-f0-9]{32}','match'));
+0102 end
+0103 if status~=0
+0104     error('DIAMOND makedb did not run successfully, error:\n%s',strip(message))
+0105 end
+0106 
+0107 for i=1:numel(refFastaFiles)
+0108     if ~hideVerbose
+0109         fprintf(['Running DIAMOND blastp with "' modelIDs{i} '" against "' organismID{1} '"..\n']);
+0110     end
+0111     [status, message]=system(['"' fullfile(ravenPath,'software','diamond',['diamond' binEnd]) '" blastp --query "' refFastaFiles{i} '" --out "' outFile '_' num2str(i) '" --db "' fullfile(tmpDB) '" --more-sensitive --outfmt 6 qseqid sseqid evalue pident length bitscore ppos --threads ' cores ]);
+0112     if developMode
+0113         diamondReport.diamondTxtOutput{numel(diamondReport.diamondTxtOutput)+1}=importdata([outFile '_' num2str(i)]);
+0114     end
+0115     if status~=0
+0116         error('DIAMOND blastp did not run successfully, error:\n%s',strip(message))
+0117     end
+0118 end
+0119 delete([tmpDB filesep 'tmpDB*']);
+0120 
+0121 %Then create a database for each of the reference organisms and blast the
+0122 %new organism against them
+0123 for i=1:numel(refFastaFiles)
+0124     if ~hideVerbose
+0125         fprintf(['Running DIAMOND blastp with "' organismID{1} '" against "' modelIDs{i} '"..\n']);
+0126     end
+0127     [status, message1]=system(['"' fullfile(ravenPath,'software','diamond',['diamond' binEnd]) '" makedb --in "' refFastaFiles{i} '" --db "' fullfile(tmpDB) '"']);
+0128     if status~=0
+0129         error('DIAMOND makedb did not run successfully, error:\n%s',strip(message1))
+0130     end
+0131     [status, message]=system(['"' fullfile(ravenPath,'software','diamond',['diamond' binEnd]) '" blastp --query "' fastaFile{1} '" --out "' outFile '_r' num2str(i) '" --db "' fullfile(tmpDB) '" --more-sensitive --outfmt 6 qseqid sseqid evalue pident length bitscore ppos --threads ' cores]);
+0132     if developMode
+0133         diamondReport.dbHashes{numel(diamondReport.dbHashes)+1} = char(regexp(message1,'[a-f0-9]{32}','match'));
+0134         diamondReport.diamondTxtOutput{numel(diamondReport.diamondTxtOutput)+1}=importdata([outFile '_r' num2str(i)]);
+0135     end
+0136     if status~=0
+0137         error('DIAMOND blastp did not run successfully, error:\n%s',strip(message))
+0138     end
+0139     delete([tmpDB filesep 'tmpDB*']);
+0140 end
+0141 
+0142 %Done with the DIAMOND blastp, do the parsing of the text files
+0143 for i=1:numel(refFastaFiles)*2
+0144     tempStruct=[];
+0145     if i<=numel(refFastaFiles)
+0146         tempStruct.fromId=modelIDs{i};
+0147         tempStruct.toId=organismID{1};
+0148         A=readtable([outFile '_' num2str(i)],'Delimiter','\t','Format','%s%s%f%f%f%f%f');
+0149     else
+0150         tempStruct.fromId=organismID{1};
+0151         tempStruct.toId=modelIDs{i-numel(refFastaFiles)};
+0152         A=readtable([outFile '_r' num2str(i-numel(refFastaFiles))],'Delimiter','\t','Format','%s%s%f%f%f%f%f');
+0153     end
+0154     tempStruct.fromGenes=A{:,1};
+0155     tempStruct.toGenes=A{:,2};
+0156     tempStruct.evalue=table2array(A(:,3));
+0157     tempStruct.identity=table2array(A(:,4));
+0158     tempStruct.aligLen=table2array(A(:,5));
+0159     tempStruct.bitscore=table2array(A(:,6));
+0160     tempStruct.ppos=table2array(A(:,7));
+0161     blastStructure=[blastStructure tempStruct];
+0162 end
+0163 
+0164 %Remove the old tempfiles
+0165 delete([outFile '*']);
+0166 %Remove the temp fasta files
+0167 delete(files{:})
+0168 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/external/getWoLFScores.html b/doc/external/getWoLFScores.html new file mode 100644 index 000000000..e4c8178cf --- /dev/null +++ b/doc/external/getWoLFScores.html @@ -0,0 +1,113 @@ + + + + Description of getWoLFScores + + + + + + + + + +
Home > external > getWoLFScores.m
+ + + +

getWoLFScores +

+ +

PURPOSE ^

+
getWoLFScores
+ +

SYNOPSIS ^

+
function GSS = getWoLFScores(inputFile, kingdom)
+ +

DESCRIPTION ^

+
 getWoLFScores
+   Call WoLF PSort to predict the sub-cellular localization of proteins.
+   The output can be used as input to predictLocalization. This function
+   is currently only available for Linux and requires Perl to be
+   installed. If one wants to use another predictor, see parseScores. The
+   function normalizes the scores so that the best score for each gene is
+   1.0.
+
+   Input:
+   inputFile    a FASTA file with protein sequences
+   kingdom     the kingdom of the organism, 'animal', 'fungi' or 'plant'
+
+   Output:
+   GSS         a gene scoring structure to be used in predictLocalization
+
+ Usage: GSS = getWoLFScores(inputFile, kingdom)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function GSS = getWoLFScores(inputFile, kingdom)
+0002 % getWoLFScores
+0003 %   Call WoLF PSort to predict the sub-cellular localization of proteins.
+0004 %   The output can be used as input to predictLocalization. This function
+0005 %   is currently only available for Linux and requires Perl to be
+0006 %   installed. If one wants to use another predictor, see parseScores. The
+0007 %   function normalizes the scores so that the best score for each gene is
+0008 %   1.0.
+0009 %
+0010 %   Input:
+0011 %   inputFile    a FASTA file with protein sequences
+0012 %   kingdom     the kingdom of the organism, 'animal', 'fungi' or 'plant'
+0013 %
+0014 %   Output:
+0015 %   GSS         a gene scoring structure to be used in predictLocalization
+0016 %
+0017 % Usage: GSS = getWoLFScores(inputFile, kingdom)
+0018 
+0019 if ~isfile(inputFile)
+0020     error('FASTA file %s cannot be found',string(inputFile));
+0021 end
+0022 
+0023 kingdom=char(kingdom);
+0024 if ~any(strcmp(kingdom,{'animal','fungi','plant'}))
+0025     EM='Allowed kingdoms are "animal", "fungi", and "plant"';
+0026     dispEM(EM);
+0027 end
+0028 
+0029 if ispc || ismac
+0030     EM='This function currently runs only on Linux. Use parseScores if you want to use another predictor';
+0031     dispEM(EM);
+0032 end
+0033 
+0034 %Get the directory for RAVEN Toolbox
+0035 ravenPath=findRAVENroot();
+0036 
+0037 %Temporary output name
+0038 outFile=tempname;
+0039 fid=fopen(outFile,'w');
+0040 
+0041 %Do the prediction
+0042 [~, output]=unix(['perl "' ravenPath '/software/WoLFPSORT/bin/runWolfPsortSummary" ' kingdom ' < ' inputFile]);
+0043 
+0044 %Save output and call the general parser
+0045 fprintf(fid,output);
+0046 fclose(fid);
+0047 GSS=parseScores(outFile,'wolf');
+0048 
+0049 %Clean up
+0050 delete(outFile);
+0051 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/external/index.html b/doc/external/index.html new file mode 100644 index 000000000..8521638f3 --- /dev/null +++ b/doc/external/index.html @@ -0,0 +1,31 @@ + + + + Index for Directory external + + + + + + + + + + +
< Master indexIndex for external >
+ +

Index for external

+ +

Matlab files in this directory:

+ +
 combineMetaCycKEGGModelscombineMetaCycKEGGModels
 getBlastgetBlast
 getBlastFromExcelgetBlastFromExcel
 getDiamondgetDiamond
 getWoLFScoresgetWoLFScores
 makeFakeBlastStructuremakeFakeBlastStructure
 parseScoresparseScores
 updateDocumentationupdateDocumentation
+ + +

Subsequent directories:

+ + +
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/external/kegg/constructMultiFasta.html b/doc/external/kegg/constructMultiFasta.html new file mode 100644 index 000000000..def6a4931 --- /dev/null +++ b/doc/external/kegg/constructMultiFasta.html @@ -0,0 +1,222 @@ + + + + Description of constructMultiFasta + + + + + + + + + +
Home > external > kegg > constructMultiFasta.m
+ + + +

constructMultiFasta +

+ +

PURPOSE ^

+
constructMultiFasta
+ +

SYNOPSIS ^

+
function constructMultiFasta(model,sourceFile,outputDir)
+ +

DESCRIPTION ^

+
 constructMultiFasta
+   Saves one file in FASTA format for each reaction in the model that has genes
+
+   Input:
+   model         a model structure
+   sourceFile    a file with sequences in FASTA format
+   outputDir     the directory to save the resulting FASTA files in
+
+   The source file is assumed to have the format '>gene identifier
+   additional info'. Only the gene identifier is used for matching. This is
+   to be compatible with the rest of the code that retrieves information
+   from KEGG.
+
+ Usage: constructMultiFasta(model,sourceFile,outputDir)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function constructMultiFasta(model,sourceFile,outputDir)
+0002 % constructMultiFasta
+0003 %   Saves one file in FASTA format for each reaction in the model that has genes
+0004 %
+0005 %   Input:
+0006 %   model         a model structure
+0007 %   sourceFile    a file with sequences in FASTA format
+0008 %   outputDir     the directory to save the resulting FASTA files in
+0009 %
+0010 %   The source file is assumed to have the format '>gene identifier
+0011 %   additional info'. Only the gene identifier is used for matching. This is
+0012 %   to be compatible with the rest of the code that retrieves information
+0013 %   from KEGG.
+0014 %
+0015 % Usage: constructMultiFasta(model,sourceFile,outputDir)
+0016 
+0017 sourceFile=char(sourceFile);
+0018 outputDir=char(outputDir);
+0019 if ~isfile(sourceFile)
+0020     error('FASTA file %s cannot be found',string(sourceFile));
+0021 end
+0022 
+0023 fprintf('Scanning the source multi-FASTA file... ');
+0024 %Open the source file
+0025 fid = fopen(sourceFile, 'r');
+0026 
+0027 %Since the list of genes will be accessed many times I use a Java hashtable
+0028 hTable = java.util.Hashtable;
+0029 
+0030 for i=1:numel(model.genes)
+0031     hTable.put(model.genes{i}, i);
+0032 end
+0033 
+0034 %First go through the source file and save the position (in bytes) of the
+0035 %start of each gene
+0036 elementPositions=zeros(5000000,1,'int64'); %Make room for 5000000 elements
+0037 totalElements=0;
+0038 whereAmI=0; %Keeps track of where in the file we are
+0039 while 1
+0040     %Read 10 mb at a time
+0041     str=fread(fid,10000000,'int8');
+0042     
+0043     %Find any '>' which indicates a new label in FASTA format
+0044     newPosts=find(str==62); %62 is '>'
+0045     
+0046     elementPositions(totalElements+1:totalElements+numel(newPosts))=whereAmI+newPosts;
+0047     
+0048     totalElements=totalElements+numel(newPosts);
+0049     
+0050     whereAmI=whereAmI+10000000;
+0051     
+0052     if feof(fid)
+0053         break;
+0054     end
+0055 end
+0056 elementPositions=elementPositions(1:totalElements);
+0057 fprintf('COMPLETE\n');
+0058 
+0059 fprintf(['NOTICE: If Matlab is freezing and does not provide any output in 30 minutes, consider increasing Java Heap Memory\n', ...
+0060     'in MATLAB settings and start over with the new session\n']);
+0061 fprintf('Mapping genes to the multi-FASTA source file...   0%% complete');
+0062 %Now loop through the file to see which genes are present in the gene list
+0063 %and save their position IN elementPositions! This is to enable a easy way
+0064 %to get the distance to the following element
+0065 genePositions=zeros(numel(model.genes),1);
+0066 for i=1:numel(elementPositions)
+0067     fseek(fid,elementPositions(i),-1);
+0068     str=fread(fid,[1 30],'*char'); %Assumes that no ID is longer than 20 characters
+0069     delim=find(str==32 | str==10,1,'first'); %Space or line feed
+0070     
+0071     geneIdentifier=str(1:delim-1);
+0072     
+0073     %This should never happen, but just to prevent errors. Could be that
+0074     %'>' is a part of some gene information. An alternative would be to
+0075     %check that the indexes follows a line feed
+0076     if isempty(geneIdentifier)
+0077         continue;
+0078     end
+0079     
+0080     %If not found it means that the id was too long
+0081     if isempty(delim)
+0082         EM='Too long gene identifier, increase read length';
+0083         dispEM(EM);
+0084     end
+0085     
+0086     %See if the gene was found
+0087     id=hTable.get(geneIdentifier);
+0088     
+0089     if any(id)
+0090         if genePositions(id)==0
+0091             genePositions(id)=i;
+0092         end
+0093     end
+0094     %Print the progress
+0095     if rem(i-1,350000) == 0
+0096         progress=num2str(floor(100*i/numel(elementPositions)));
+0097         progress=pad(progress,3,'left');
+0098         fprintf('\b\b\b\b\b\b\b\b\b\b\b\b\b%s%% complete',progress);
+0099     end
+0100 end
+0101 fprintf('\b\b\b\b\b\b\b\b\b\b\b\b\bCOMPLETE\n');   
+0102 
+0103 fprintf('Generating the KEGG Orthology specific multi-FASTA files...   0%% complete');
+0104 %Loop through the reactions and print the corresponding sequences
+0105 for i=1:numel(model.rxns)
+0106 
+0107     %Do not overwrite existing files
+0108     if ~exist(fullfile(outputDir,[model.rxns{i} '.fa']), 'file')
+0109         
+0110         %Get the positions in elementPositions for the involved genes
+0111         genesUsed=model.rxnGeneMat(i,:);
+0112         
+0113         %Open a file for this reaction. This saves empty files for KOs
+0114         %without genes
+0115         rxnfid=fopen(fullfile(outputDir,[model.rxns{i} '.fa']),'w');
+0116         
+0117         if any(genesUsed)
+0118             positions=genePositions(genesUsed~=0);
+0119             
+0120             %It could be that some genes were not found. Delete those
+0121             %elements
+0122             positions(positions==0)=[];
+0123             
+0124             %Print each sequence
+0125             for j=1:numel(positions)
+0126                 fseek(fid,elementPositions(positions(j)),-1);
+0127                 %Should check that it ends with a gene!!!! Check for eof
+0128                 if positions(j)<numel(elementPositions)
+0129                     str=fread(fid,[1 double(elementPositions(positions(j)+1))-double(elementPositions(positions(j)))-1],'*char');
+0130                     
+0131                     %If the string does not end with a line feed character
+0132                     if str(end)~=10
+0133                         str=[str fread(fid,[1 double(elementPositions(positions(j)+2))-double(elementPositions(positions(j)+1))],'*char')];
+0134                         
+0135                         %This is if we still have not found a new gene.
+0136                         %Maximal unluck. This whole check should be done
+0137                         %when elementPositions are calculated!
+0138                         if str(end)~=10
+0139                             %Skip this gene
+0140                             continue;
+0141                         end
+0142                     end
+0143                 else
+0144                     str=fread(fid,[1 inf],'*char');
+0145                 end
+0146                 fwrite(rxnfid,['>' str]);
+0147             end
+0148         end
+0149         fclose(rxnfid);
+0150     end
+0151     %Print the progress
+0152     if rem(i-1,50) == 0
+0153         progress=num2str(floor(100*i/numel(model.rxns)));
+0154         progress=pad(progress,3,'left');
+0155         fprintf('\b\b\b\b\b\b\b\b\b\b\b\b\b%s%% complete',progress);
+0156     end
+0157 end
+0158 fprintf('\b\b\b\b\b\b\b\b\b\b\b\b\bCOMPLETE\n');
+0159 
+0160 %Close the source file
+0161 fclose(fid);
+0162 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/external/kegg/getGenesFromKEGG.html b/doc/external/kegg/getGenesFromKEGG.html new file mode 100644 index 000000000..cba93c72e --- /dev/null +++ b/doc/external/kegg/getGenesFromKEGG.html @@ -0,0 +1,516 @@ + + + + Description of getGenesFromKEGG + + + + + + + + + +
Home > external > kegg > getGenesFromKEGG.m
+ + + +

getGenesFromKEGG +

+ +

PURPOSE ^

+
getGenesFromKEGG
+ +

SYNOPSIS ^

+
function model=getGenesFromKEGG(keggPath,koList)
+ +

DESCRIPTION ^

+
 getGenesFromKEGG
+   Retrieves information on all genes stored in KEGG database
+
+   Input:
+   keggPath    if keggGenes.mat is not in the RAVEN\external\kegg
+               directory, this function will attempt to read data from a
+               local FTP dump of the KEGG database. keggPath is the path
+               to the root of this database
+   koList      the number of genes in KEGG is very large. koList can be a
+               cell array with KO identifiers, in which case only genes
+               belonging to one of those KEGG orthologies are retrieved
+               (optional, default all KOs with associated reactions)
+
+   Output:
+   model       a model structure generated from the database. The
+               following fields are filled
+       id              'KEGG'
+       name     'Automatically generated from KEGG database'
+       rxns            KO ids
+       rxnNames        Name for each entry
+       genes           IDs for all the genes. Genes are saved as organism
+                       abbreviation:id (same as in KEGG). 'HSA:124' for
+                       example is alcohol dehydrogenase in Homo sapiens
+       rxnGeneMat      A binary matrix that indicates whether a specific
+                       gene is present in a KO id
+
+   NOTE: If the file keggGenes.mat is in the RAVEN\external\kegg directory
+   it will be loaded instead of parsing of the KEGG files. If it does not
+   exist it will be saved after parsing of the KEGG files. In general, you
+   should remove the keggGenes.mat file if you want to rebuild the model
+   structure from a newer version of KEGG.
+
+ Usage: model=getGenesFromKEGG(keggPath,koList)
+
+ NOTE: This is how one entry looks in the file
+
+ ENTRY       K11440                      KO
+ NAME        gbsB
+ DEFINITION  choline dehydrogenase [EC:1.1.1.1]
+ PATHWAY     ko00260  Glycine, serine and threonine metabolism
+             ko01100  Metabolic pathways
+ MODULE      M00555  Betaine biosynthesis, choline => betaine
+ BRITE       KEGG Orthology (KO) [BR:ko00001]
+             (list truncated)
+ DBLINKS     RN: R08557 R08558
+             COG: COG1454
+ GENES       BSU: BSU31050(gbsB)
+             BSR: I33_3189
+             (list truncated)
+ REFERENCE   PMID:8752328
+   AUTHORS   Boch J, Kempf B, Schmid R, Bremer E
+   TITLE     Synthesis of the osmoprotectant glycine... (truncated)
+   JOURNAL   J Bacteriol 178:5121-9 (1996)
+             DOI:10.1128/JB.178.17.5121-5129.1996
+   SEQUENCE  [bsu:BSU31050]
+ ///
+
+ The file is not tab-delimited. Instead each label is 12 characters
+ (except for '///').
+
+ Check if the genes have been parsed before and saved. If so, load the
+ model.
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 function model=getGenesFromKEGG(keggPath,koList)
+0002 % getGenesFromKEGG
+0003 %   Retrieves information on all genes stored in KEGG database
+0004 %
+0005 %   Input:
+0006 %   keggPath    if keggGenes.mat is not in the RAVEN\external\kegg
+0007 %               directory, this function will attempt to read data from a
+0008 %               local FTP dump of the KEGG database. keggPath is the path
+0009 %               to the root of this database
+0010 %   koList      the number of genes in KEGG is very large. koList can be a
+0011 %               cell array with KO identifiers, in which case only genes
+0012 %               belonging to one of those KEGG orthologies are retrieved
+0013 %               (optional, default all KOs with associated reactions)
+0014 %
+0015 %   Output:
+0016 %   model       a model structure generated from the database. The
+0017 %               following fields are filled
+0018 %       id              'KEGG'
+0019 %       name     'Automatically generated from KEGG database'
+0020 %       rxns            KO ids
+0021 %       rxnNames        Name for each entry
+0022 %       genes           IDs for all the genes. Genes are saved as organism
+0023 %                       abbreviation:id (same as in KEGG). 'HSA:124' for
+0024 %                       example is alcohol dehydrogenase in Homo sapiens
+0025 %       rxnGeneMat      A binary matrix that indicates whether a specific
+0026 %                       gene is present in a KO id
+0027 %
+0028 %   NOTE: If the file keggGenes.mat is in the RAVEN\external\kegg directory
+0029 %   it will be loaded instead of parsing of the KEGG files. If it does not
+0030 %   exist it will be saved after parsing of the KEGG files. In general, you
+0031 %   should remove the keggGenes.mat file if you want to rebuild the model
+0032 %   structure from a newer version of KEGG.
+0033 %
+0034 % Usage: model=getGenesFromKEGG(keggPath,koList)
+0035 %
+0036 % NOTE: This is how one entry looks in the file
+0037 %
+0038 % ENTRY       K11440                      KO
+0039 % NAME        gbsB
+0040 % DEFINITION  choline dehydrogenase [EC:1.1.1.1]
+0041 % PATHWAY     ko00260  Glycine, serine and threonine metabolism
+0042 %             ko01100  Metabolic pathways
+0043 % MODULE      M00555  Betaine biosynthesis, choline => betaine
+0044 % BRITE       KEGG Orthology (KO) [BR:ko00001]
+0045 %             (list truncated)
+0046 % DBLINKS     RN: R08557 R08558
+0047 %             COG: COG1454
+0048 % GENES       BSU: BSU31050(gbsB)
+0049 %             BSR: I33_3189
+0050 %             (list truncated)
+0051 % REFERENCE   PMID:8752328
+0052 %   AUTHORS   Boch J, Kempf B, Schmid R, Bremer E
+0053 %   TITLE     Synthesis of the osmoprotectant glycine... (truncated)
+0054 %   JOURNAL   J Bacteriol 178:5121-9 (1996)
+0055 %             DOI:10.1128/JB.178.17.5121-5129.1996
+0056 %   SEQUENCE  [bsu:BSU31050]
+0057 % ///
+0058 %
+0059 % The file is not tab-delimited. Instead each label is 12 characters
+0060 % (except for '///').
+0061 %
+0062 % Check if the genes have been parsed before and saved. If so, load the
+0063 % model.
+0064 %
+0065 
+0066 if nargin<1
+0067     keggPath='RAVEN/external/kegg';
+0068 else
+0069     keggPath=char(keggPath);
+0070 end
+0071 
+0072 ravenPath=findRAVENroot();
+0073 genesFile=fullfile(ravenPath,'external','kegg','keggGenes.mat');
+0074 if ~exist(genesFile, 'file')
+0075     try
+0076         downloadKEGGgenes();
+0077     catch
+0078         %Download failed; fall through to local regeneration below
+0079     end
+0080 end
+0081 if exist(genesFile, 'file')
+0082     fprintf(['Importing KEGG genes from ' strrep(genesFile,'\','/') '... ']);
+0083     load(genesFile);
+0084 else
+0085     fprintf(['NOTE: Cannot locate ' strrep(genesFile,'\','/') ', it will therefore be generated from the local KEGG database\n']);
+0086     if ~isfile(fullfile(keggPath,'ko')) || ~isfile(fullfile(keggPath,'reaction'))
+0087         EM=fprintf(['The files ''ko'' and ''reaction'' cannot be located at ' strrep(keggPath,'\','/') '/ and should be downloaded from the KEGG FTP\n']);
+0088         dispEM(EM);
+0089     else
+0090         fprintf('Generating keggGenes.mat file...\n');
+0091         %Get all KOs that are associated to reactions
+0092         allKOs=getAllKOs(keggPath);
+0093         
+0094         %Since the list of genes will be accessed many times the hash table
+0095         %is established
+0096         geneMap=containers.Map('KeyType','char','ValueType','int32');
+0097         
+0098         %Add new functionality in the order specified in models
+0099         model.id='KEGG';
+0100         model.name='Automatically generated from KEGG database';
+0101         
+0102         %Preallocate memory
+0103         model.rxns=cell(numel(allKOs),1);
+0104         model.rxnNames=cell(numel(allKOs),1);
+0105         
+0106         %Reserve space for 500000 genes
+0107         model.genes=cell(500000,1);
+0108         
+0109         %Load information on KO ID, name, and associated genes
+0110         fid = fopen(fullfile(keggPath,'ko'), 'r');
+0111         
+0112         %Keeps track of how many KOs that have been added
+0113         koCounter=0;
+0114         nGenes=0;
+0115         addingGenes=false;
+0116         
+0117         %These contain the mapping between KOs and genes and are used to
+0118         %generate the model.rxnGeneMat in the end
+0119         koIndex=zeros(5000000,1);
+0120         geneIndex=koIndex;
+0121         nMappings=0;
+0122         
+0123         skipRead=false;
+0124         
+0125         %Loop through the file
+0126         while 1
+0127             %Get the next line
+0128             if skipRead==false
+0129                 tline = fgetl(fid);
+0130             else
+0131                 skipRead=false;
+0132             end
+0133             
+0134             %Abort at end of file
+0135             if ~ischar(tline)
+0136                 break;
+0137             end
+0138             
+0139             %Skip '///'
+0140             if numel(tline)<12
+0141                 addingGenes=false;
+0142                 continue;
+0143             end
+0144             
+0145             %Check if it's a new reaction
+0146             if strcmp(tline(1:12),'ENTRY       ')
+0147                 %Check if it should be added
+0148                 koID=tline(13:18);
+0149                 
+0150                 if ismember(koID,allKOs)
+0151                     addMe=true;
+0152                     koCounter=koCounter+1;
+0153                 else
+0154                     addMe=false;
+0155                     continue;
+0156                 end
+0157                 
+0158                 %Add reaction ID (always 6 characters)
+0159                 model.rxns{koCounter}=koID;
+0160                 
+0161                 model.rxnNames{koCounter}='';
+0162                 %Will be overwritten if it exists
+0163             end
+0164             
+0165             %To get here we must be in a KO that should be added
+0166             if addMe==true
+0167                 %Add name
+0168                 if strcmp(tline(1:12),'DEFINITION  ')
+0169                     model.rxnNames{koCounter}=tline(13:end);
+0170                 end
+0171                 
+0172                 %Check if it's time to start adding genes
+0173                 if strcmp(tline(1:12),'GENES       ')
+0174                     addingGenes=true;
+0175                 end
+0176                 
+0177                 %Add genes
+0178                 if addingGenes==true
+0179                     %We are now adding genes for the current KO. All gene
+0180                     %rows start with 12 spaces. If this is not true it
+0181                     %means that there is additional annotation such as
+0182                     %AUTHORS. This is not common but it exists
+0183                     if strcmp(tline(1:12),'            ') || strcmp(tline(1:12),'GENES       ')
+0184                         geneLine=tline(13:end);
+0185                         
+0186                         %Check if the line is from a new organism of from
+0187                         %the same as before
+0188                         if strcmp(geneLine(4),':')
+0189                             %If organism id contains 3 letters;
+0190                             currentOrganism=geneLine(1:3);
+0191                             %Parse the string
+0192                             genes=regexp(geneLine(6:end),' ','split');
+0193                             genes=strcat(currentOrganism,':',genes(:));
+0194                         elseif strcmp(geneLine(5),':')
+0195                             %If organism id contains 4 letters;
+0196                             currentOrganism=geneLine(1:4);
+0197                             %Parse the string
+0198                             genes=regexp(geneLine(7:end),' ','split');
+0199                             genes=strcat(currentOrganism,':',genes(:));
+0200                         end
+0201                         
+0202                         %Add the genes to the gene list
+0203                         for i=1:numel(genes)
+0204                             geneString=genes{i};
+0205                             if geneMap.isKey(geneString)
+0206                                 index=geneMap(geneString);
+0207                             else
+0208                                 nGenes=nGenes+1;
+0209                                 model.genes{nGenes}=geneString;
+0210                                 index=nGenes;
+0211                                 geneMap(geneString)=index;
+0212                             end
+0213                             
+0214                             %Add the connection to the KO
+0215                             nMappings=nMappings+1;
+0216                             koIndex(nMappings)=koCounter;
+0217                             geneIndex(nMappings)=index;
+0218                         end
+0219                     else
+0220                         %Now we want to throw away everything until the
+0221                         %next entry
+0222                         while 1
+0223                             tline = fgetl(fid);
+0224                             if strcmp(tline,'///')
+0225                                 %When the new entry is found, skip reading
+0226                                 %one line to fit with the rest of the code
+0227                                 skipRead=true;
+0228                                 break;
+0229                             end
+0230                         end
+0231                     end
+0232                 end
+0233             end
+0234         end
+0235         %Close the file
+0236         fclose(fid);
+0237         
+0238         %If too much space was allocated, shrink the model
+0239         model.rxns=model.rxns(1:koCounter);
+0240         model.rxnNames=model.rxnNames(1:koCounter);
+0241         model.genes=model.genes(1:nGenes);
+0242         
+0243         %Retrieve and add the gene associations
+0244         model.rxnGeneMat=sparse(koIndex(1:nMappings),geneIndex(1:nMappings),ones(nMappings,1));
+0245         
+0246         %To make sure the size is correct if the last KOs don't have genes
+0247         if size(model.rxnGeneMat,1)~=koCounter
+0248             model.rxnGeneMat(koCounter,1)=0;
+0249         end
+0250         
+0251         %Trim the genes so that they only contain information that can be
+0252         %matched to the KEGG file of protein sequences (remove all
+0253         %information after first parenthesis)
+0254         %NOTE: For some reason the organism abbreviation should be in lower
+0255         %case in this database. Fix this here
+0256         for i=1:numel(model.genes)
+0257             parIndex=strfind(model.genes{i},'(');
+0258             if any(parIndex)
+0259                 model.genes{i}=model.genes{i}(1:parIndex-1);
+0260             end
+0261             colIndex=strfind(model.genes{i},':');
+0262             model.genes{i}=[lower(model.genes{i}(1:colIndex-1)) model.genes{i}(colIndex:end)];
+0263         end
+0264         
+0265         %Save the model structure
+0266         save(genesFile,'model');
+0267     end
+0268 end
+0269 
+0270 %Only get the KOs in koList
+0271 if nargin>1
+0272     I=~ismember(model.rxns,koList);
+0273     model=removeReactions(model,I,true,true);
+0274 end
+0275 fprintf('COMPLETE\n');
+0276 end
+0277 
+0278 function allKOs=getAllKOs(keggPath)
+0279 %Retrieves all KOs that are associated to reactions. This is because the
+0280 %number of genes in KEGG is very large so without this parsing it would
+0281 %take many hours
+0282 
+0283 allKOs={};
+0284 
+0285 %First check if the reactions have already been parsed
+0286 ravenPath=findRAVENroot;
+0287 rxnsFile=fullfile(ravenPath,'external','kegg','keggRxns.mat');
+0288 if exist(rxnsFile, 'file')
+0289     fprintf(['NOTE: Importing KEGG ORTHOLOGY list from ' strrep(rxnsFile,'\','/') '.\n']);
+0290     load(rxnsFile,'model');
+0291     
+0292     %Loop through the reactions and add the corresponding genes
+0293     for i=1:numel(model.rxns)
+0294         if isstruct(model.rxnMiriams{i})
+0295             %Get all KOs
+0296             allKOs=[allKOs;model.rxnMiriams{i}.value(strcmpi(model.rxnMiriams{i}.name,'kegg.orthology'))];
+0297         end
+0298     end
+0299 else
+0300     %Parse the reaction file instead First load information on reaction ID,
+0301     %reaction name, KO, pathway and ec-number
+0302     fid = fopen(fullfile(keggPath,'reaction'), 'r');
+0303     orthology=false;
+0304     while 1
+0305         %Get the next line
+0306         tline = fgetl(fid);
+0307         
+0308         %Abort at end of file
+0309         if ~ischar(tline)
+0310             break;
+0311         end
+0312         
+0313         %Skip '///'
+0314         if numel(tline)<12
+0315             continue;
+0316         end
+0317         
+0318         %Check if it's a new reaction
+0319         if strcmp(tline(1:12),'ENTRY       ')
+0320             orthology=false;
+0321         end
+0322         
+0323         if strcmp(tline(1:9),'REFERENCE')
+0324             orthology=false;
+0325         end
+0326         
+0327         %Add KO-ids
+0328         if numel(tline)>16
+0329             if strcmp(tline(1:16),'ORTHOLOGY   KO: ') || strcmp(tline(1:16),'            KO: ') || strcmp(tline(1:12),'ORTHOLOGY   ') || orthology==true
+0330                 if strcmp(tline(13:16),'KO:')
+0331                     %This is in the old version
+0332                     allKOs=[allKOs;tline(17:22)];
+0333                 elseif strcmp(tline(1:12),'ORTHOLOGY   ')
+0334                     %This means that it found one KO in the new format and
+0335                     %that subsequent lines might be other KOs
+0336                     orthology=true;
+0337                     allKOs=[allKOs;tline(13:18)];
+0338                 end
+0339             end
+0340         end
+0341     end
+0342     
+0343     %Close the file
+0344     fclose(fid);
+0345 end
+0346 allKOs=unique(allKOs);
+0347 end
+0348 
+0349 function downloadKEGGgenes()
+0350 % downloadKEGGgenes
+0351 %   Downloads keggGenes.mat from the RAVEN GitHub release into
+0352 %   external/kegg/. This file is distributed as a release asset rather
+0353 %   than shipped in the repository because it exceeds GitHub's 100 MB
+0354 %   file-size limit.
+0355 %
+0356 %   The following asset is expected on the release tag defined below:
+0357 %       keggGenes.zip   containing keggGenes.mat
+0358 %
+0359 %   To force a refresh (for example, after a new KEGG snapshot has been
+0360 %   published with a new RAVEN release), delete
+0361 %   external/kegg/keggGenes.mat and call getGenesFromKEGG again.
+0362 %
+0363 %   Usage: downloadKEGGgenes()
+0364 
+0365 % Release tag that hosts the data archive. Bump this for any RAVEN
+0366 % release that ships an updated keggGenes.mat.
+0367 releaseTag = 'v2.11.1';
+0368 
+0369 archiveName = 'keggGenes.zip';
+0370 targetDir   = fullfile(findRAVENroot(),'external','kegg');
+0371 targetFile  = fullfile(targetDir,'keggGenes.mat');
+0372 url         = ['https://github.com/SysBioChalmers/RAVEN/releases/download/',...
+0373                releaseTag,'/',archiveName];
+0374 zipPath     = fullfile(targetDir,archiveName);
+0375 
+0376 fprintf(['Downloading ' archiveName ' from RAVEN ' releaseTag ' release... ']);
+0377 try
+0378     websave(zipPath,url);
+0379 catch ME
+0380     if strcmp(ME.identifier,'MATLAB:webservices:HTTP404StatusCodeError')
+0381         error(['Failed to download ' archiveName ': the server returned ' ...
+0382                'a 404 error. If this persists, please report it at ' ...
+0383                'https://github.com/SysBioChalmers/RAVEN/issues']);
+0384     else
+0385         rethrow(ME);
+0386     end
+0387 end
+0388 fprintf('COMPLETE\n');
+0389 
+0390 fprintf(['Extracting ' archiveName ' to ' strrep(targetDir,'\','/') '... ']);
+0391 try
+0392     unzip(zipPath,targetDir);
+0393 catch ME
+0394     if isfile(zipPath); delete(zipPath); end
+0395     error(['Failed to extract ' archiveName '. The downloaded archive ' ...
+0396            'may be corrupted.\nOriginal error: %s'],ME.message);
+0397 end
+0398 fprintf('COMPLETE\n');
+0399 
+0400 if isfile(zipPath); delete(zipPath); end
+0401 
+0402 if ~isfile(targetFile)
+0403     error(['keggGenes.mat was not found in ' archiveName ...
+0404            '. Please verify the release asset contents.']);
+0405 end
+0406 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/external/kegg/getKEGGModelForOrganism.html b/doc/external/kegg/getKEGGModelForOrganism.html new file mode 100644 index 000000000..843e4b454 --- /dev/null +++ b/doc/external/kegg/getKEGGModelForOrganism.html @@ -0,0 +1,1342 @@ + + + + Description of getKEGGModelForOrganism + + + + + + + + + +
Home > external > kegg > getKEGGModelForOrganism.m
+ + + +

getKEGGModelForOrganism +

+ +

PURPOSE ^

+
getKEGGModelForOrganism
+ +

SYNOPSIS ^

+
function model=getKEGGModelForOrganism(organismID,fastaFile,dataDir,outDir,keepSpontaneous,keepUndefinedStoich,keepIncomplete,keepGeneral,cutOff,minScoreRatioKO,minScoreRatioG,maxPhylDist,nSequences,seqIdentity,globalModel)
+ +

DESCRIPTION ^

+
 getKEGGModelForOrganism
+   Reconstructs a genome-scale metabolic model based on protein homology
+   to the orthologies in KEGG. If the target species is not available in
+   KEGG, the user must select a closely related species. It is also
+   possible to circumvent protein homology search (see fastaFile parameter
+   for more details)
+
+   Input:
+   organismID          three or four letter abbreviation of the organism
+                       (as used in KEGG). If not available, use a closely
+                       related species. This is used for determing the
+                       phylogenetic distance. Use 'eukaryotes' or
+                       'prokaryotes' to get a model for the whole domain.
+                       Only applicable if fastaFile is empty, i.e. no
+                       homology search should be performed
+   fastaFile           a FASTA file that contains the protein sequences of
+                       the organism for which to reconstruct a model (optional,
+                       if no FASTA file is supplied then a model is
+                       reconstructed based only on the organism
+                       abbreviation. This option ignores all settings
+                       except for keepSpontaneous, keepUndefinedStoich,
+                       keepIncomplete and keepGeneral)
+   dataDir             directory for which to retrieve the input data.
+                       Should contain a combination of these sub-folders:
+                       -dataDir\keggdb
+                           The KEGG database files used in 1a (see below)
+                       -dataDir\fasta
+                           The multi-FASTA files generated in 1b (see
+                           below)
+                       -dataDir\aligned
+                           The aligned FASTA files as generated in 2a (see
+                           below)
+                       -dataDir\hmms
+                           The hidden Markov models as generated in 2b or
+                           downloaded from BioMet Toolbox (see below)
+                       The final directory in dataDir should be styled as
+                       prok90_kegg116 or euk90_kegg116, indicating whether
+                       the HMMs were trained on pro- or eukaryotic
+                       sequences; using which sequence similarity treshold
+                       (first set of digits); using which KEGG version
+                       (second set of digits). (this parameter should
+                       ALWAYS be provided)
+   outDir              directory to save the results from the quering of
+                       the hidden Markov models. The output is specific
+                       for the input sequences and the settings used. It
+                       is stored in this manner so that the function can
+                       continue if interrupted or if it should run in
+                       parallel. Be careful not to leave output files from
+                       different organisms or runs with different settings
+                       in the same folder. They will not be overwritten
+                       (optional, default is a temporary dir where all *.out
+                       files are deleted before and after doing the
+                       reconstruction)
+   keepSpontaneous     include reactions labeled as "spontaneous". (optional,
+                       default true)
+   keepUndefinedStoich    include reactions in the form n A <=> n+1 A. These
+                       will be dealt with as two separate metabolites
+                       (optional, default true)
+   keepIncomplete      include reactions which have been labelled as
+                       "incomplete", "erroneous" or "unclear" (optional,
+                       default true)
+   keepGeneral         include reactions which have been labelled as
+                       "general reaction". These are reactions on the form
+                       "an aldehyde <=> an alcohol", and are therefore
+                       unsuited for modelling purposes. Note that not all
+                       reactions have this type of annotation, and the
+                       script will therefore not be able to remove all
+                       such reactions (optional, default false)
+   cutOff              significance score from HMMer needed to assign
+                       genes to a KO (optional, default 10^-50)
+   minScoreRatioG      a gene is only assigned to KOs for which the score
+                       is >=log(score)/log(best score) for that gene. This
+                       is to prevent that a gene which clearly belongs to
+                       one KO is assigned also to KOs with much lower
+                       scores (optional, default 0.8 (lower is less strict))
+   minScoreRatioKO     ignore genes in a KO if their score is
+                       <log(score)/log(best score in KO). This is to
+                       "prune" KOs which have many genes and where some are
+                       clearly a better fit (optional, default 0.3 (lower is
+                       less strict))
+   maxPhylDist         -1: only use sequences from the same domain
+                       (Prokaryota, Eukaryota)
+                       other (positive) value: only use sequences for
+                       organisms where the phylogenetic distance is at the
+                       most this large (as calculated in getPhylDist)
+                       (optional, default Inf, which means that all sequences
+                       will be used)
+   nSequences          for each KO, use up to this many sequences from the
+                       most closely related species. This is mainly to
+                       speed up the alignment process for KOs with very
+                       many genes. This subsampling is performed before
+                       running CD-HIT (optional, default inf)
+   seqIdentity         sequence identity threshold in CD-HIT, referred as
+                       "global sequence identity" in CD-HIT User's Guide.
+                       If -1 is provided, CD-HIT is skipped (optional, default 0.9)
+   globalModel         structure containing both model and KOModel
+                       structures as generated by getModelFromKEGG. These
+                       will otherwise be loaded by via getModelFromKEGG.
+                       Providing globalKEGGmodel can speed up model
+                       generation if getKEGGModelForOrganism is run
+                       multiple times for different strains. Example:
+                       [globalModel.model,globalModel.KOModel] = getModelFromKEGG;
+                       (optional, default empty, global model is loaded by
+                       getModelFromKEGG)
+
+   Output:
+   model               the reconstructed model
+
+   PLEASE READ THIS: The input to this function can be confusing, because
+   it is intended to be run in parallel on a cluster or in multiple
+   sessions. It therefore saves a lot of intermediate results to storage.
+   This also serves the purpose of not having to do redundant
+   calculations. This, however, comes with the disadvantage of somewhat
+   trickier handling. This is what this function does:
+
+   1a. Loads files from a local KEGG FTP dump and constructs a general
+       RAVEN model representing the metabolic network. The functions
+       getRxnsFromKEGG, getGenesFromKEGG, getMetsFromKEGG summarise the
+       data into 'keggRxns.mat', 'keggGenes.mat' and 'keggMets.mat' files,
+       which are later merged into 'keggModel.mat' by getModelFromKEGG
+       function. The function getPhylDist generates 'keggPhylDist.mat'
+       file. KEGG FTP access requires a <a href="matlab:
+       web('http://www.bioinformatics.jp/en/keggftp.html')">license</a>.
+   1b. Generates protein FASTA files from the KEGG FTP dump (see 1a). One
+       multi-FASTA file for each KO in KEGG is generated.
+
+   The Step 1 has to be re-done every time KEGG updates their database (or
+   rather when the updates are large enough to warrant re-running this
+   part). Many users would probably never use this feature.
+
+   2a. Filters KO-specific protein sets. This is done by using the
+       settings "maxPhylDist" and "nSequences" to control which sequences
+       should be used for constructing Hidden Markov models (HMMs), and
+       later for matching your sequences to.
+       The most common alternatives here would be to use sequences from
+       only eukaryotes, only prokaryotes or all sequences in KEGG, but you
+       could also play around with the parameters to use e.g. only fungal
+       sequences.
+   2b. KO-specific protein FASTA files are re-organised into
+       non-redundant protein sets with CD-HIT. The user can only set
+       seqIdentity parameter, which corresponds to '-c' parameter in
+       CD-HIT, described as "sequence identity threshold". CD-HIT suggsted
+       sequence identity specific word_length (-n) parameters are used.
+   2c. Does a multi sequence alignment for multi-FASTA files obtained in
+       Step 2b for future use. MAFFT software with automatic selection of
+       alignment algorithm is used in this step ('--auto').
+   2d. Trains hidden Markov models using HMMer for each of the aligned
+       KO-specific FASTA files obtained in Step 2c. This is performed with
+       'hmmbuild' using the default settings.
+
+   Step 2 may be reasonable to be re-done if the user wants to tweak the
+   settings in proteins filtering, clustering, multi sequence alignment or
+   HMMs training steps. However, it requires to have KO-specific protein
+   FASTA files obtained in Step 1a. As such files are not provided in
+   RAVEN and BioMet ToolBox, the user can only generate these files from
+   KEGG FTP dump files, so KEGG FTP license is needed.
+
+   3a. Queries the HMMs with sequences for the organism you are making a
+       model for. This step uses both the output from step 1a and from 2d.
+       This is done with 'hmmsearch' function under default settings. The
+       significance threshold value set in 'cutOff' parameter is used
+       later when parsing '*.out' files to filter out KO hits with higher
+       value than 'cutOff' value. The results with passable E values are
+       summarised into KO-gene occurence matrix with E values in
+       intersections as 'koGeneMat'. The parameters 'minScoreRatioG' and
+       'minScoreRatioKO' are then applied to 'prune' KO-gene associations
+       (see the function descriptions above for more details). The
+       intersection values for these 'prunable' associations are converted
+       to zeroes.
+   3b. Constructs a model based on the pre-processed KO-gene association
+       matrix (koGeneMat). As the full KEGG model already has reaction-KO
+       relationships, KOs are converted into the query genes. The final
+       draft model contains only these reactions, which are associated
+       with KOs from koGeneMat. The reactions without the genes may also
+       be included, if the user set keepSpontaneous as 'true'.
+
+   The Step 3 is specific to the organism for which the model is
+   reconstructed.
+
+   In principle the function looks at which output that is already available
+   and runs only the parts that are required for step 3. This means
+   that (see the definition of the parameters for details):
+   -1a is only performed if there are no KEGG model files in the
+   RAVEN\external\kegg directory
+   -1b is only performed if not all required HMMs OR aligned FASTA files
+   OR multi-FASTA files exist in the defined dataDir. This means that this
+   step is skipped if the HMMs are downloaded from BioMet Toolbox instead
+   (see above). If not all files exist it will try to find
+   the KEGG database files in dataDir.
+   -2a is only performed if not all required HMMs OR aligned FASTA files
+   files exist in the defined dataDir. This means that this step is skipped
+   if the HMMs are downloaded from BioMet Toolbox instead (see above).
+   -2b is only performed if not all required HMMs exist in the defined
+   dataDir. This means that this step is skipped if the FASTA files or
+   HMMs are downloaded from BioMet Toolbox instead (see above).
+   -3a is performed for the required HMMs for which no corresponding .out
+   file exists in outDir. This is just a way to enable the function to be
+   run in parallel or to resume if interrupted.
+   -3b is always performed.
+
+   These steps are specific to the organism for which you are
+   reconstructing the model.
+
+   Regarding the whole pipeline, the function checks the output that is
+   already available and runs only the parts that are required for step 3.
+   This means that (see the definition of the parameters for details):
+   -1a is only performed if there are no KEGG model files in the
+   RAVEN\external\kegg directory.
+   -1b is only performed if any of required KOs do not have HMMs, aligned
+   FASTA files, clustered FASTA files and raw FASTA files in the defined
+   dataDir. This means that this step is skipped if the HMMs are
+   downloaded from BioMet Toolbox instead (see above). If not all files
+   exist it will try to find the KEGG database files in dataDir.
+   -2ab are only performed if any of required KOs do not have HMMs,
+   aligned FASTA files and clustered FASTA files in the defined dataDir.
+   This means that this step is skipped if the HMMs are downloaded from
+   BioMet Toolbox instead (see above).
+   -2c is only performed if any of required KOs do not have HMMs and
+   aligned FASTA files in the defined dataDir. This means that this step
+   is skipped if the HMMs are downloaded from BioMet Toolbox instead (see
+   above).
+   -2d is only performed if any of required KOs do not have HMMs exist in
+   the defined dataDir. This means that this step is skipped if the FASTA
+   files or HMMs are downloaded from BioMet Toolbox instead (see above).
+   -3a is performed for the required HMMs for which no corresponding .out
+   file exists in outDir. This is just a way to enable the function to be
+   run in parallel or to resume if interrupted.
+   -3b is always performed.
+
+   NOTE: it is also possible to obtain draft model from KEGG without
+   providing protein FASTA file for the target organism. In such case the
+   organism three-four letter abbreviation set as 'organismID' must exist
+   in the local KEGG database. In such case, the program just fetches all
+   the reactions, which are associated with given 'organismID'.
+
+ Usage: model=getKEGGModelForOrganism(organismID,fastaFile,dataDir,...
+    outDir,keepSpontaneous,keepUndefinedStoich,keepIncomplete,...
+    keepGeneral,cutOff,minScoreRatioKO,minScoreRatioG,maxPhylDist,...
+    nSequences,seqIdentity)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 function model=getKEGGModelForOrganism(organismID,fastaFile,dataDir,...
+0002     outDir,keepSpontaneous,keepUndefinedStoich,keepIncomplete,...
+0003     keepGeneral,cutOff,minScoreRatioKO,minScoreRatioG,maxPhylDist,...
+0004     nSequences,seqIdentity,globalModel)
+0005 % getKEGGModelForOrganism
+0006 %   Reconstructs a genome-scale metabolic model based on protein homology
+0007 %   to the orthologies in KEGG. If the target species is not available in
+0008 %   KEGG, the user must select a closely related species. It is also
+0009 %   possible to circumvent protein homology search (see fastaFile parameter
+0010 %   for more details)
+0011 %
+0012 %   Input:
+0013 %   organismID          three or four letter abbreviation of the organism
+0014 %                       (as used in KEGG). If not available, use a closely
+0015 %                       related species. This is used for determing the
+0016 %                       phylogenetic distance. Use 'eukaryotes' or
+0017 %                       'prokaryotes' to get a model for the whole domain.
+0018 %                       Only applicable if fastaFile is empty, i.e. no
+0019 %                       homology search should be performed
+0020 %   fastaFile           a FASTA file that contains the protein sequences of
+0021 %                       the organism for which to reconstruct a model (optional,
+0022 %                       if no FASTA file is supplied then a model is
+0023 %                       reconstructed based only on the organism
+0024 %                       abbreviation. This option ignores all settings
+0025 %                       except for keepSpontaneous, keepUndefinedStoich,
+0026 %                       keepIncomplete and keepGeneral)
+0027 %   dataDir             directory for which to retrieve the input data.
+0028 %                       Should contain a combination of these sub-folders:
+0029 %                       -dataDir\keggdb
+0030 %                           The KEGG database files used in 1a (see below)
+0031 %                       -dataDir\fasta
+0032 %                           The multi-FASTA files generated in 1b (see
+0033 %                           below)
+0034 %                       -dataDir\aligned
+0035 %                           The aligned FASTA files as generated in 2a (see
+0036 %                           below)
+0037 %                       -dataDir\hmms
+0038 %                           The hidden Markov models as generated in 2b or
+0039 %                           downloaded from BioMet Toolbox (see below)
+0040 %                       The final directory in dataDir should be styled as
+0041 %                       prok90_kegg116 or euk90_kegg116, indicating whether
+0042 %                       the HMMs were trained on pro- or eukaryotic
+0043 %                       sequences; using which sequence similarity treshold
+0044 %                       (first set of digits); using which KEGG version
+0045 %                       (second set of digits). (this parameter should
+0046 %                       ALWAYS be provided)
+0047 %   outDir              directory to save the results from the quering of
+0048 %                       the hidden Markov models. The output is specific
+0049 %                       for the input sequences and the settings used. It
+0050 %                       is stored in this manner so that the function can
+0051 %                       continue if interrupted or if it should run in
+0052 %                       parallel. Be careful not to leave output files from
+0053 %                       different organisms or runs with different settings
+0054 %                       in the same folder. They will not be overwritten
+0055 %                       (optional, default is a temporary dir where all *.out
+0056 %                       files are deleted before and after doing the
+0057 %                       reconstruction)
+0058 %   keepSpontaneous     include reactions labeled as "spontaneous". (optional,
+0059 %                       default true)
+0060 %   keepUndefinedStoich    include reactions in the form n A <=> n+1 A. These
+0061 %                       will be dealt with as two separate metabolites
+0062 %                       (optional, default true)
+0063 %   keepIncomplete      include reactions which have been labelled as
+0064 %                       "incomplete", "erroneous" or "unclear" (optional,
+0065 %                       default true)
+0066 %   keepGeneral         include reactions which have been labelled as
+0067 %                       "general reaction". These are reactions on the form
+0068 %                       "an aldehyde <=> an alcohol", and are therefore
+0069 %                       unsuited for modelling purposes. Note that not all
+0070 %                       reactions have this type of annotation, and the
+0071 %                       script will therefore not be able to remove all
+0072 %                       such reactions (optional, default false)
+0073 %   cutOff              significance score from HMMer needed to assign
+0074 %                       genes to a KO (optional, default 10^-50)
+0075 %   minScoreRatioG      a gene is only assigned to KOs for which the score
+0076 %                       is >=log(score)/log(best score) for that gene. This
+0077 %                       is to prevent that a gene which clearly belongs to
+0078 %                       one KO is assigned also to KOs with much lower
+0079 %                       scores (optional, default 0.8 (lower is less strict))
+0080 %   minScoreRatioKO     ignore genes in a KO if their score is
+0081 %                       <log(score)/log(best score in KO). This is to
+0082 %                       "prune" KOs which have many genes and where some are
+0083 %                       clearly a better fit (optional, default 0.3 (lower is
+0084 %                       less strict))
+0085 %   maxPhylDist         -1: only use sequences from the same domain
+0086 %                       (Prokaryota, Eukaryota)
+0087 %                       other (positive) value: only use sequences for
+0088 %                       organisms where the phylogenetic distance is at the
+0089 %                       most this large (as calculated in getPhylDist)
+0090 %                       (optional, default Inf, which means that all sequences
+0091 %                       will be used)
+0092 %   nSequences          for each KO, use up to this many sequences from the
+0093 %                       most closely related species. This is mainly to
+0094 %                       speed up the alignment process for KOs with very
+0095 %                       many genes. This subsampling is performed before
+0096 %                       running CD-HIT (optional, default inf)
+0097 %   seqIdentity         sequence identity threshold in CD-HIT, referred as
+0098 %                       "global sequence identity" in CD-HIT User's Guide.
+0099 %                       If -1 is provided, CD-HIT is skipped (optional, default 0.9)
+0100 %   globalModel         structure containing both model and KOModel
+0101 %                       structures as generated by getModelFromKEGG. These
+0102 %                       will otherwise be loaded by via getModelFromKEGG.
+0103 %                       Providing globalKEGGmodel can speed up model
+0104 %                       generation if getKEGGModelForOrganism is run
+0105 %                       multiple times for different strains. Example:
+0106 %                       [globalModel.model,globalModel.KOModel] = getModelFromKEGG;
+0107 %                       (optional, default empty, global model is loaded by
+0108 %                       getModelFromKEGG)
+0109 %
+0110 %   Output:
+0111 %   model               the reconstructed model
+0112 %
+0113 %   PLEASE READ THIS: The input to this function can be confusing, because
+0114 %   it is intended to be run in parallel on a cluster or in multiple
+0115 %   sessions. It therefore saves a lot of intermediate results to storage.
+0116 %   This also serves the purpose of not having to do redundant
+0117 %   calculations. This, however, comes with the disadvantage of somewhat
+0118 %   trickier handling. This is what this function does:
+0119 %
+0120 %   1a. Loads files from a local KEGG FTP dump and constructs a general
+0121 %       RAVEN model representing the metabolic network. The functions
+0122 %       getRxnsFromKEGG, getGenesFromKEGG, getMetsFromKEGG summarise the
+0123 %       data into 'keggRxns.mat', 'keggGenes.mat' and 'keggMets.mat' files,
+0124 %       which are later merged into 'keggModel.mat' by getModelFromKEGG
+0125 %       function. The function getPhylDist generates 'keggPhylDist.mat'
+0126 %       file. KEGG FTP access requires a <a href="matlab:
+0127 %       web('http://www.bioinformatics.jp/en/keggftp.html')">license</a>.
+0128 %   1b. Generates protein FASTA files from the KEGG FTP dump (see 1a). One
+0129 %       multi-FASTA file for each KO in KEGG is generated.
+0130 %
+0131 %   The Step 1 has to be re-done every time KEGG updates their database (or
+0132 %   rather when the updates are large enough to warrant re-running this
+0133 %   part). Many users would probably never use this feature.
+0134 %
+0135 %   2a. Filters KO-specific protein sets. This is done by using the
+0136 %       settings "maxPhylDist" and "nSequences" to control which sequences
+0137 %       should be used for constructing Hidden Markov models (HMMs), and
+0138 %       later for matching your sequences to.
+0139 %       The most common alternatives here would be to use sequences from
+0140 %       only eukaryotes, only prokaryotes or all sequences in KEGG, but you
+0141 %       could also play around with the parameters to use e.g. only fungal
+0142 %       sequences.
+0143 %   2b. KO-specific protein FASTA files are re-organised into
+0144 %       non-redundant protein sets with CD-HIT. The user can only set
+0145 %       seqIdentity parameter, which corresponds to '-c' parameter in
+0146 %       CD-HIT, described as "sequence identity threshold". CD-HIT suggsted
+0147 %       sequence identity specific word_length (-n) parameters are used.
+0148 %   2c. Does a multi sequence alignment for multi-FASTA files obtained in
+0149 %       Step 2b for future use. MAFFT software with automatic selection of
+0150 %       alignment algorithm is used in this step ('--auto').
+0151 %   2d. Trains hidden Markov models using HMMer for each of the aligned
+0152 %       KO-specific FASTA files obtained in Step 2c. This is performed with
+0153 %       'hmmbuild' using the default settings.
+0154 %
+0155 %   Step 2 may be reasonable to be re-done if the user wants to tweak the
+0156 %   settings in proteins filtering, clustering, multi sequence alignment or
+0157 %   HMMs training steps. However, it requires to have KO-specific protein
+0158 %   FASTA files obtained in Step 1a. As such files are not provided in
+0159 %   RAVEN and BioMet ToolBox, the user can only generate these files from
+0160 %   KEGG FTP dump files, so KEGG FTP license is needed.
+0161 %
+0162 %   3a. Queries the HMMs with sequences for the organism you are making a
+0163 %       model for. This step uses both the output from step 1a and from 2d.
+0164 %       This is done with 'hmmsearch' function under default settings. The
+0165 %       significance threshold value set in 'cutOff' parameter is used
+0166 %       later when parsing '*.out' files to filter out KO hits with higher
+0167 %       value than 'cutOff' value. The results with passable E values are
+0168 %       summarised into KO-gene occurence matrix with E values in
+0169 %       intersections as 'koGeneMat'. The parameters 'minScoreRatioG' and
+0170 %       'minScoreRatioKO' are then applied to 'prune' KO-gene associations
+0171 %       (see the function descriptions above for more details). The
+0172 %       intersection values for these 'prunable' associations are converted
+0173 %       to zeroes.
+0174 %   3b. Constructs a model based on the pre-processed KO-gene association
+0175 %       matrix (koGeneMat). As the full KEGG model already has reaction-KO
+0176 %       relationships, KOs are converted into the query genes. The final
+0177 %       draft model contains only these reactions, which are associated
+0178 %       with KOs from koGeneMat. The reactions without the genes may also
+0179 %       be included, if the user set keepSpontaneous as 'true'.
+0180 %
+0181 %   The Step 3 is specific to the organism for which the model is
+0182 %   reconstructed.
+0183 %
+0184 %   In principle the function looks at which output that is already available
+0185 %   and runs only the parts that are required for step 3. This means
+0186 %   that (see the definition of the parameters for details):
+0187 %   -1a is only performed if there are no KEGG model files in the
+0188 %   RAVEN\external\kegg directory
+0189 %   -1b is only performed if not all required HMMs OR aligned FASTA files
+0190 %   OR multi-FASTA files exist in the defined dataDir. This means that this
+0191 %   step is skipped if the HMMs are downloaded from BioMet Toolbox instead
+0192 %   (see above). If not all files exist it will try to find
+0193 %   the KEGG database files in dataDir.
+0194 %   -2a is only performed if not all required HMMs OR aligned FASTA files
+0195 %   files exist in the defined dataDir. This means that this step is skipped
+0196 %   if the HMMs are downloaded from BioMet Toolbox instead (see above).
+0197 %   -2b is only performed if not all required HMMs exist in the defined
+0198 %   dataDir. This means that this step is skipped if the FASTA files or
+0199 %   HMMs are downloaded from BioMet Toolbox instead (see above).
+0200 %   -3a is performed for the required HMMs for which no corresponding .out
+0201 %   file exists in outDir. This is just a way to enable the function to be
+0202 %   run in parallel or to resume if interrupted.
+0203 %   -3b is always performed.
+0204 %
+0205 %   These steps are specific to the organism for which you are
+0206 %   reconstructing the model.
+0207 %
+0208 %   Regarding the whole pipeline, the function checks the output that is
+0209 %   already available and runs only the parts that are required for step 3.
+0210 %   This means that (see the definition of the parameters for details):
+0211 %   -1a is only performed if there are no KEGG model files in the
+0212 %   RAVEN\external\kegg directory.
+0213 %   -1b is only performed if any of required KOs do not have HMMs, aligned
+0214 %   FASTA files, clustered FASTA files and raw FASTA files in the defined
+0215 %   dataDir. This means that this step is skipped if the HMMs are
+0216 %   downloaded from BioMet Toolbox instead (see above). If not all files
+0217 %   exist it will try to find the KEGG database files in dataDir.
+0218 %   -2ab are only performed if any of required KOs do not have HMMs,
+0219 %   aligned FASTA files and clustered FASTA files in the defined dataDir.
+0220 %   This means that this step is skipped if the HMMs are downloaded from
+0221 %   BioMet Toolbox instead (see above).
+0222 %   -2c is only performed if any of required KOs do not have HMMs and
+0223 %   aligned FASTA files in the defined dataDir. This means that this step
+0224 %   is skipped if the HMMs are downloaded from BioMet Toolbox instead (see
+0225 %   above).
+0226 %   -2d is only performed if any of required KOs do not have HMMs exist in
+0227 %   the defined dataDir. This means that this step is skipped if the FASTA
+0228 %   files or HMMs are downloaded from BioMet Toolbox instead (see above).
+0229 %   -3a is performed for the required HMMs for which no corresponding .out
+0230 %   file exists in outDir. This is just a way to enable the function to be
+0231 %   run in parallel or to resume if interrupted.
+0232 %   -3b is always performed.
+0233 %
+0234 %   NOTE: it is also possible to obtain draft model from KEGG without
+0235 %   providing protein FASTA file for the target organism. In such case the
+0236 %   organism three-four letter abbreviation set as 'organismID' must exist
+0237 %   in the local KEGG database. In such case, the program just fetches all
+0238 %   the reactions, which are associated with given 'organismID'.
+0239 %
+0240 % Usage: model=getKEGGModelForOrganism(organismID,fastaFile,dataDir,...
+0241 %    outDir,keepSpontaneous,keepUndefinedStoich,keepIncomplete,...
+0242 %    keepGeneral,cutOff,minScoreRatioKO,minScoreRatioG,maxPhylDist,...
+0243 %    nSequences,seqIdentity)
+0244 
+0245 if nargin<2 || isempty(fastaFile)
+0246     fastaFile=[];
+0247 else
+0248     fastaFile=char(fastaFile);
+0249 end
+0250 if nargin<3
+0251     dataDir=[];
+0252 else
+0253     dataDir=char(dataDir);
+0254 end
+0255 if nargin<4 || isempty(outDir)
+0256     outDir=tempdir;
+0257     %Delete all *.out files if any exist
+0258     delete(fullfile(outDir,'*.out'));
+0259 else
+0260     outDir=char(outDir);
+0261 end
+0262 if nargin<5 || isempty(keepSpontaneous)
+0263     keepSpontaneous=true;
+0264 end
+0265 if nargin<6 || isempty(keepUndefinedStoich)
+0266     keepUndefinedStoich=true;
+0267 end
+0268 if nargin<7 || isempty(keepIncomplete)
+0269     keepIncomplete=true;
+0270 end
+0271 if nargin<8 || isempty(keepGeneral)
+0272     keepGeneral=false;
+0273 end
+0274 if nargin<9 || isempty(cutOff)
+0275     cutOff=10^-50;
+0276 end
+0277 if nargin<10 || isempty(minScoreRatioKO)
+0278     minScoreRatioKO=0.3;
+0279 end
+0280 if nargin<11 || isempty(minScoreRatioG)
+0281     minScoreRatioG=0.8;
+0282 end
+0283 if nargin<12 || isempty(maxPhylDist)
+0284     maxPhylDist=inf;
+0285     %Include all sequences for each reaction
+0286 end
+0287 if nargin<13 || isempty(nSequences)
+0288     nSequences=inf;
+0289     %Include all sequences for each reaction
+0290 end
+0291 if nargin<14 || isempty(seqIdentity)
+0292     seqIdentity=0.9;
+0293 end
+0294 
+0295 if isempty(fastaFile)
+0296     fprintf(['\n*** The model reconstruction from KEGG based on the annotation available for KEGG Species <strong>' organismID '</strong> ***\n\n']);
+0297 else
+0298     fprintf('\n*** The model reconstruction from KEGG based on the protein homology search against KEGG Orthology specific HMMs ***\n\n');
+0299     %Check if query fasta exists
+0300     fastaFile=checkFileExistence(fastaFile,2); %Copy file to temp dir
+0301 end
+0302 
+0303 %Run the external binaries multi-threaded to use all logical cores assigned
+0304 %to MATLAB
+0305 cores = evalc('feature(''numcores'')');
+0306 cores = strsplit(cores, 'MATLAB was assigned: ');
+0307 cores = regexp(cores{2},'^\d*','match');
+0308 cores = cores{1};
+0309 
+0310 %Get the directory for RAVEN Toolbox.
+0311 ravenPath=findRAVENroot();
+0312 
+0313 %Checking if dataDir is consistent. It must point to pre-trained HMMs set,
+0314 %compatible with the the current RAVEN version. The user may have the
+0315 %required zip file already in working directory or have it extracted. If
+0316 %the zip file and directory is not here, it is downloaded from the cloud
+0317 if ~isempty(dataDir)
+0318     hmmOptions={'euk90_kegg116','prok90_kegg116'};
+0319     if ~endsWith(dataDir,hmmOptions) %Check if dataDir ends with any of the hmmOptions.
+0320         %If not, then check whether the required folders exist anyway.
+0321         if ~isfile(fullfile(dataDir,'keggdb','genes.pep')) && ...
+0322                 ~isfolder(fullfile(dataDir,'fasta')) && ...
+0323                 ~isfolder(fullfile(dataDir,'aligned')) && ...
+0324                 ~isfolder(fullfile(dataDir,'hmms'))
+0325             error(['Pre-trained HMMs set is not recognised. If you want download RAVEN provided sets, it should match any of the following: ' strjoin(hmmOptions,' or ')])
+0326         end
+0327     else
+0328         if isfolder(dataDir) && isfile(fullfile(dataDir,'hmms','K00844.hmm'))
+0329             fprintf(['NOTE: Found <strong>' dataDir '</strong> directory with pre-trained HMMs, it will therefore be used during reconstruction\n']);
+0330         elseif ~isfolder(dataDir) && isfile([dataDir,'.zip'])
+0331             fprintf('Extracting the HMMs archive file... ');
+0332             unzip([dataDir,'.zip']);
+0333             fprintf('COMPLETE\n');
+0334         else
+0335             hmmIndex=strcmp(dataDir,hmmOptions);
+0336             if ~any(hmmIndex)
+0337                 error(['Pre-trained HMMs are only provided with proteins clustered at 90% sequence identity (i.e. prok90_kegg116 and euk90_kegg116). ' ...
+0338                     'Use either of these datasets, or otherwise download the relevant sequence data from KEGG to train HMMs with your desired sequence identity'])
+0339             else
+0340                 fprintf('Downloading the HMMs archive file... ');
+0341                 try
+0342                     websave([dataDir,'.zip'],['https://github.com/SysBioChalmers/RAVEN/releases/download/v2.11.0/',hmmOptions{hmmIndex},'.zip']);
+0343                 catch ME
+0344                     if strcmp(ME.identifier,'MATLAB:webservices:HTTP404StatusCodeError')
+0345                         error('Failed to download the HMMs archive file, the server returned a 404 error, try again later. If the problem persists please report it on the RAVEN GitHub Issues page: https://github.com/SysBioChalmers/RAVEN/issues')
+0346                     end
+0347                 end
+0348             end
+0349 
+0350             fprintf('COMPLETE\n');
+0351             fprintf('Extracting the HMMs archive file... ');
+0352             unzip([dataDir,'.zip']);
+0353             fprintf('COMPLETE\n');
+0354         end
+0355         %Check if HMMs are extracted
+0356         if ~isfile(fullfile(dataDir,'hmms','K00844.hmm'))
+0357             error(['The HMM files seem improperly extracted and not found in ',dataDir,'/hmms. Please remove ',dataDir,' folder and rerun getKEGGModelForOrganism']);
+0358         end
+0359     end
+0360 end
+0361 
+0362 %Check if the fasta-file contains '/' or'\'. If not then it's probably just
+0363 %a file name. Expand to full path.
+0364 if any(fastaFile)
+0365     if ~any(strfind(fastaFile,'\')) && ~any(strfind(fastaFile,'/'))
+0366         fastaFile=which(fastaFile);
+0367     end
+0368     %Create the required sub-folders in dataDir if they dont exist
+0369     if ~isfolder(fullfile(dataDir,'keggdb'))
+0370         mkdir(dataDir,'keggdb');
+0371     end
+0372     if ~isfolder(fullfile(dataDir,'fasta'))
+0373         mkdir(dataDir,'fasta');
+0374     end
+0375     if ~isfolder(fullfile(dataDir,'aligned'))
+0376         mkdir(dataDir,'aligned');
+0377     end
+0378     if ~isfolder(fullfile(dataDir,'hmms'))
+0379         mkdir(dataDir,'hmms');
+0380     end
+0381     if ~isfolder(outDir)
+0382         mkdir(outDir);
+0383     end
+0384 end
+0385 
+0386 %First generate the full global KEGG model. Can be provided as input.
+0387 %Otherwise, getModelFromKEGG is run. The dataDir must not be supplied as
+0388 %there is also an internal RAVEN version available
+0389 if nargin==15
+0390     model=globalModel.model;
+0391     KOModel=globalModel.KOModel;
+0392 elseif any(dataDir)
+0393     [model, KOModel]=getModelFromKEGG(fullfile(dataDir,'keggdb'),keepSpontaneous,keepUndefinedStoich,keepIncomplete,keepGeneral);
+0394 else
+0395     [model, KOModel]=getModelFromKEGG([],keepSpontaneous,keepUndefinedStoich,keepIncomplete,keepGeneral);
+0396 end
+0397 model.id=organismID;
+0398 model.c=zeros(numel(model.rxns),1);
+0399 
+0400 %If no FASTA file is supplied, then just remove all genes which are not for
+0401 %the given organism ID
+0402 if isempty(fastaFile)
+0403     %Check if organismID can be found in KEGG species list or is
+0404     %set to "eukaryotes" or "prokaryotes"
+0405     phylDistsFull=getPhylDist(fullfile(dataDir,'keggdb'),true);
+0406     if ~ismember(organismID,[phylDistsFull.ids 'eukaryotes' 'prokaryotes'])
+0407         error('Provided organismID is incorrect. Only species abbreviations from KEGG Species List or "eukaryotes"/"prokaryotes" are allowed.');
+0408     end
+0409 
+0410     fprintf(['Pruning the model from <strong>non-' organismID '</strong> genes... ']);
+0411     if ismember(organismID,{'eukaryotes','prokaryotes'})
+0412         phylDists=getPhylDist(fullfile(dataDir,'keggdb'),maxPhylDist==-1);
+0413         if strcmp(organismID,'eukaryotes')
+0414             proxyid='hsa';
+0415             %Use H. sapiens here
+0416         else
+0417             proxyid='eco';
+0418             %Use E. coli here
+0419         end
+0420         [~, phylDistId]=ismember(proxyid,phylDists.ids);
+0421         idsToKeep=phylDists.ids(~isinf(phylDists.distMat(phylDistId,:)));
+0422         taxIDs=cellfun(@(x) x{1},cellfun(@(x) strsplit(x,':'),model.genes,'UniformOutput',false),'UniformOutput',false);
+0423         I=ismember(upper(taxIDs),upper(idsToKeep));
+0424     else
+0425         %KEGG organism IDs may have three or four letters
+0426         organismID=strcat(organismID,':');
+0427         %Add colon for accurate matching
+0428         if length(organismID)==4
+0429             I=cellfun(@(x) strcmpi(x(1:4),organismID),model.genes);
+0430         elseif length(organismID)==5
+0431             I=cellfun(@(x) strcmpi(x(1:5),organismID),model.genes);
+0432         end
+0433     end
+0434     %Remove those genes
+0435     model.genes=model.genes(I);
+0436     model.rxnGeneMat=model.rxnGeneMat(:,I);
+0437     fprintf('COMPLETE\n');
+0438 end
+0439 
+0440 %First remove all reactions without genes
+0441 if keepSpontaneous==true
+0442     fprintf('Removing non-spontaneous reactions without GPR rules... ');
+0443     load(fullfile(ravenPath,'external','kegg','keggRxns.mat'),'isSpontaneous');
+0444     I=~any(model.rxnGeneMat,2)&~ismember(model.rxns,isSpontaneous);
+0445     spontRxnsWithGenes=model.rxns(any(model.rxnGeneMat,2)&~ismember(model.rxns,isSpontaneous));
+0446 else
+0447     fprintf('Removing reactions without GPR rules... ');
+0448     I=~any(model.rxnGeneMat,2);
+0449 end
+0450 model=removeReactions(model,I,true);
+0451 fprintf('COMPLETE\n');
+0452 
+0453 %Clean gene names
+0454 fprintf('Fixing gene names in the model... ');
+0455 %Get rid of the prefix organism id
+0456 model.genes=regexprep(model.genes,'^\w+?:','');
+0457 fprintf('COMPLETE\n');
+0458 
+0459 %If no FASTA file is supplied, then we are done here
+0460 if isempty(fastaFile)
+0461     %Create grRules
+0462     fprintf('Constructing GPR associations and annotations for the model... ');
+0463     model.grRules=cell(numel(model.rxns),1);
+0464     model.grRules(:)={''};
+0465     %Add the gene associations as 'or'
+0466     for i=1:numel(model.rxns)
+0467         %Find the involved genes
+0468         I=find(model.rxnGeneMat(i,:));
+0469         if any(I)
+0470             model.grRules{i}=['(' model.genes{I(1)}];
+0471             for j=2:numel(I)
+0472                 model.grRules{i}=[model.grRules{i} ' or ' model.genes{I(j)}];
+0473             end
+0474             model.grRules{i}=[model.grRules{i} ')'];
+0475         end
+0476     end
+0477     %Fix grRules and reconstruct rxnGeneMat
+0478     [grRules,rxnGeneMat] = standardizeGrRules(model); %Give detailed output
+0479     model.grRules = grRules;
+0480     model.rxnGeneMat = rxnGeneMat;
+0481     %Add geneMiriams, assuming that it follows the syntax
+0482     %kegg.genes/organismID:geneName
+0483     model.geneMiriams='';
+0484     for i=1:numel(model.genes)
+0485         model.geneMiriams{i,1}.name{1,1}='kegg.genes';
+0486         model.geneMiriams{i,1}.value{1,1}=strcat(lower(organismID),model.genes{i,1});
+0487     end
+0488     %Add the description to the reactions
+0489     for i=1:numel(model.rxns)
+0490         if ~isempty(model.rxnNotes{i})
+0491             model.rxnNotes(i)=strcat('Included by getKEGGModelForOrganism (without HMMs).',model.rxnNotes(i));
+0492             model.rxnNotes(i)=strrep(model.rxnNotes(i),'.','. ');
+0493         else
+0494             model.rxnNotes(i)={'Included by getKEGGModelForOrganism (without HMMs)'};
+0495         end
+0496     end
+0497     fprintf('COMPLETE\n\n');
+0498     fprintf('*** Model reconstruction complete ***\n');
+0499     return;
+0500 end
+0501 
+0502 %Create a phylogenetic distance structure
+0503 phylDistStruct=getPhylDist(fullfile(dataDir,'keggdb'),maxPhylDist==-1);
+0504 [~, phylDistId]=ismember(model.id,phylDistStruct.ids);
+0505 
+0506 %Calculate the real maximal distance now. An abitary large number of 1000
+0507 %is used for the "all in kingdom" or "all sequences" options. This is a bit
+0508 %inconvenient way to do it, but it is to make it fit with some older code
+0509 if isinf(maxPhylDist) || maxPhylDist==-1
+0510     maxPhylDist=1000;
+0511 end
+0512 
+0513 %Get the KO ids for which files have been generated. Maybe not the neatest
+0514 %way..
+0515 fastaFiles=listFiles(fullfile(dataDir,'fasta','*.fa'));
+0516 alignedFiles=listFiles(fullfile(dataDir,'aligned','*.fa'));
+0517 alignedWorking=listFiles(fullfile(dataDir,'aligned','*.faw'));
+0518 hmmFiles=listFiles(fullfile(dataDir,'hmms','*.hmm'));
+0519 outFiles=listFiles(fullfile(outDir,'*.out'));
+0520 
+0521 %Check if multi-FASTA files should be generated. This should only be
+0522 %performed if there are IDs in the KOModel structure that haven't been
+0523 %parsed yet
+0524 missingFASTA=setdiff(KOModel.rxns,[fastaFiles;alignedFiles;hmmFiles;outFiles]);
+0525 
+0526 if ~isempty(missingFASTA)
+0527     if ~isfile(fullfile(dataDir,'keggdb','genes.pep'))
+0528         EM=['The file ''genes.pep'' cannot be located at ' strrep(dataDir,'\','/') '/ and should be downloaded from the KEGG FTP.\n'];
+0529         dispEM(EM);
+0530     end
+0531     %Only construct models for KOs which don't have files already
+0532     fastaModel=removeReactions(KOModel,setdiff(KOModel.rxns,missingFASTA),true,true);
+0533     %Permute the order of the KOs in the model so that constructMultiFasta
+0534     %can be run on several processors at once
+0535     fastaModel=permuteModel(fastaModel,randperm(RandStream.create('mrg32k3a','Seed',cputime()),numel(fastaModel.rxns)),'rxns');
+0536     constructMultiFasta(fastaModel,fullfile(dataDir,'keggdb','genes.pep'),fullfile(dataDir,'fasta'));
+0537 else
+0538     fprintf('Generating the KEGG Orthology specific multi-FASTA files... COMPLETE\n');
+0539 end
+0540 
+0541 if isunix
+0542     if ismac
+0543         binEnd='.mac';
+0544     else
+0545         binEnd='';
+0546     end
+0547 elseif ispc
+0548     binEnd='';
+0549 else
+0550     EM='Unknown OS, exiting.';
+0551     disp(EM);
+0552     return
+0553 end
+0554 
+0555 tmpFile=tempname;
+0556 %On Windows, paths need to be translated to Unix before parsing it to WSL
+0557 if ispc
+0558     wslPath.tmpFile=getWSLpath(tmpFile);
+0559     %mafft has problems writing to terminal (/dev/stderr) when running
+0560     %on WSL via MATLAB, instead write and read progress file
+0561     mafftOutput = tempname;
+0562     wslPath.mafftOutput=getWSLpath(mafftOutput);
+0563     wslPath.mafft=getWSLpath(fullfile(ravenPath,'software','mafft','mafft-linux64','mafft.bat'));
+0564     wslPath.hmmbuild=getWSLpath(fullfile(ravenPath,'software','hmmer','hmmbuild'));
+0565     wslPath.hmmsearch=getWSLpath(fullfile(ravenPath,'software','hmmer','hmmsearch'));
+0566     wslPath.cdhit=getWSLpath(fullfile(ravenPath,'software','cd-hit','cd-hit'));
+0567 end
+0568 
+0569 %Check if alignment of FASTA files should be performed
+0570 missingAligned=setdiff(KOModel.rxns,[alignedFiles;hmmFiles;alignedWorking;outFiles]);
+0571 if ~isempty(missingAligned)
+0572     if seqIdentity==-1
+0573         fprintf('Performing the multiple alignment for KEGG Orthology specific protein sets...   0%% complete');
+0574     else
+0575         fprintf('Performing clustering and multiple alignment for KEGG Orthology specific protein sets...   0%% complete');
+0576     end
+0577     missingAligned=missingAligned(randperm(RandStream.create('mrg32k3a','Seed',cputime()),numel(missingAligned)));
+0578 
+0579     for i=1:numel(missingAligned)
+0580         %This is checked here because it could be that it is created by a
+0581         %parallel process. The faw-files are saved as temporary files to
+0582         %kept track of which files are being worked on
+0583         if ~isfile(fullfile(dataDir,'aligned',[missingAligned{i} '.faw'])) &&...
+0584                 ~isfile(fullfile(dataDir,'aligned',[missingAligned{i} '.fa']))
+0585             %Check that the multi-FASTA file exists. It should do so since
+0586             %we are saving empty files as well. Print a warning and
+0587             %continue if not
+0588             if ~isfile(fullfile(dataDir,'fasta',[missingAligned{i} '.fa']))
+0589                 EM=['WARNING: The multi-FASTA file for ' missingAligned{i} ' does not exist'];
+0590                 dispEM(EM,false);
+0591                 continue;
+0592             end
+0593 
+0594             %If the multi-FASTA file is empty then save an empty aligned
+0595             %file and continue
+0596             s=dir(fullfile(dataDir,'fasta',[missingAligned{i} '.fa']));
+0597             if s.bytes<=0
+0598                 fid=fopen(fullfile(dataDir,'aligned',[missingAligned{i} '.fa']),'w');
+0599                 fclose(fid);
+0600                 continue;
+0601             end
+0602 
+0603             %Create an empty file to prevent other threads to start to work
+0604             %on the same alignment
+0605             fid=fopen(fullfile(dataDir,'aligned',[missingAligned{i} '.faw']),'w');
+0606             fclose(fid);
+0607 
+0608             %First load the FASTA file, then select up to nSequences
+0609             %sequences of the most closely related species, apply any
+0610             %constraints from maxPhylDist, and save it as a temporary file,
+0611             %and create the model from that
+0612 
+0613             fastaStruct=fastaread(fullfile(dataDir,'fasta',[missingAligned{i} '.fa']));
+0614             phylDist=inf(numel(fastaStruct),1);
+0615             for j=1:numel(fastaStruct)
+0616                 %Get the organism abbreviation
+0617                 index=strfind(fastaStruct(j).Header,':');
+0618                 if any(index)
+0619                     abbrev=fastaStruct(j).Header(1:index(1)-1);
+0620                     [~, index]=ismember(abbrev,phylDistStruct.ids);
+0621                     if any(index)
+0622                         phylDist(j)=phylDistStruct.distMat(index(1),phylDistId);
+0623                     end
+0624                 end
+0625             end
+0626 
+0627             %Inf means that it should not be included
+0628             phylDist(phylDist>maxPhylDist)=[];
+0629 
+0630             %Sort based on phylDist
+0631             [~, order]=sort(phylDist);
+0632 
+0633             %Save the first nSequences hits to a temporary FASTA file
+0634             if nSequences<=numel(fastaStruct)
+0635                 fastaStruct=fastaStruct(order(1:nSequences));
+0636             else
+0637                 fastaStruct=fastaStruct(order);
+0638             end
+0639 
+0640             %Do the clustering and alignment if there are more than one
+0641             %sequences, otherwise just save the sequence (or an empty file)
+0642             if numel(fastaStruct)>1
+0643                 if seqIdentity~=-1
+0644                     cdhitInpCustom=tempname;
+0645                     fastawrite(cdhitInpCustom,fastaStruct);
+0646                     if seqIdentity<=1 && seqIdentity>0.7
+0647                         nparam='5';
+0648                     elseif seqIdentity>0.6
+0649                         nparam='4';
+0650                     elseif seqIdentity>0.5
+0651                         nparam='3';
+0652                     elseif seqIdentity>0.4
+0653                         nparam='2';
+0654                     else
+0655                         EM='The provided seqIdentity must be between 0 and 1\n';
+0656                         dispEM(EM);
+0657                     end
+0658                     if ispc
+0659                         wslPath.cdhitInpCustom=getWSLpath(cdhitInpCustom);
+0660                         [status, output]=system(['wsl "' wslPath.cdhit '" -T "' num2str(cores) '" -i "' wslPath.cdhitInpCustom '" -o "' wslPath.tmpFile '" -c "' num2str(seqIdentity) '" -n ' nparam ' -M 2000']);
+0661                     elseif ismac || isunix
+0662                         [status, output]=system(['"' fullfile(ravenPath,'software','cd-hit',['cd-hit' binEnd]) '" -T "' num2str(cores) '" -i "' cdhitInpCustom '" -o "' tmpFile '" -c "' num2str(seqIdentity) '" -n ' nparam ' -M 2000']);
+0663                     end
+0664                     if status~=0
+0665                         EM=['Error when performing clustering of ' missingAligned{i} ':\n' output];
+0666                         dispEM(EM);
+0667                     end
+0668                     %Remove the old tempfile
+0669                     if exist(cdhitInpCustom, 'file')
+0670                         delete([cdhitInpCustom '*']);
+0671                     end
+0672                 else
+0673                     %This means that CD-HIT should be skipped since
+0674                     %seqIdentity is equal to -1
+0675                     fastawrite(tmpFile,fastaStruct);
+0676                 end
+0677                 %Do the alignment for this file
+0678                 if ismac
+0679                     [status, output]=system(['"' fullfile(ravenPath,'software','mafft','mafft-mac','mafft.bat') '" --auto --anysymbol --thread "' num2str(cores) '" "' tmpFile '" > "' fullfile(dataDir,'aligned',[missingAligned{i} '.faw']) '"']);
+0680                 elseif isunix
+0681                     [status, output]=system(['"' fullfile(ravenPath,'software','mafft','mafft-linux64','mafft.bat') '" --auto --anysymbol --thread "' num2str(cores) '" "' tmpFile '" > "' fullfile(dataDir,'aligned',[missingAligned{i} '.faw']) '"']);
+0682                 elseif ispc
+0683                     wslPath.fawFile=getWSLpath(fullfile(dataDir,'aligned',[missingAligned{i} '.faw']));
+0684                     [status, ~]=system(['wsl "' wslPath.mafft '" --auto --anysymbol --progress "' wslPath.mafftOutput '" --thread "' num2str(cores) '" --out "' wslPath.fawFile '" "' wslPath.tmpFile '"']);
+0685                     output=fileread(mafftOutput);
+0686                     delete(mafftOutput);
+0687                 end
+0688                 if status~=0
+0689                     %It could be that alignment failed because only one
+0690                     %sequence was left after clustering. If that is the
+0691                     %case, then the clustered file is just copied as 'faw'
+0692                     %file
+0693                     if any(regexp(output,'Only 1 sequence found'))
+0694                         movefile(tmpFile,fullfile(dataDir,'aligned',[missingAligned{i} '.faw']),'f');
+0695                     else
+0696                         EM=['Error when performing alignment of ' missingAligned{i} ':\n' output];
+0697                         dispEM(EM);
+0698                     end
+0699                 end
+0700                 %Remove the old tempfile
+0701                 if exist(tmpFile, 'file')
+0702                     delete([tmpFile '*']);
+0703                 end
+0704             else
+0705                 %If there is only one sequence then it's not possible to do
+0706                 %a multiple alignment. Just print the sequence instead. An
+0707                 %empty file was written previously so that doesn't have to
+0708                 %be dealt with
+0709                 if numel(fastaStruct)==1
+0710                     warnState = warning; %Save the current warning state
+0711                     warning('off','Bioinfo:fastawrite:AppendToFile');
+0712                     fastawrite(fullfile(dataDir,'aligned',[missingAligned{i} '.faw']),fastaStruct);
+0713                     warning(warnState) %Reset warning state to previous settings
+0714                 end
+0715             end
+0716             %Move the temporary file to the real one
+0717             movefile(fullfile(dataDir,'aligned',[missingAligned{i} '.faw']),fullfile(dataDir,'aligned',[missingAligned{i} '.fa']),'f');
+0718 
+0719             %Print the progress every 25 files
+0720             if rem(i-1,25) == 0
+0721                 progress=num2str(floor(100*numel(listFiles(fullfile(dataDir,'aligned','*.fa')))/numel(KOModel.rxns)));
+0722                 progress=pad(progress,3,'left');
+0723                 fprintf('\b\b\b\b\b\b\b\b\b\b\b\b\b%s%% complete',progress);
+0724             end
+0725         end
+0726     end
+0727     fprintf('\b\b\b\b\b\b\b\b\b\b\b\b\bCOMPLETE\n');
+0728 else
+0729     if seqIdentity==-1
+0730         fprintf('Performing the multiple alignment for KEGG Orthology specific protein sets... COMPLETE\n');
+0731     else
+0732         fprintf('Performing clustering and multiple alignment for KEGG Orthology specific protein sets... COMPLETE\n');
+0733     end
+0734 end
+0735 
+0736 %Check if training of Hidden Markov models should be performed
+0737 missingHMMs=setdiff(KOModel.rxns,[hmmFiles;outFiles]);
+0738 if ~isempty(missingHMMs)
+0739     fprintf('Training the KEGG Orthology specific HMMs...   0%% complete');
+0740     missingHMMs=missingHMMs(randperm(RandStream.create('mrg32k3a','Seed',cputime()),numel(missingHMMs)));
+0741     %Train models for all missing KOs
+0742     for i=1:numel(missingHMMs)
+0743         %This is checked here because it could be that it is created by a
+0744         %parallel process
+0745         if ~isfile(fullfile(dataDir,'hmms',[missingHMMs{i} '.hmm'])) && ~isfile(fullfile(dataDir,'hmms',[missingHMMs{i} '.hmw']))
+0746             %Check that the aligned FASTA file exists. It could be that it
+0747             %is still being worked on by some other instance of the program
+0748             %(the .faw file should then exist). This should not happen on a
+0749             %single computer. It doesn't throw an error, because it should
+0750             %finalize the ones it can
+0751             if ~isfile(fullfile(dataDir,'aligned',[missingHMMs{i} '.fa']))
+0752                 EM=['The aligned FASTA file for ' missingHMMs{i} ' does not exist'];
+0753                 dispEM(EM,false);
+0754                 continue;
+0755             end
+0756 
+0757             %If the multi-FASTA file is empty then save an empty aligned
+0758             %file and continue
+0759             s=dir(fullfile(dataDir,'aligned',[missingHMMs{i} '.fa']));
+0760             if s.bytes<=0
+0761                 fid=fopen(fullfile(dataDir,'hmms',[missingHMMs{i} '.hmm']),'w');
+0762                 fclose(fid);
+0763                 continue;
+0764             end
+0765             %Create a temporary file to indicate that it is working on the
+0766             %KO. This is because hmmbuild cannot overwrite existing files
+0767             fid=fopen(fullfile(dataDir,'hmms',[missingHMMs{i} '.hmw']),'w');
+0768             fclose(fid);
+0769 
+0770             %Create HMM
+0771             if ismac || isunix
+0772                 [status, output]=system(['"' fullfile(ravenPath,'software','hmmer',['hmmbuild' binEnd]) '" --cpu "' num2str(cores) '" "' fullfile(dataDir,'hmms',[missingHMMs{i} '.hmm']) '" "' fullfile(dataDir,'aligned',[missingHMMs{i} '.fa']) '"']);
+0773             else
+0774                 wslPath.hmmFile   = getWSLpath(fullfile(dataDir,'hmms',[missingHMMs{i} '.hmm']));
+0775                 wslPath.alignFile = getWSLpath(fullfile(dataDir,'aligned',[missingHMMs{i} '.fa']));
+0776                 [status, output]  = system(['wsl "' wslPath.hmmbuild '" --cpu "' num2str(cores) '" "' wslPath.hmmFile '" "' wslPath.alignFile '"']);
+0777             end
+0778             if status~=0
+0779                 EM=['Error when training HMM for ' missingHMMs{i} ':\n' output];
+0780                 dispEM(EM);
+0781             end
+0782 
+0783             %Delete the temporary file
+0784             delete(fullfile(dataDir,'hmms',[missingHMMs{i} '.hmw']));
+0785 
+0786             %Print the progress every 25 files
+0787             if rem(i-1,25) == 0
+0788                 progress=num2str(floor(100*numel(listFiles(fullfile(dataDir,'hmms','*.hmm')))/numel(KOModel.rxns)));
+0789                 progress=pad(progress,3,'left');
+0790                 fprintf('\b\b\b\b\b\b\b\b\b\b\b\b\b%s%% complete',progress);
+0791             end
+0792         end
+0793     end
+0794     fprintf('\b\b\b\b\b\b\b\b\b\b\b\b\bCOMPLETE\n');
+0795 else
+0796     fprintf('Training the KEGG Orthology specific HMMs... COMPLETE\n');
+0797 end
+0798 
+0799 %Check which new .out files that should be generated. Check if training of
+0800 %Hidden Markov models should be performed
+0801 missingOUT=setdiff(KOModel.rxns,outFiles);
+0802 if ~isempty(missingOUT)
+0803     fprintf('Querying the user-specified FASTA file against the KEGG Orthology specific HMMs...   0%% complete');
+0804     missingOUT=missingOUT(randperm(RandStream.create('mrg32k3a','Seed',cputime()),numel(missingOUT)));
+0805     for i=1:numel(missingOUT)
+0806         %This is checked here because it could be that it is created by a
+0807         %parallel process
+0808         if ~isfile(fullfile(outDir,[missingOUT{i} '.out']))
+0809             %Check that the HMM file exists. It should do so since %we are
+0810             %saving empty files as well. Print a warning and continue if
+0811             %not
+0812             if ~isfile(fullfile(dataDir,'hmms',[missingOUT{i} '.hmm']))
+0813                 EM=['The HMM file for ' missingOUT{i} ' does not exist'];
+0814                 dispEM(EM,false);
+0815                 continue;
+0816             end
+0817 
+0818             %Save an empty file to prevent several threads working on the
+0819             %same file
+0820             fid=fopen(fullfile(outDir,[missingOUT{i} '.out']),'w');
+0821             fclose(fid);
+0822 
+0823             %If the HMM file is empty then save an out file and continue
+0824             s=dir(fullfile(dataDir,'hmms',[missingOUT{i} '.hmm']));
+0825             if s.bytes<=0
+0826                 continue;
+0827             end
+0828 
+0829             %Check each gene in the input file against this model
+0830             if ismac || isunix
+0831                 [status, output]=system(['"' fullfile(ravenPath,'software','hmmer',['hmmsearch' binEnd]) '" --cpu "' num2str(cores) '" "' fullfile(dataDir,'hmms',[missingOUT{i} '.hmm']) '" "' fastaFile '"']);
+0832             else
+0833                 wslPath.hmmFile   = getWSLpath(fullfile(dataDir,'hmms',[missingOUT{i} '.hmm']));
+0834                 wslPath.fastaFile = getWSLpath(fastaFile);
+0835                 [status, output]=system(['wsl "' wslPath.hmmsearch '" --cpu "' num2str(cores) '" "' wslPath.hmmFile '" "' wslPath.fastaFile '"']);
+0836             end
+0837             if status~=0
+0838                 EM=['Error when querying HMM for ' missingOUT{i} ':\n' output];
+0839                 dispEM(EM);
+0840             end
+0841 
+0842             %Save the output to a file
+0843             fid=fopen(fullfile(outDir,[missingOUT{i} '.out']),'w');
+0844             fwrite(fid,output);
+0845             fclose(fid);
+0846 
+0847             %Print the progress every 25 files
+0848             if rem(i-1,25) == 0
+0849                 progress=num2str(floor(100*numel(listFiles(fullfile(outDir,'*.out')))/numel(KOModel.rxns)));
+0850                 progress=pad(progress,3,'left');
+0851                 fprintf('\b\b\b\b\b\b\b\b\b\b\b\b\b%s%% complete',progress);
+0852             end
+0853         end
+0854     end
+0855     fprintf('\b\b\b\b\b\b\b\b\b\b\b\b\bCOMPLETE\n');
+0856 else
+0857     fprintf('Querying the user-specified FASTA file against the KEGG Orthology specific HMMs... COMPLETE\n');
+0858 end
+0859 
+0860 
+0861 %***Begin retrieving the output and putting together the resulting model
+0862 
+0863 fprintf('Parsing the HMM search results... ');
+0864 %Retrieve matched genes from the HMMs
+0865 koGeneMat=zeros(numel(KOModel.rxns),3000); %Make room for 3000 genes
+0866 genes=cell(3000,1);
+0867 %Store the best score for a gene in a hash list (since it will be searching
+0868 %many times)
+0869 hTable = java.util.Hashtable;
+0870 
+0871 geneCounter=0;
+0872 for i=1:numel(KOModel.rxns)
+0873     if exist(fullfile(outDir,[KOModel.rxns{i} '.out']), 'file')
+0874         fid=fopen(fullfile(outDir,[KOModel.rxns{i} '.out']),'r');
+0875         beginMatches=false;
+0876         while 1
+0877             %Get the next line
+0878             tline = fgetl(fid);
+0879 
+0880             %Abort at end of file
+0881             if ~ischar(tline)
+0882                 break;
+0883             end
+0884 
+0885             if and(beginMatches,strcmp(tline,'  ------ inclusion threshold ------'))
+0886                 break;
+0887             end
+0888 
+0889             if beginMatches==false
+0890                 %This is how the listing of matches begins
+0891                 if any(strfind(tline,'E-value '))
+0892                     %Read one more line that is only padding
+0893                     tline = fgetl(fid);
+0894                     beginMatches=true;
+0895                 end
+0896             else
+0897                 %If matches should be read
+0898                 if ~strcmp(tline,'   [No hits detected that satisfy reporting thresholds]') && ~isempty(tline)
+0899                     elements=regexp(tline,' ','split');
+0900                     elements=elements(cellfun(@any,elements));
+0901 
+0902                     %Check if the match is below the treshhold
+0903                     score=str2double(elements{1});
+0904                     gene=elements{9};
+0905                     if score<=cutOff
+0906                         %If the score is exactly 0, change it to a very
+0907                         %small value to avoid NaN
+0908                         if score==0
+0909                             score=10^-250;
+0910                         end
+0911                         %Check if the gene is added already and, is so, get
+0912                         %the best score for it
+0913                         I=hTable.get(gene);
+0914                         if any(I)
+0915                             koGeneMat(i,I)=score;
+0916                         else
+0917                             geneCounter=geneCounter+1;
+0918                             %The gene was not present yet so add it
+0919                             hTable.put(gene,geneCounter);
+0920                             genes{geneCounter}=gene;
+0921                             koGeneMat(i,geneCounter)=score;
+0922                         end
+0923                     end
+0924                 else
+0925                     break;
+0926                 end
+0927             end
+0928         end
+0929         fclose(fid);
+0930     end
+0931 end
+0932 fprintf('COMPLETE\n');
+0933 
+0934 fprintf('Removing gene, KEGG Orthology associations below minScoreRatioKO, minScoreRatioG... ');
+0935 koGeneMat=koGeneMat(:,1:geneCounter);
+0936 
+0937 %Remove the genes for each KO that are below minScoreRatioKO.
+0938 for i=1:size(koGeneMat,1)
+0939     J=find(koGeneMat(i,:));
+0940     if any(J)
+0941         koGeneMat(i,J(log(koGeneMat(i,J))/log(min(koGeneMat(i,J)))<minScoreRatioKO))=0;
+0942     end
+0943 end
+0944 
+0945 %Remove the KOs for each gene that are below minScoreRatioG
+0946 for i=1:size(koGeneMat,2)
+0947     J=find(koGeneMat(:,i));
+0948     if any(J)
+0949         koGeneMat(J(log(koGeneMat(J,i))/log(min(koGeneMat(J,i)))<minScoreRatioG),i)=0;
+0950     end
+0951 end
+0952 fprintf('COMPLETE\n');
+0953 
+0954 fprintf('Adding gene annotations to the model... ');
+0955 %Create the new model
+0956 model.genes=genes(1:geneCounter);
+0957 model.grRules=cell(numel(model.rxns),1);
+0958 model.grRules(:)={''};
+0959 model.rxnGeneMat=sparse(numel(model.rxns),numel(model.genes));
+0960 
+0961 %Loop through the reactions and add the corresponding genes
+0962 for i=1:numel(model.rxns)
+0963     if isstruct(model.rxnMiriams{i})
+0964         %Get all KOs
+0965         I=find(strcmpi(model.rxnMiriams{i}.name,'kegg.orthology'));
+0966         KOs=model.rxnMiriams{i}.value(I);
+0967         %Find the KOs and the corresponding genes
+0968         J=ismember(KOModel.rxns,KOs);
+0969         [~, K]=find(koGeneMat(J,:));
+0970 
+0971         if any(K)
+0972             model.rxnGeneMat(i,K)=1;
+0973             %Also delete KOs for which no genes were found. If no genes at
+0974             %all were matched to the reaction it will be deleted later
+0975             L=sum(koGeneMat(J,:),2)==0;
+0976             model.rxnMiriams{i}.value(I(L))=[];
+0977             model.rxnMiriams{i}.name(I(L))=[];
+0978         end
+0979     end
+0980 end
+0981 fprintf('COMPLETE\n');
+0982 
+0983 %Find and delete all reactions without genes. This also removes genes that
+0984 %are not used (which could happen because minScoreRatioG and
+0985 %minScoreRatioKO). If keepSpontaneous==true, the spontaneous reactions
+0986 %without genes are kept in the model. Spontaneous reactions with original
+0987 %gene associations are treated in the same way, like the rest of the
+0988 %reactions - if gene associations were removed during HMM search, such
+0989 %reactions are deleted from the model
+0990 if keepSpontaneous==true
+0991     %Not the most comprise way to delete reactions without genes, but this
+0992     %makes the code easier to understand. Firstly the non-spontaneous
+0993     %reactions without genes are removed. After that, the second deletion
+0994     %step removes spontaneous reactions, which had gene associations before
+0995     %HMM search, but no longer have after it
+0996     fprintf('Removing non-spontaneous reactions which after HMM search no longer have GPR rules... ');
+0997     I=~any(model.rxnGeneMat,2)&~ismember(model.rxns,isSpontaneous);
+0998     model=removeReactions(model,I,true,true);
+0999     I=~any(model.rxnGeneMat,2)&ismember(model.rxns,spontRxnsWithGenes);
+1000     model=removeReactions(model,I,true,true);
+1001 else
+1002     %Just simply check for any new reactions without genes and remove
+1003     %it
+1004     fprintf('Removing reactions which after HMM search no longer have GPR rules... ');
+1005     I=~any(model.rxnGeneMat,2);
+1006     model=removeReactions(model,I,true,true);
+1007 end
+1008 fprintf('COMPLETE\n');
+1009 
+1010 fprintf('Constructing GPR rules and finalizing the model... ');
+1011 %Add the gene associations as 'or'
+1012 for i=1:numel(model.rxns)
+1013     %Find the involved genes
+1014     I=find(model.rxnGeneMat(i,:));
+1015     if any(I)
+1016         model.grRules{i}=['(' model.genes{I(1)}];
+1017         for j=2:numel(I)
+1018             model.grRules{i}=[model.grRules{i} ' or ' model.genes{I(j)}];
+1019         end
+1020         model.grRules{i}=[model.grRules{i} ')'];
+1021     end
+1022 end
+1023 
+1024 %Fix grRules and reconstruct rxnGeneMat
+1025 [grRules,rxnGeneMat] = standardizeGrRules(model,false); %Give detailed output
+1026 model.grRules = grRules;
+1027 model.rxnGeneMat = rxnGeneMat;
+1028 
+1029 %Add the description to the reactions
+1030 for i=1:numel(model.rxns)
+1031     if ~isempty(model.rxnNotes{i})
+1032         model.rxnNotes(i)=strcat('Included by getKEGGModelForOrganism (using HMMs).',model.rxnNotes(i));
+1033         model.rxnNotes(i)=strrep(model.rxnNotes(i),'.','. ');
+1034     else
+1035         model.rxnNotes(i)={'Included by getKEGGModelForOrganism (using HMMs)'};
+1036     end
+1037 end
+1038 %Remove the temp fasta file
+1039 delete(fastaFile)
+1040 fprintf('COMPLETE\n\n*** Model reconstruction complete ***\n');
+1041 end
+1042 
+1043 function files=listFiles(directory)
+1044 %Supporter function to list the files in a directory and return them as a
+1045 %cell array
+1046 temp=dir(directory);
+1047 files=cell(numel(temp),1);
+1048 for i=1:numel(temp)
+1049     files{i}=temp(i,1).name;
+1050 end
+1051 files=strrep(files,'.fa','');
+1052 files=strrep(files,'.hmm','');
+1053 files=strrep(files,'.out','');
+1054 files=strrep(files,'.faw','');
+1055 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/external/kegg/getMetsFromKEGG.html b/doc/external/kegg/getMetsFromKEGG.html new file mode 100644 index 000000000..9299cd96b --- /dev/null +++ b/doc/external/kegg/getMetsFromKEGG.html @@ -0,0 +1,391 @@ + + + + Description of getMetsFromKEGG + + + + + + + + + +
Home > external > kegg > getMetsFromKEGG.m
+ + + +

getMetsFromKEGG +

+ +

PURPOSE ^

+
getMetsFromKEGG
+ +

SYNOPSIS ^

+
function model=getMetsFromKEGG(keggPath)
+ +

DESCRIPTION ^

+
 getMetsFromKEGG
+   Retrieves information on all metabolites stored in KEGG database
+
+   Input:
+   keggPath    if keggMets.mat is not in the RAVEN\external\kegg
+               directory, this function will attempt to read data from a
+               local FTP dump of the KEGG database. keggPath is the path
+               to the root of this database
+
+   Output:
+   model       a model structure generated from the database. The
+               following fields are filled
+       id              'KEGG'
+       name     'Automatically generated from KEGG database'
+       mets            KEGG compound ids
+       metNames        Compound name. Only the first name will be saved if
+                       there are several synonyms
+       metMiriams      If there is a CHEBI id available, then that will be
+                       saved here
+       inchis          InChI string for the metabolite
+       metFormulas     The chemical composition of the metabolite. This
+                       will only be loaded if there is no InChI string
+
+   NOTE: If the file keggMets.mat is in the RAVEN\external\kegg directory
+   it will be loaded instead of parsing of the KEGG files. If it does not
+   exist it will be saved after parsing of the KEGG files. In general, you
+   should remove the keggMets.mat file if you want to rebuild the model
+   structure from a newer version of KEGG.
+               
+ Usage: model=getMetsFromKEGG(keggPath)
+
+ NOTE: This is how one entry looks in the file
+
+ ENTRY       C00001                      Compound
+ NAME        H2O;
+             Water
+ FORMULA     H2O
+ EXACT_MASS  18.0106
+ MOL_WEIGHT  18.0153
+ REMARK      Same as: D00001
+ REACTION    R00001 R00002 R00004 R00005 R00009 R00010 R00011 R00017
+             R00022 R00024 R00025 R00026 R00028 R00036 R00041 R00044
+             (list truncated)
+ ENZYME      1.1.1.1         1.1.1.22        1.1.1.23        1.1.1.115
+             1.1.1.132       1.1.1.136       1.1.1.170       1.1.1.186
+             (list truncated)
+ BRITE       Therapeutic category of drugs in Japan [BR:br08301]
+             (list truncated)
+ DBLINKS     CAS: 7732-18-5
+             PubChem: 3303
+             ChEBI: 15377
+             (list truncated)
+
+ Then a lot of info about the positions of the atoms and so on. It is not
+ certain that each metabolite follows this structure exactly.
+
+ The file is not tab-delimited. Instead each label is 12 characters
+ (except for '///').
+
+ Check if the reactions have been parsed before and saved. If so, load the
+ model.
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function model=getMetsFromKEGG(keggPath)
+0002 % getMetsFromKEGG
+0003 %   Retrieves information on all metabolites stored in KEGG database
+0004 %
+0005 %   Input:
+0006 %   keggPath    if keggMets.mat is not in the RAVEN\external\kegg
+0007 %               directory, this function will attempt to read data from a
+0008 %               local FTP dump of the KEGG database. keggPath is the path
+0009 %               to the root of this database
+0010 %
+0011 %   Output:
+0012 %   model       a model structure generated from the database. The
+0013 %               following fields are filled
+0014 %       id              'KEGG'
+0015 %       name     'Automatically generated from KEGG database'
+0016 %       mets            KEGG compound ids
+0017 %       metNames        Compound name. Only the first name will be saved if
+0018 %                       there are several synonyms
+0019 %       metMiriams      If there is a CHEBI id available, then that will be
+0020 %                       saved here
+0021 %       inchis          InChI string for the metabolite
+0022 %       metFormulas     The chemical composition of the metabolite. This
+0023 %                       will only be loaded if there is no InChI string
+0024 %
+0025 %   NOTE: If the file keggMets.mat is in the RAVEN\external\kegg directory
+0026 %   it will be loaded instead of parsing of the KEGG files. If it does not
+0027 %   exist it will be saved after parsing of the KEGG files. In general, you
+0028 %   should remove the keggMets.mat file if you want to rebuild the model
+0029 %   structure from a newer version of KEGG.
+0030 %
+0031 % Usage: model=getMetsFromKEGG(keggPath)
+0032 %
+0033 % NOTE: This is how one entry looks in the file
+0034 %
+0035 % ENTRY       C00001                      Compound
+0036 % NAME        H2O;
+0037 %             Water
+0038 % FORMULA     H2O
+0039 % EXACT_MASS  18.0106
+0040 % MOL_WEIGHT  18.0153
+0041 % REMARK      Same as: D00001
+0042 % REACTION    R00001 R00002 R00004 R00005 R00009 R00010 R00011 R00017
+0043 %             R00022 R00024 R00025 R00026 R00028 R00036 R00041 R00044
+0044 %             (list truncated)
+0045 % ENZYME      1.1.1.1         1.1.1.22        1.1.1.23        1.1.1.115
+0046 %             1.1.1.132       1.1.1.136       1.1.1.170       1.1.1.186
+0047 %             (list truncated)
+0048 % BRITE       Therapeutic category of drugs in Japan [BR:br08301]
+0049 %             (list truncated)
+0050 % DBLINKS     CAS: 7732-18-5
+0051 %             PubChem: 3303
+0052 %             ChEBI: 15377
+0053 %             (list truncated)
+0054 %
+0055 % Then a lot of info about the positions of the atoms and so on. It is not
+0056 % certain that each metabolite follows this structure exactly.
+0057 %
+0058 % The file is not tab-delimited. Instead each label is 12 characters
+0059 % (except for '///').
+0060 %
+0061 % Check if the reactions have been parsed before and saved. If so, load the
+0062 % model.
+0063 %
+0064 
+0065 if nargin<1
+0066     keggPath='RAVEN/external/kegg';
+0067 else
+0068     keggPath=char(keggPath);
+0069 end
+0070 
+0071 ravenPath=findRAVENroot();
+0072 metsFile=fullfile(ravenPath,'external','kegg','keggMets.mat');
+0073 if exist(metsFile, 'file')
+0074     fprintf(['Importing KEGG metabolites from ' strrep(metsFile,'\','/') '... ']);
+0075     load(metsFile);
+0076 else
+0077     fprintf(['NOTE: Cannot locate ' strrep(metsFile,'\','/') ', it will therefore be generated from the local KEGG database\n']);
+0078     if ~isfile(fullfile(keggPath,'compound')) || ~isfile(fullfile(keggPath,'compound.inchi'))
+0079         EM=fprintf(['The files ''compound'' and ''compound.inchi'' cannot be located at ' strrep(keggPath,'\','/') '/ and should be downloaded from the KEGG FTP.\n']);
+0080         dispEM(EM);
+0081     else
+0082         fprintf('Generating keggMets.mat file... ');
+0083         %Add new functionality in the order specified in models
+0084         model.id='KEGG';
+0085         model.name='Automatically generated from KEGG database';
+0086         
+0087         %Preallocate memory for 50000 metabolites
+0088         model.mets=cell(50000,1);
+0089         model.metNames=cell(50000,1);
+0090         model.metFormulas=cell(50000,1);
+0091         model.metMiriams=cell(50000,1);
+0092         
+0093         %First load information on metabolite ID, metabolite name,
+0094         %composition, and ChEBI
+0095         
+0096         fid = fopen(fullfile(keggPath,'compound'), 'r');
+0097         
+0098         %Keeps track of how many metabolites that have been added
+0099         metCounter=0;
+0100         
+0101         %Loop through the file
+0102         while 1
+0103             %Get the next line
+0104             tline = fgetl(fid);
+0105             
+0106             %Abort at end of file
+0107             if ~ischar(tline)
+0108                 break;
+0109             end
+0110             
+0111             %Skip '///'
+0112             if numel(tline)<12
+0113                 continue;
+0114             end
+0115             
+0116             %Check if it's a new reaction
+0117             if strcmp(tline(1:12),'ENTRY       ')
+0118                 metCounter=metCounter+1;
+0119                 
+0120                 %Add empty strings where there should be such
+0121                 model.metNames{metCounter}='';
+0122                 model.metFormulas{metCounter}='';
+0123                 
+0124                 %Add compound ID (always 6 characters)
+0125                 model.mets{metCounter}=tline(13:18);
+0126                 
+0127                 %Add the KEGG id as metMiriams
+0128                 if length(model.mets{metCounter})==6
+0129                     miriamStruct=model.metMiriams{metCounter};
+0130                     if strcmp('G',model.mets{metCounter}(1))
+0131                         miriamStruct.name{1,1}='kegg.glycan';
+0132                     else
+0133                         miriamStruct.name{1,1}='kegg.compound';
+0134                     end
+0135                     miriamStruct.value{1,1}=tline(13:18);
+0136                     model.metMiriams{metCounter}=miriamStruct;
+0137                 end
+0138             end
+0139             
+0140             %Add name
+0141             if strcmp(tline(1:12),'NAME        ')
+0142                 %If there are synonyms, then the last character is ';'
+0143                 if strcmp(tline(end),';')
+0144                     model.metNames{metCounter}=tline(13:end-1);
+0145                     %Semicolon can also occur in the middle, separating
+0146                     %several synonims in the same line
+0147                     model.metNames{metCounter} = regexprep(model.metNames{metCounter},';.+','');
+0148                 elseif regexp(tline,';')
+0149                     model.metNames{metCounter}=tline(13:end);
+0150                     model.metNames{metCounter} = regexprep(model.metNames{metCounter},';.+','');
+0151                 else
+0152                     model.metNames{metCounter}=tline(13:end);
+0153                 end
+0154             end
+0155             
+0156             %Add composition
+0157             if strcmp(tline(1:12),'FORMULA     ')
+0158                 model.metFormulas{metCounter}=tline(13:end);
+0159             end
+0160             
+0161             %Add PubChem id
+0162             if numel(tline)>21
+0163                 if strcmp(tline(13:21),'PubChem: ')
+0164                     if isstruct(model.metMiriams{metCounter})
+0165                         addToIndex=numel(model.metMiriams{metCounter}.name)+1;
+0166                     else
+0167                         addToIndex=1;
+0168                     end
+0169                     miriamStruct=model.metMiriams{metCounter};
+0170                     miriamStruct.name{addToIndex,1}='pubchem.substance';
+0171                     miriamStruct.value{addToIndex,1}=tline(22:end);
+0172                     model.metMiriams{metCounter}=miriamStruct;
+0173                 end
+0174             end
+0175             
+0176             %Add CHEBI id
+0177             if numel(tline)>19
+0178                 if strcmp(tline(13:19),'ChEBI: ')
+0179                     if isstruct(model.metMiriams{metCounter})
+0180                         addToIndex=numel(model.metMiriams{metCounter}.name)+1;
+0181                     else
+0182                         addToIndex=1;
+0183                     end
+0184                     chebiIDs=strsplit(tline(20:end),' ');
+0185                     miriamStruct=model.metMiriams{metCounter};
+0186                     for i=1:numel(chebiIDs)
+0187                         miriamStruct.name{addToIndex,1}='chebi';
+0188                         miriamStruct.value{addToIndex,1}=strcat('CHEBI:',chebiIDs{i});
+0189                         addToIndex=addToIndex+1;
+0190                     end
+0191                     model.metMiriams{metCounter}=miriamStruct;
+0192                 end
+0193             end
+0194         end
+0195         
+0196         %Close the file
+0197         fclose(fid);
+0198         
+0199         %If too much space was allocated, shrink the model
+0200         model.mets=model.mets(1:metCounter);
+0201         model.metNames=model.metNames(1:metCounter);
+0202         model.metFormulas=model.metFormulas(1:metCounter);
+0203         model.metMiriams=model.metMiriams(1:metCounter);
+0204         
+0205         %Then load the InChI strings from another file. Not all metabolites
+0206         %will be present in the list
+0207         
+0208         inchIDs=cell(numel(model.mets),1);
+0209         inchis=cell(numel(model.mets),1);
+0210         
+0211         %The format is metID*tab*string
+0212         
+0213         fid = fopen(fullfile(keggPath,'compound.inchi'), 'r');
+0214         
+0215         %Loop through the file
+0216         counter=1;
+0217         while 1
+0218             %Get the next line
+0219             tline = fgetl(fid);
+0220             
+0221             %Abort at end of file
+0222             if ~ischar(tline)
+0223                 break;
+0224             end
+0225             
+0226             %Get the ID and the InChI
+0227             inchIDs{counter}=tline(1:6);
+0228             inchis{counter}=tline(14:end);
+0229             counter=counter+1;
+0230         end
+0231         
+0232         %Close the file
+0233         fclose(fid);
+0234         
+0235         inchIDs=inchIDs(1:counter-1);
+0236         inchis=inchis(1:counter-1);
+0237         
+0238         %Find the metabolites that had InChI strings and add them to the
+0239         %model
+0240         [a, b]=ismember(inchIDs,model.mets);
+0241         
+0242         %If there were mets with InChIs but that were not in the list
+0243         if ~all(a)
+0244             EM='Not all metabolites with InChI strings were found in the original list';
+0245             disp(EM);
+0246         end
+0247         
+0248         model.inchis=cell(numel(model.mets),1);
+0249         model.inchis(:)={''};
+0250         model.inchis(b)=inchis;
+0251         
+0252         %Remove composition if InChI was found
+0253         model.metFormulas(b)={''};
+0254         
+0255         %Ensuring that all model.metMiriams.value consist only of strings,
+0256         %no double
+0257         for i=1:(numel(model.mets))
+0258             for j=1:(numel(model.metMiriams{i}))
+0259                 if isa(model.metMiriams{i}.value{j},'double')
+0260                     model.metMiriams{i}.value{j}=num2str(model.metMiriams{i}.value{j});
+0261                 end
+0262             end
+0263         end
+0264         
+0265         %Removing fronting and trailing whitespace from metNames
+0266         model.metNames = deblank(model.metNames);
+0267         
+0268         %Fixing redundant metNames. The first occurence of particular
+0269         %metabolite name is not changed, but starting from the second
+0270         %occurence, original metabolite name is concatenated with KEGG
+0271         %COMPOUND id between the brackets
+0272         for i=1:(numel(model.metNames))
+0273             if ~isempty(model.metNames{i})
+0274                 if sum(ismember(model.metNames(1:i-1),model.metNames(i)))>=1
+0275                     model.metNames(i) = strcat(model.metNames(i), ' (', model.mets(i),')');
+0276                 end
+0277             end
+0278         end
+0279         %Saves the model
+0280         save(metsFile,'model');
+0281     end
+0282 end
+0283 fprintf('COMPLETE\n');
+0284 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/external/kegg/getModelFromKEGG.html b/doc/external/kegg/getModelFromKEGG.html new file mode 100644 index 000000000..ae4dd1a35 --- /dev/null +++ b/doc/external/kegg/getModelFromKEGG.html @@ -0,0 +1,381 @@ + + + + Description of getModelFromKEGG + + + + + + + + + +
Home > external > kegg > getModelFromKEGG.m
+ + + +

getModelFromKEGG +

+ +

PURPOSE ^

+
getModelFromKEGG
+ +

SYNOPSIS ^

+
function [model,KOModel]=getModelFromKEGG(keggPath,keepSpontaneous,keepUndefinedStoich,keepIncomplete,keepGeneral)
+ +

DESCRIPTION ^

+
 getModelFromKEGG
+   Retrieves information stored in KEGG database and generates a model
+
+   Input:
+   keggPath            if keggGenes.mat, keggMets.mat, keggPhylDist.mat or
+                       keggRxns.mat are not in the RAVEN/external/kegg
+                       directory, this function will attempt to read data
+                       from a local FTP dump of the KEGG database.
+                       keggPath is the path to the root of this database
+                       (optional, default 'RAVEN/external/kegg'). If
+                       keggModel.mat is present in the same directory, the
+                       function reads the data from this file and ignores
+                       keggGenes.mat, keggMets.mat and keggRxns.mat
+   keepSpontaneous     include reactions labeled as "spontaneous" (optional,
+                       default true)
+   keepUndefinedStoich include reactions in the form n A <=> n+1 A. These
+                       will be dealt with as two separate metabolites
+                       (optional, default true)
+   keepIncomplete      include reactions which have been labelled as
+                       "incomplete", "erroneous" or "unclear" (optional,
+                       default true)
+   keepGeneral         include reactions which have been labelled as
+                       "general reaction". These are reactions on the form
+                       "an aldehyde <=> an alcohol", and are therefore
+                       unsuited for modelling purposes. Note that not all
+                       reactions have this type of annotation, and the
+                       script will therefore not be able to remove all
+                       such reactions (optional, default false)
+
+   Output:
+   model               a model structure generated from the database. All
+                       reactions and the metabolites used in them will be
+                       added
+   KOModel             a model structure representing the KEGG Orthology
+                       ids and their associated genes. The KO ids are
+                       saved as reactions
+
+   NOTE: The model output from getModelFromKEGG can be used as template
+   for fillGaps. In that case, ensure that the genes and rxnGeneMat fields
+   are removed before parsing: model=rmfield(model,'genes'), etc.
+
+ Usage: [model,KOModel]=getModelFromKEGG(keggPath,keepSpontaneous,...
+    keepUndefinedStoich,keepIncomplete,keepGeneral)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 function [model,KOModel]=getModelFromKEGG(keggPath,keepSpontaneous,...
+0002     keepUndefinedStoich,keepIncomplete,keepGeneral)
+0003 % getModelFromKEGG
+0004 %   Retrieves information stored in KEGG database and generates a model
+0005 %
+0006 %   Input:
+0007 %   keggPath            if keggGenes.mat, keggMets.mat, keggPhylDist.mat or
+0008 %                       keggRxns.mat are not in the RAVEN/external/kegg
+0009 %                       directory, this function will attempt to read data
+0010 %                       from a local FTP dump of the KEGG database.
+0011 %                       keggPath is the path to the root of this database
+0012 %                       (optional, default 'RAVEN/external/kegg'). If
+0013 %                       keggModel.mat is present in the same directory, the
+0014 %                       function reads the data from this file and ignores
+0015 %                       keggGenes.mat, keggMets.mat and keggRxns.mat
+0016 %   keepSpontaneous     include reactions labeled as "spontaneous" (optional,
+0017 %                       default true)
+0018 %   keepUndefinedStoich include reactions in the form n A <=> n+1 A. These
+0019 %                       will be dealt with as two separate metabolites
+0020 %                       (optional, default true)
+0021 %   keepIncomplete      include reactions which have been labelled as
+0022 %                       "incomplete", "erroneous" or "unclear" (optional,
+0023 %                       default true)
+0024 %   keepGeneral         include reactions which have been labelled as
+0025 %                       "general reaction". These are reactions on the form
+0026 %                       "an aldehyde <=> an alcohol", and are therefore
+0027 %                       unsuited for modelling purposes. Note that not all
+0028 %                       reactions have this type of annotation, and the
+0029 %                       script will therefore not be able to remove all
+0030 %                       such reactions (optional, default false)
+0031 %
+0032 %   Output:
+0033 %   model               a model structure generated from the database. All
+0034 %                       reactions and the metabolites used in them will be
+0035 %                       added
+0036 %   KOModel             a model structure representing the KEGG Orthology
+0037 %                       ids and their associated genes. The KO ids are
+0038 %                       saved as reactions
+0039 %
+0040 %   NOTE: The model output from getModelFromKEGG can be used as template
+0041 %   for fillGaps. In that case, ensure that the genes and rxnGeneMat fields
+0042 %   are removed before parsing: model=rmfield(model,'genes'), etc.
+0043 %
+0044 % Usage: [model,KOModel]=getModelFromKEGG(keggPath,keepSpontaneous,...
+0045 %    keepUndefinedStoich,keepIncomplete,keepGeneral)
+0046 
+0047 ravenPath=findRAVENroot();
+0048 
+0049 if nargin<1
+0050     keggPath=fullfile(ravenPath,'external','kegg');
+0051 else
+0052     keggPath=char(keggPath);
+0053 end
+0054 if nargin<2
+0055     keepSpontaneous=true;
+0056 end
+0057 if nargin<3
+0058     keepUndefinedStoich=true;
+0059 end
+0060 if nargin<4
+0061     keepIncomplete=true;
+0062 end
+0063 if nargin<5
+0064     keepGeneral=false;
+0065 end
+0066 
+0067 modelFile=fullfile(ravenPath,'external','kegg','keggModel.mat');
+0068 if exist(modelFile, 'file') && isNewestFile(ravenPath)
+0069     fprintf(['Importing the global KEGG model from ' strrep(modelFile,'\','/') '... ']);
+0070     load(modelFile);
+0071     fprintf('COMPLETE\n');
+0072 else
+0073     fprintf(['NOTE: The file ' strrep(modelFile,'\','/') ' does not exist or is out-of-date and therefore will be (re)generated\n']);
+0074     %First get all reactions
+0075     [model,isSpontaneous,isUndefinedStoich,isIncomplete,isGeneral]=getRxnsFromKEGG(keggPath);
+0076     
+0077     %Get the KO ids that are associated with any of the reactions. They
+0078     %will be used later on to create a rxn-gene matrix
+0079     KOs=cell(numel(model.rxns)*2,1);
+0080     %Make room for two KO ids per reaction
+0081     
+0082     addToIndex=1;
+0083     %Add all KO ids that are used
+0084     for i=1:numel(model.rxns)
+0085         if isstruct(model.rxnMiriams{i})
+0086             for j=1:numel(model.rxnMiriams{i}.name)
+0087                 if strcmpi('kegg.orthology',model.rxnMiriams{i}.name{j})
+0088                     %Add the KO id
+0089                     KOs(addToIndex)=model.rxnMiriams{i}.value(j);
+0090                     addToIndex=addToIndex+1;
+0091                 end
+0092             end
+0093         end
+0094     end
+0095     
+0096     KOs=KOs(1:addToIndex-1);
+0097     KOs=unique(KOs);
+0098     
+0099     %Get all genes from any organism in KEGG that is associated with any of
+0100     %the KOs
+0101     KOModel=getGenesFromKEGG(keggPath,KOs);
+0102     
+0103     fprintf('Pruning the global KEGG model from the partially annotated, lumped KEGG Orthology entries... ')
+0104     model.genes=KOModel.genes;
+0105     
+0106     %It can be that there are KOs from the reactions that have no database
+0107     %entry. These are (as far as I have seen) lumped versions of other KOs
+0108     %and should be removed
+0109     KOsToRemove=setdiff(KOs, KOModel.rxns);
+0110     
+0111     %Loop through all reactions and delete the KOs that were not found
+0112     for i=1:numel(model.rxns)
+0113         if isstruct(model.rxnMiriams{i})
+0114             for j=1:numel(model.rxnMiriams{i}.name)
+0115                 toDel=[];
+0116                 if strcmp(model.rxnMiriams{i}.name{j},'kegg.orthology')
+0117                     if ismember(model.rxnMiriams{i}.value{j},KOsToRemove)
+0118                         toDel=[toDel;j];
+0119                     end
+0120                 end
+0121             end
+0122             %Delete the KOs
+0123             if any(toDel)
+0124                 %If all posts are deleted, then delete the whole structure
+0125                 if numel(toDel)==j
+0126                     model.rxnMiriams{i}=[];
+0127                 else
+0128                     model.rxnMiriams{i}.name(toDel)=[];
+0129                     model.rxnMiriams{i}.value(toDel)=[];
+0130                 end
+0131             end
+0132         end
+0133     end
+0134     fprintf('COMPLETE\n');
+0135     
+0136     fprintf('Constructing the rxnGeneMat for the global KEGG model...   0%% complete');
+0137     %Create the rxnGeneMat for the reactions. This is simply done by
+0138     %merging the gene associations for all the involved KOs
+0139     r=zeros(10000000,1);
+0140     %Store the positions since it's slow to write to a sparse array in a
+0141     %loop
+0142     c=zeros(10000000,1);
+0143     counter=1;
+0144     for i=1:numel(model.rxns)
+0145         if isstruct(model.rxnMiriams{i})
+0146             I=strncmp('kegg.orthology',model.rxnMiriams{i}.name,18);
+0147             if any(I)
+0148                 [J, K]=ismember(model.rxnMiriams{i}.value(I),KOModel.rxns);
+0149                 %Find all gene indexes that correspond to any of these KOs
+0150                 [~, L]=find(KOModel.rxnGeneMat(K(J),:));
+0151                 if any(L)
+0152                     %Allocate room for more elements if needed
+0153                     if counter+numel(L)-1>=numel(r)
+0154                         r=[r;zeros(numel(r),1)];
+0155                         c=[c;zeros(numel(c),1)];
+0156                     end
+0157                     r(counter:counter+numel(L)-1)=ones(numel(L),1)*i;
+0158                     c(counter:counter+numel(L)-1)=L(:);
+0159                     counter=counter+numel(L);
+0160                 end
+0161             end
+0162         end
+0163         if rem(i-1,100) == 0
+0164             progress=pad(num2str(floor(i/numel(model.rxns)*100)),3,'left');
+0165             fprintf('\b\b\b\b\b\b\b\b\b\b\b\b\b%s%% complete',progress);
+0166         end
+0167     end
+0168     
+0169     model.rxnGeneMat=sparse(r(1:counter-1),c(1:counter-1),ones(counter-1,1));
+0170     if size(model.rxnGeneMat,1)~=numel(model.rxns) || size(model.rxnGeneMat,2)~=numel(KOModel.genes)
+0171         model.rxnGeneMat(numel(model.rxns),numel(KOModel.genes))=0;
+0172     end
+0173     fprintf('\b\b\b\b\b\b\b\b\b\b\b\b\bCOMPLETE\n');
+0174     
+0175     %Then get all metabolites
+0176     metModel=getMetsFromKEGG(keggPath);
+0177     
+0178     fprintf('Finalizing the global KEGG model... ');
+0179     %Add information about all metabolites to the model
+0180     [a, b]=ismember(model.mets,metModel.mets);
+0181     a=find(a);
+0182     b=b(a);
+0183     
+0184     if ~isfield(model,'metNames')
+0185         model.metNames=cell(numel(model.mets),1);
+0186         model.metNames(:)={''};
+0187     end
+0188     model.metNames(a)=metModel.metNames(b);
+0189     
+0190     if ~isfield(model,'metFormulas')
+0191         model.metFormulas=cell(numel(model.mets),1);
+0192         model.metFormulas(:)={''};
+0193     end
+0194     model.metFormulas(a)=metModel.metFormulas(b);
+0195     
+0196     if ~isfield(model,'inchis')
+0197         model.inchis=cell(numel(model.mets),1);
+0198         model.inchis(:)={''};
+0199     end
+0200     model.inchis(a)=metModel.inchis(b);
+0201     
+0202     if ~isfield(model,'metMiriams')
+0203         model.metMiriams=cell(numel(model.mets),1);
+0204     end
+0205     model.metMiriams(a)=metModel.metMiriams(b);
+0206     
+0207     %The composition should be loaded from InChIs when available
+0208     I=find(~cellfun(@isempty,model.inchis));
+0209     for i=1:numel(I)
+0210         S=regexp(model.inchis(I(i)),'/','split');
+0211         S=S{1};
+0212         if numel(S)>=2
+0213             %Don't copy if it doesn't look good
+0214             model.metFormulas(I(i))=S(2);
+0215         end
+0216     end
+0217     
+0218     %Put all metabolites in one compartment called 's' (for system). This
+0219     %is done just to be more compatible with the rest of the code
+0220     model.comps={'s'};
+0221     model.compNames={'System'};
+0222     model.metComps=ones(numel(model.mets),1);
+0223     
+0224     %If reactions with undefined stoichiometry are kept, then the
+0225     %corresponding metabolites will have ids such as "(n+1) C00001" and
+0226     %their names will be empty. These ids are not valid SBML identifiers
+0227     %and are therefore replaced with "undefined1, undefined2...". The
+0228     %former ids are stored as the new names
+0229     I=find(cellfun(@any,strfind(model.mets,'n')) | cellfun(@any,strfind(model.mets,'m')));
+0230     model.metNames(I)=model.mets(I);
+0231     repNums=1:numel(I);
+0232     repIDs=strcat('undefined_',cellfun(@num2str,num2cell(repNums(:)),'UniformOutput',false));
+0233     model.mets(I)=repIDs;
+0234     
+0235     %It could also be that the metabolite names are empty for some other
+0236     %reason. In that case, use the ID instead
+0237     I=cellfun(@isempty,model.metNames);
+0238     model.metNames(I)=model.mets(I);
+0239 
+0240     %Deafult LB and UB
+0241     model.annotation.defaultLB = -1000;
+0242     model.annotation.defaultUB = 1000;
+0243     
+0244     %Save the model structure
+0245     save(modelFile,'model','KOModel','isGeneral','isIncomplete','isUndefinedStoich','isSpontaneous');
+0246     fprintf('COMPLETE\n');
+0247 end
+0248 
+0249 %Delete reactions which are labeled as "incomplete", "erroneous",
+0250 %"unclear", "general reaction" or having undefined stoichiometry (depending
+0251 %on settings)
+0252 if keepSpontaneous==false
+0253     model=removeReactions(model,intersect(isSpontaneous,model.rxns),true,true);
+0254 end
+0255 if keepUndefinedStoich==false
+0256     model=removeReactions(model,intersect(isUndefinedStoich,model.rxns),true,true);
+0257 end
+0258 if keepIncomplete==false
+0259     model=removeReactions(model,intersect(isIncomplete,model.rxns),true,true);
+0260 end
+0261 if keepGeneral==false
+0262     model=removeReactions(model,intersect(isGeneral,model.rxns),true,true);
+0263 end
+0264 
+0265 end
+0266 
+0267 function output = isNewestFile(ravenPath)
+0268 %The ad hoc function, which checks whether keggModel.mat is the more
+0269 %recently modified than keggRxns.mat, keggGenes.mat and keggRxns.mat
+0270 modelFile=fullfile(ravenPath,'external','kegg','keggModel.mat');
+0271 rxnsFile=fullfile(ravenPath,'external','kegg','keggRxns.mat');
+0272 genesFile=fullfile(ravenPath,'external','kegg','keggGenes.mat');
+0273 metsFile=fullfile(ravenPath,'external','kegg','keggMets.mat');
+0274 if (getFileTime(modelFile)>getFileTime(rxnsFile))&&...
+0275         (getFileTime(modelFile)>getFileTime(genesFile))&&...
+0276         (getFileTime(modelFile)>getFileTime(metsFile))
+0277     output=1;
+0278 else
+0279     output=0;
+0280 end
+0281 end
+0282 
+0283 function modTime = getFileTime(fileName)
+0284 %Gets a last modification time for a particular file in datenum format that
+0285 %the numbers could be easily compared for different files
+0286 listing = dir(fileName);
+0287 assert(numel(listing) == 1, 'No such file: %s', fileName);
+0288 modTime = listing.datenum;
+0289 format long;
+0290 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/external/kegg/getPhylDist.html b/doc/external/kegg/getPhylDist.html new file mode 100644 index 000000000..226ba9b73 --- /dev/null +++ b/doc/external/kegg/getPhylDist.html @@ -0,0 +1,208 @@ + + + + Description of getPhylDist + + + + + + + + + +
Home > external > kegg > getPhylDist.m
+ + + +

getPhylDist +

+ +

PURPOSE ^

+
getPhylDist
+ +

SYNOPSIS ^

+
function phylDistStruct=getPhylDist(keggPath,onlyInKingdom)
+ +

DESCRIPTION ^

+
 getPhylDist
+   Calculates distance between species in KEGG based on systematic name
+
+   Input:
+   keggPath        if keggPhylDist.mat is not in the RAVEN\external\kegg
+                   directory, this function will attempt to read data from
+                   a local FTP dump of the KEGG database. keggPath is the
+                   path to the root of this database
+   onlyInKingdom   if true, it generates a distance matrix with distance
+                   Inf for organisms from another domains (Prokaryota,
+                   Eukaryota) (optional, default false)
+
+   Output:
+   phylDistStruct  a structure with a list of organism ids and a matrix
+                   that specifies their pairwise distances
+
+   NOTE: This simple metric is based on the number of nodes two organisms
+   are away from each other in KEGG
+
+ Usage: phylDistStruct=getPhylDist(keggPath,onlyInKingdom)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function phylDistStruct=getPhylDist(keggPath,onlyInKingdom)
+0002 % getPhylDist
+0003 %   Calculates distance between species in KEGG based on systematic name
+0004 %
+0005 %   Input:
+0006 %   keggPath        if keggPhylDist.mat is not in the RAVEN\external\kegg
+0007 %                   directory, this function will attempt to read data from
+0008 %                   a local FTP dump of the KEGG database. keggPath is the
+0009 %                   path to the root of this database
+0010 %   onlyInKingdom   if true, it generates a distance matrix with distance
+0011 %                   Inf for organisms from another domains (Prokaryota,
+0012 %                   Eukaryota) (optional, default false)
+0013 %
+0014 %   Output:
+0015 %   phylDistStruct  a structure with a list of organism ids and a matrix
+0016 %                   that specifies their pairwise distances
+0017 %
+0018 %   NOTE: This simple metric is based on the number of nodes two organisms
+0019 %   are away from each other in KEGG
+0020 %
+0021 % Usage: phylDistStruct=getPhylDist(keggPath,onlyInKingdom)
+0022 
+0023 if nargin<1
+0024     keggPath='RAVEN/external/kegg';
+0025 else
+0026     keggPath=char(keggPath);
+0027 end
+0028 if nargin<2
+0029     onlyInKingdom=false;
+0030 end
+0031 
+0032 %Check if the reactions have been parsed before and saved. If so, load the
+0033 %model
+0034 ravenPath=findRAVENroot();
+0035 distFile=fullfile(ravenPath,'external','kegg','keggPhylDist.mat');
+0036 if exist(distFile, 'file')
+0037     fprintf(['Importing the KEGG phylogenetic distance matrix from ' strrep(distFile,'\','/') '... ']);
+0038     load(distFile);
+0039     fprintf('COMPLETE\n');
+0040 else
+0041     fprintf(['Cannot locate ' strrep(distFile,'\','/') '\n']);
+0042     if ~isfile(fullfile(keggPath,'taxonomy'))
+0043         EM=fprintf(['The file ''taxonomy'' cannot be located at ' strrep(keggPath,'\','/') '/ and should be downloaded from the KEGG FTP.\n']);
+0044         dispEM(EM);
+0045     else
+0046         fprintf('Generating keggPhylDist.mat file... ');
+0047         %Open the file that describes the naming of the species
+0048         fid = fopen(fullfile(keggPath,'taxonomy'), 'r');
+0049         
+0050         phylDistStruct.ids={};
+0051         phylDistStruct.names={};
+0052         
+0053         %Keeps the categories for each organism
+0054         orgCat={};
+0055         
+0056         currentCat={};
+0057         %Keeps track of the current category
+0058         
+0059         depth=0;
+0060         %Keeps track of the current tree depth
+0061         
+0062         %Loop through the file
+0063         orgCounter=0;
+0064         while 1
+0065             %Get the next line
+0066             tline = fgetl(fid);
+0067             
+0068             %Abort at end of file
+0069             if ~ischar(tline)
+0070                 break;
+0071             end
+0072             
+0073             if any(tline)
+0074                 %Check if it's a new category
+0075                 if tline(1)=='#'
+0076                     %Find the first space (=depth +1)
+0077                     sPos=strfind(tline,' ')-1;
+0078                     %Should always exist
+0079                     
+0080                     sPos=sPos(1);
+0081                     
+0082                     %If we have stepped back one step in the tree
+0083                     if sPos<depth
+0084                         currentCat=currentCat(1:sPos);
+0085                     end
+0086                     depth=sPos;
+0087                     
+0088                     currentCat{depth}=tline(sPos+2:end);
+0089                 else
+0090                     orgCounter=orgCounter+1;
+0091                     %It is an organism Get the id between first and second
+0092                     %white space
+0093                     sPos=find(isstrprop(tline, 'wspace'));
+0094                     %Should always exist
+0095                     
+0096                     phylDistStruct.ids{orgCounter}=tline(sPos(1)+1:sPos(2)-1);
+0097                     phylDistStruct.names{orgCounter}=tline(sPos(3)+1:end);
+0098                     orgCat{orgCounter}=currentCat;
+0099                 end
+0100             end
+0101         end
+0102         %Generate a distance matrix (very straight forward here, not neat)
+0103         phylDistStruct.distMat=zeros(numel(phylDistStruct.ids));
+0104         phylDistStructOnlyInKingdom.distMat=zeros(numel(phylDistStruct.ids));
+0105         phylDistStructOnlyInKingdom.ids=phylDistStruct.ids;
+0106         for i=1:numel(phylDistStruct.ids)
+0107             for j=1:numel(phylDistStruct.ids)
+0108                 if ~strcmp(orgCat{i}(1),orgCat{j}(1))
+0109                     phylDistStructOnlyInKingdom.distMat(i,j)=Inf;
+0110                 end
+0111                 %Calculate the distance between then
+0112                 dist=numel(orgCat{i})-numel(orgCat{j});
+0113                 if dist>0
+0114                     aCat=orgCat{i}(1:end-dist);
+0115                 else
+0116                     aCat=orgCat{i};
+0117                 end
+0118                 if dist<0
+0119                     bCat=orgCat{j}(1:end+dist);
+0120                 else
+0121                     bCat=orgCat{j};
+0122                 end
+0123                 
+0124                 %Loop through the categories and stop when they are the
+0125                 %same
+0126                 for k=numel(aCat):-1:1
+0127                     if strcmp(aCat{k},bCat{k})
+0128                         break;
+0129                     end
+0130                 end
+0131                 phylDistStruct.distMat(i,j)=dist+numel(aCat)-k;
+0132             end
+0133         end
+0134         %Save the structure
+0135         save(distFile,'phylDistStruct','phylDistStructOnlyInKingdom');
+0136         fprintf('COMPLETE\n');
+0137     end
+0138 end
+0139 if onlyInKingdom==true
+0140     phylDistStruct=phylDistStructOnlyInKingdom;
+0141 end
+0142 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/external/kegg/getRxnsFromKEGG.html b/doc/external/kegg/getRxnsFromKEGG.html new file mode 100644 index 000000000..f419f5d0f --- /dev/null +++ b/doc/external/kegg/getRxnsFromKEGG.html @@ -0,0 +1,620 @@ + + + + Description of getRxnsFromKEGG + + + + + + + + + +
Home > external > kegg > getRxnsFromKEGG.m
+ + + +

getRxnsFromKEGG +

+ +

PURPOSE ^

+
getRxnsFromKEGG
+ +

SYNOPSIS ^

+
function [model,isSpontaneous,isUndefinedStoich,isIncomplete,isGeneral]=getRxnsFromKEGG(keggPath)
+ +

DESCRIPTION ^

+
 getRxnsFromKEGG
+   Retrieves information on all reactions stored in KEGG database
+
+   Input:
+   keggPath            if keggRxns.mat is not in the RAVEN\external\kegg
+                       directory, this function will attempt to read data
+                       from a local FTP dump of the KEGG database.
+                       keggPath is the path to the root of this database
+
+   Output:
+   model               a model structure generated from the database. The
+                       following fields are filled
+       id                  'KEGG'
+       name         'Automatically generated from KEGG database'
+       rxns                KEGG reaction ids
+       rxnNames            Name for each reaction entry
+       mets                KEGG compound ids. If the equations use
+                           stoichiometry such as ID(n+1) then the whole
+                           expression is saved as the id
+       eccodes             Corresponding ec-number if available
+       rxnMiriams          Contains reaction specific information such as
+                           KO id and pathways that the reaction is
+                           associated to
+       S                   Stoichiometric matrix
+       lb                  -1000 for all reactions
+       ub                  1000 for all reactions
+       rev                 1 for reversible and 0 for irreversible. For
+                           reactions present in pathway maps the
+                           reversibility is taken from there
+       b                   0 for all metabolites
+   isSpontaneous       a cell array with the reactions labelled as
+                       "spontaneous"
+   isUndefinedStoich    a cell array with the reactions labelled as with
+                       undefined stoichiometry
+   isIncomplete        a cell array with the reactions labelled as
+                       "incomplete", "erroneous" or "unclear"
+   isGeneral           a cell array with the reactions labelled as
+                       "general reaction"
+
+   NOTE: Reactions on the form A <=> A + B will not be loaded. If the file
+   keggRxns.mat is in the RAVEN/external/kegg directory it will be loaded
+   instead of parsing of the KEGG files. If it does not exist it will be
+   saved after parsing of the KEGG files. In general, you should remove
+   the keggRxns.mat file along with other KEGG mat files if you want to
+   rebuild the model structure from a newer version of KEGG.
+
+ Usage: [model,isSpontaneous,isUndefinedStoich,isIncomplete,...
+    isGeneral]=getRxnsFromKEGG(keggPath)
+
+ NOTE: This is how one entry looks in the file
+
+ ENTRY       R00010                      Reaction
+ NAME        alpha,alpha-trehalose glucohydrolase
+ DEFINITION  alpha,alpha-Trehalose + H2O <=> 2 D-Glucose
+ EQUATION    C01083 + C00001 <=> 2 C00031
+ REMARK      Same as: R06103
+ RCLASS      RC00049  C00031_C01083
+ ENZYME      3.2.1.28
+ PATHWAY     rn00500  Starch and sucrose metabolism
+             rn01100  Metabolic pathways
+ ORTHOLOGY   K01194  alpha,alpha-trehalase [EC:3.2.1.28]
+ DBLINKS     RHEA: 32678
+ ///
+
+ The file is not tab-delimited. Instead each label is 12 characters
+ (except for '///')
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function [model,isSpontaneous,isUndefinedStoich,isIncomplete,...
+0002     isGeneral]=getRxnsFromKEGG(keggPath)
+0003 % getRxnsFromKEGG
+0004 %   Retrieves information on all reactions stored in KEGG database
+0005 %
+0006 %   Input:
+0007 %   keggPath            if keggRxns.mat is not in the RAVEN\external\kegg
+0008 %                       directory, this function will attempt to read data
+0009 %                       from a local FTP dump of the KEGG database.
+0010 %                       keggPath is the path to the root of this database
+0011 %
+0012 %   Output:
+0013 %   model               a model structure generated from the database. The
+0014 %                       following fields are filled
+0015 %       id                  'KEGG'
+0016 %       name         'Automatically generated from KEGG database'
+0017 %       rxns                KEGG reaction ids
+0018 %       rxnNames            Name for each reaction entry
+0019 %       mets                KEGG compound ids. If the equations use
+0020 %                           stoichiometry such as ID(n+1) then the whole
+0021 %                           expression is saved as the id
+0022 %       eccodes             Corresponding ec-number if available
+0023 %       rxnMiriams          Contains reaction specific information such as
+0024 %                           KO id and pathways that the reaction is
+0025 %                           associated to
+0026 %       S                   Stoichiometric matrix
+0027 %       lb                  -1000 for all reactions
+0028 %       ub                  1000 for all reactions
+0029 %       rev                 1 for reversible and 0 for irreversible. For
+0030 %                           reactions present in pathway maps the
+0031 %                           reversibility is taken from there
+0032 %       b                   0 for all metabolites
+0033 %   isSpontaneous       a cell array with the reactions labelled as
+0034 %                       "spontaneous"
+0035 %   isUndefinedStoich    a cell array with the reactions labelled as with
+0036 %                       undefined stoichiometry
+0037 %   isIncomplete        a cell array with the reactions labelled as
+0038 %                       "incomplete", "erroneous" or "unclear"
+0039 %   isGeneral           a cell array with the reactions labelled as
+0040 %                       "general reaction"
+0041 %
+0042 %   NOTE: Reactions on the form A <=> A + B will not be loaded. If the file
+0043 %   keggRxns.mat is in the RAVEN/external/kegg directory it will be loaded
+0044 %   instead of parsing of the KEGG files. If it does not exist it will be
+0045 %   saved after parsing of the KEGG files. In general, you should remove
+0046 %   the keggRxns.mat file along with other KEGG mat files if you want to
+0047 %   rebuild the model structure from a newer version of KEGG.
+0048 %
+0049 % Usage: [model,isSpontaneous,isUndefinedStoich,isIncomplete,...
+0050 %    isGeneral]=getRxnsFromKEGG(keggPath)
+0051 %
+0052 % NOTE: This is how one entry looks in the file
+0053 %
+0054 % ENTRY       R00010                      Reaction
+0055 % NAME        alpha,alpha-trehalose glucohydrolase
+0056 % DEFINITION  alpha,alpha-Trehalose + H2O <=> 2 D-Glucose
+0057 % EQUATION    C01083 + C00001 <=> 2 C00031
+0058 % REMARK      Same as: R06103
+0059 % RCLASS      RC00049  C00031_C01083
+0060 % ENZYME      3.2.1.28
+0061 % PATHWAY     rn00500  Starch and sucrose metabolism
+0062 %             rn01100  Metabolic pathways
+0063 % ORTHOLOGY   K01194  alpha,alpha-trehalase [EC:3.2.1.28]
+0064 % DBLINKS     RHEA: 32678
+0065 % ///
+0066 %
+0067 % The file is not tab-delimited. Instead each label is 12 characters
+0068 % (except for '///')
+0069 %
+0070 
+0071 ravenPath=findRAVENroot();
+0072 
+0073 if nargin<1
+0074     keggPath=fullfile(ravenPath,'external','kegg');
+0075 else
+0076     keggPath=char(keggPath);
+0077 end
+0078 
+0079 %Check if the reactions have been parsed before and saved. If so, load the
+0080 %model
+0081 rxnsFile=fullfile(ravenPath,'external','kegg','keggRxns.mat');
+0082 if exist(rxnsFile, 'file')
+0083     fprintf(['Importing KEGG reactions from ' strrep(rxnsFile,'\','/') '... ']);
+0084     load(rxnsFile);
+0085 else
+0086     fprintf(['NOTE: Cannot locate ' strrep(rxnsFile,'\','/') ', it will therefore be generated from the local KEGG database\n']);
+0087     if ~isfile(fullfile(keggPath,'reaction')) || ~isfile(fullfile(keggPath,'reaction.lst')) || ~isfile(fullfile(keggPath,'reaction_mapformula.lst'))
+0088         EM=fprintf(['The files ''reaction'', ''reaction.lst'' and ''reaction_mapformula.lst'' cannot be located at ' strrep(keggPath,'\','/') '/ and should be downloaded from the KEGG FTP\n']);
+0089         dispEM(EM);
+0090     else
+0091         fprintf('Generating keggRxns.mat file... ');
+0092         %Add new functionality in the order specified in models
+0093         model.id='KEGG';
+0094         model.name='Automatically generated from KEGG database';
+0095         
+0096         %Preallocate memory for 15000 reactions
+0097         model.rxns=cell(15000,1);
+0098         model.rxnNames=cell(15000,1);
+0099         model.eccodes=cell(15000,1);
+0100         model.subSystems=cell(15000,1);
+0101         model.rxnMiriams=cell(15000,1);
+0102         model.rxnNotes=cell(15000,1);
+0103         equations=cell(15000,1);
+0104         %Temporarily store the equations
+0105         
+0106         isSpontaneous=false(15000,1);
+0107         isIncomplete=false(15000,1);
+0108         isGeneral=false(15000,1);
+0109 
+0110         %First load information on reaction ID, reaction name, KO, pathway,
+0111         %and ec-number
+0112         fid = fopen(fullfile(keggPath,'reaction'), 'r');
+0113         
+0114         %Keep track of how many reactions have been added
+0115         rxnCounter=0;
+0116         
+0117         %Loop through the file
+0118         orthology=false;
+0119         pathway=false;
+0120         module=false;
+0121         while 1
+0122             %Get the next line
+0123             tline = fgetl(fid);
+0124             
+0125             %Abort at end of file
+0126             if ~ischar(tline)
+0127                 break;
+0128             end
+0129             
+0130             %Skip '///'
+0131             if numel(tline)<12
+0132                 continue;
+0133             end
+0134             % Skip other lines with unused information
+0135             if strcmp(tline(1:5),'BRITE')
+0136                 pathway = false;
+0137                 continue;
+0138             end
+0139 
+0140             %Check if it's a new reaction
+0141             if strcmp(tline(1:12),'ENTRY       ')
+0142                 rxnCounter=rxnCounter+1;
+0143                 
+0144                 %Add empty strings where there should be such
+0145                 model.rxnNames{rxnCounter}='';
+0146                 model.eccodes{rxnCounter}='';
+0147                 %model.subSystems{rxnCounter}={''}; %remain empty cell
+0148                 model.rxnNotes{rxnCounter}='';
+0149                 equations{rxnCounter}='';
+0150                 
+0151                 %Add reaction ID (always 6 characters)
+0152                 model.rxns{rxnCounter}=tline(13:18);
+0153                 orthology=false;
+0154                 pathway=false;
+0155                 module=false;
+0156                 
+0157                 %Add KEGG reaction ID miriam
+0158                 tempStruct=model.rxnMiriams{rxnCounter};
+0159                 tempStruct.name{1,1}='kegg.reaction';
+0160                 tempStruct.value{1,1}=tline(13:18);
+0161                 model.rxnMiriams{rxnCounter}=tempStruct;
+0162             end
+0163             
+0164             %Add name
+0165             if strcmp(tline(1:12),'NAME        ')
+0166                 model.rxnNames{rxnCounter}=tline(13:end);
+0167             end
+0168             
+0169             %Add whether the comment includes "incomplete", "erroneous" or
+0170             %"unclear"
+0171             if strcmp(tline(1:12),'COMMENT     ')
+0172                 %Read all text until '///', 'RPAIR', 'ENZYME', 'PATHWAY' or 'RCLASS'
+0173                 commentText=tline(13:end);
+0174                 while 1
+0175                     tline = fgetl(fid);
+0176                     if ~strcmp(tline(1:3),'///') && ~strcmp(tline(1:3),'RPA') && ~strcmp(tline(1:3),'ENZ') && ~strcmp(tline(1:3),'PAT') && ~strcmp(tline(1:3),'RCL')
+0177                         commentText=[commentText ' ' strtrim(tline)];
+0178                     else
+0179                         break;
+0180                     end
+0181                 end
+0182                 if any(regexpi(commentText,'SPONTANEOUS'))
+0183                     %It should start this way
+0184                     isSpontaneous(rxnCounter)=true;
+0185                 end
+0186                 if any(regexpi(commentText,'INCOMPLETE')) || any(regexpi(commentText,'ERRONEOUS')) || any(regexpi(commentText,'UNCLEAR'))
+0187                     isIncomplete(rxnCounter)=true;
+0188                 end
+0189                 if any(regexpi(commentText,'GENERAL REACTION'))
+0190                     %It should start this way
+0191                     isGeneral(rxnCounter)=true;
+0192                 end
+0193                 
+0194                 %Go to next iteration if it is '///'
+0195                 if numel(tline)<12
+0196                     continue;
+0197                 end
+0198             end
+0199             
+0200             %Add ec-number
+0201             if strcmp(tline(1:12),'ENZYME      ')
+0202                 model.eccodes{rxnCounter}=tline(13:end);
+0203                 model.eccodes{rxnCounter}=deblank(model.eccodes{rxnCounter});
+0204                 model.eccodes{rxnCounter}=regexprep(model.eccodes{rxnCounter},'\s+',';');
+0205             end
+0206             if numel(tline)>8
+0207                 if strcmp(tline(1:9),'REFERENCE')
+0208                     pathway=false;
+0209                     orthology=false;
+0210                 end
+0211             end
+0212             
+0213             %Add module ids
+0214             if numel(tline)>18
+0215                 if strcmp(tline(1:12),'MODULE      ') || module==true
+0216                     pathway=false;
+0217                     orthology=false;
+0218                     if isstruct(model.rxnMiriams{rxnCounter})
+0219                         addToIndex=numel(model.rxnMiriams{rxnCounter}.name)+1;
+0220                     else
+0221                         addToIndex=1;
+0222                     end
+0223                     tempStruct=model.rxnMiriams{rxnCounter};
+0224                     tempStruct.name{addToIndex,1}='kegg.module';
+0225                     tempStruct.value{addToIndex,1}=tline(13:18);
+0226                     model.rxnMiriams{rxnCounter}=tempStruct;
+0227                 end
+0228             end
+0229             
+0230             %Add RHEA id
+0231             if numel(tline)>18
+0232                 if strcmp(tline(1:18),'DBLINKS     RHEA: ')
+0233                     pathway=false;
+0234                     orthology=false;
+0235                     module=false;
+0236                     if isstruct(model.rxnMiriams{rxnCounter})
+0237                         addToIndex=numel(model.rxnMiriams{rxnCounter}.name)+1;
+0238                     else
+0239                         addToIndex=1;
+0240                     end
+0241                     tempStruct=model.rxnMiriams{rxnCounter};
+0242                     tempStruct.name{addToIndex,1}='rhea';
+0243                     tempStruct.value{addToIndex,1}=tline(19:end);
+0244                     model.rxnMiriams{rxnCounter}=tempStruct;
+0245                 end
+0246             end
+0247             
+0248             %Add KO-ids
+0249             if numel(tline)>16
+0250                 if strcmp(tline(1:16),'ORTHOLOGY   KO: ') || strcmp(tline(1:16),'            KO: ') || strcmp(tline(1:12),'ORTHOLOGY   ') || orthology==true
+0251                     pathway=false;
+0252                     module=false;
+0253                     %Check if KO has been added already (each reaction may
+0254                     %belong to several)
+0255                     if isstruct(model.rxnMiriams{rxnCounter})
+0256                         addToIndex=numel(model.rxnMiriams{rxnCounter}.name)+1;
+0257                     else
+0258                         addToIndex=1;
+0259                     end
+0260                     
+0261                     tempStruct=model.rxnMiriams{rxnCounter};
+0262                     tempStruct.name{addToIndex,1}='kegg.orthology';
+0263                     if strcmp(tline(13:16),'KO:')
+0264                         %This is in the old version
+0265                         tempStruct.value{addToIndex,1}=tline(17:22);
+0266                     else
+0267                         %This means that it found one KO in the new format
+0268                         %and that subsequent lines might be other KOs
+0269                         orthology=true;
+0270                         tempStruct.value{addToIndex,1}=tline(13:18);
+0271                     end
+0272                     model.rxnMiriams{rxnCounter}=tempStruct;
+0273                 end
+0274             end
+0275             
+0276             %Add pathways
+0277             if numel(tline)>18
+0278                 if strcmp(tline(1:18),'PATHWAY     PATH: ') || strcmp(tline(1:18),'            PATH: ') || strcmp(tline(1:12),'PATHWAY     ') || pathway==true
+0279                     orthology=false;
+0280                     module=false;
+0281                     %Check if annotation has been added already
+0282                     if isstruct(model.rxnMiriams{rxnCounter})
+0283                         addToIndex=numel(model.rxnMiriams{rxnCounter}.name)+1;
+0284                     else
+0285                         addToIndex=1;
+0286                     end
+0287                     
+0288                     tempStruct=model.rxnMiriams{rxnCounter};
+0289                     tempStruct.name{addToIndex,1}='kegg.pathway';
+0290                     %If it is the old version
+0291                     if strcmp(tline(14:17),'PATH:')
+0292                         tempStruct.value{addToIndex,1}=tline(19:25);
+0293                     else
+0294                         %If it is the new version
+0295                         tempStruct.value{addToIndex,1}=tline(13:19);
+0296                         pathway=true;
+0297                     end
+0298                     
+0299                     %Do not save global or overview pathways. The ids for
+0300                     %such pathways begin with rn011 or rn012
+0301                     if ~strcmp('rn011',tempStruct.value{addToIndex,1}(1:5)) && ~strcmp('rn012',tempStruct.value{addToIndex,1}(1:5))
+0302                         model.rxnMiriams{rxnCounter}=tempStruct;
+0303                         
+0304                         %Also save the subSystems names. For the old KEGG
+0305                         %format, only the first mentioned subsystem is
+0306                         %picked. Use the newer KEGG format to fetch all the
+0307                         %subsystems
+0308                         if strcmp(tline(14:17),'PATH:')
+0309                             %The old format
+0310                             model.subSystems{rxnCounter}=tline(28:end);
+0311                         else
+0312                             %The new format
+0313                             model.subSystems{rxnCounter,1}{numel(model.subSystems{rxnCounter,1})+1,1}=tline(22:end);
+0314                         end
+0315                     end
+0316                 end
+0317             end
+0318         end
+0319         
+0320         %Close the file
+0321         fclose(fid);
+0322         
+0323         %This is done here since the the indexes won't match since some
+0324         %reactions are removed along the way
+0325         isIncomplete=model.rxns(isIncomplete);
+0326         isGeneral=model.rxns(isGeneral);
+0327         isSpontaneous=model.rxns(isSpontaneous);
+0328 
+0329         %If too much space was allocated, shrink the model
+0330         model.rxns=model.rxns(1:rxnCounter);
+0331         model.rxnNames=model.rxnNames(1:rxnCounter);
+0332         model.eccodes=model.eccodes(1:rxnCounter);
+0333         equations=equations(1:rxnCounter);
+0334         model.rxnMiriams=model.rxnMiriams(1:rxnCounter);
+0335         model.rxnNotes=model.rxnNotes(1:rxnCounter);
+0336         model.subSystems=model.subSystems(1:rxnCounter);
+0337         
+0338         emptySubSys = cellfun(@isempty,model.subSystems);
+0339         model.subSystems(emptySubSys) = {{''}};
+0340 
+0341         %Then load the equations from another file. This is because the
+0342         %equations are easier to retrieve from there
+0343         
+0344         %The format is rxnID: equation The reactions should have been
+0345         %loaded in the exact same order
+0346         fid = fopen(fullfile(keggPath,'reaction.lst'), 'r');
+0347         
+0348         %Loop through the file
+0349         for i=1:rxnCounter
+0350             %Get the next line
+0351             tline = fgetl(fid);
+0352             
+0353             equations{i}=tline(9:end);
+0354         end
+0355         
+0356         %Close the file
+0357         fclose(fid);
+0358         
+0359         %Several equations may have two whitespaces between the last
+0360         %reactant and the reversible arrow sign. The number of whitespaces
+0361         %is thus reduced to one
+0362         equations = regexprep(equations,'  <=>', ' <=>');
+0363         
+0364         %Construct the S matrix and list of metabolites
+0365         [S, mets, badRxns]=constructS(equations);
+0366         model.S=S;
+0367         model.mets=mets;
+0368         
+0369         %There is some limited evidence for directionality in
+0370         %reaction_mapformula.lst. The information there concerns how the
+0371         %reactions are drawn in the KEGG maps. If a reaction is
+0372         %irreversible in the same direction for all maps, then I consider
+0373         %is irreversible, otherwise reversible. Also, not all reactions are
+0374         %present in the maps, so not all will have directionality. They
+0375         %will be considered to be reversible
+0376         
+0377         %The format is R00005: 00330: C01010 => C00011 Generate a
+0378         %reversibility structure with the fields: *rxns: reaction ids
+0379         %*product: one met id that is a product. This is because the
+0380         %*reactions might be written in another direction compared to in
+0381         % the reactions.lst file
+0382         %*rev: 1 if reversible, otherwise 0
+0383         reversibility.rxns={};
+0384         reversibility.product={};
+0385         reversibility.rev=[];
+0386         
+0387         fid = fopen(fullfile(keggPath,'reaction_mapformula.lst'), 'r');
+0388         while 1
+0389             %Get the next line
+0390             tline = fgetl(fid);
+0391             
+0392             %Abort at end of file
+0393             if ~ischar(tline)
+0394                 break;
+0395             end
+0396             
+0397             rxn=tline(1:6);
+0398             prod=tline(end-5:end);
+0399             rev=any(strfind(tline,'<=>'));
+0400             if isempty(reversibility.rxns)
+0401                 reversibility.rxns{1}=rxn;
+0402                 reversibility.product{1}=prod;
+0403                 reversibility.rev(1)=rev;
+0404             elseif strcmp(reversibility.rxns(end),rxn)
+0405                 %Check if the reaction was added before. It's an ordered
+0406                 %list, so only check the last element If it's reversible in
+0407                 %the new reaction or reversible in the old reaction then
+0408                 %set (keep) to be reversible
+0409                 if rev==1 || reversibility.rev(end)==1
+0410                     reversibility.rev(end)=1;
+0411                 else
+0412                     %This means that the reaction was already loaded, that
+0413                     %it was irreversible before and irreversible in the new
+0414                     %reaction. However, it could be that they are written
+0415                     %in diferent directions. If the product differ, then
+0416                     %set to be reversible. This assumes that the reactions
+0417                     %are written with the same metabolite as the last one
+0418                     %if they are in the same direction
+0419                     if ~strcmp(prod,reversibility.product(end))
+0420                         reversibility.rev(end)=1;
+0421                     end
+0422                 end
+0423             else
+0424                 reversibility.rxns=[reversibility.rxns;rxn];
+0425                 reversibility.product=[reversibility.product;prod];
+0426                 reversibility.rev=[reversibility.rev;rev];
+0427             end
+0428         end
+0429         fclose(fid);
+0430         
+0431         %Update the reversibility
+0432         model.rev=ones(rxnCounter,1);
+0433         %Match the reaction ids
+0434         irrevIDs=find(reversibility.rev==0);
+0435         [~, I]=ismember(reversibility.rxns(irrevIDs),model.rxns);
+0436         [~, prodMetIDs]=ismember(reversibility.product(irrevIDs),model.mets);
+0437         model.rev(I)=0;
+0438         
+0439         %See if the reactions are written in the same order in model.S
+0440         linearInd=sub2ind(size(model.S), prodMetIDs, I);
+0441         changeOrder=I(model.S(linearInd)<0);
+0442         %Change the order of these reactions
+0443         model.S(:,changeOrder)=model.S(:,changeOrder).*-1;
+0444         
+0445         %Add some stuff to get a correct model structure
+0446         model.ub=ones(rxnCounter,1)*1000;
+0447         model.lb=model.rev*-1000;
+0448         model.c=zeros(rxnCounter,1);
+0449         model.b=zeros(numel(model.mets),1);
+0450         model=removeReactions(model,badRxns,true,true);
+0451         
+0452         %Identify reactions with undefined stoichiometry. Such
+0453         %reactions involve metabolites with an ID containing the letter "n"
+0454         %or "m"
+0455         I=cellfun(@any,strfind(model.mets,'n')) | cellfun(@any,strfind(model.mets,'m'));
+0456         [~, J]=find(model.S(I,:));
+0457         isUndefinedStoich=model.rxns(unique(J));   
+0458         %Sort model that metabolites with undefined stoichiometry would
+0459         %appear in the end of metabolites list
+0460         metList=[model.mets(~I);model.mets(I)];
+0461         [~,metIndexes]=ismember(metList,model.mets);
+0462         model=permuteModel(model,metIndexes,'mets');
+0463         
+0464         %Sort model that i) spontaneous, ii) with undefined
+0465         %stoichiometry, iii) incomplete and iv) general reactions would bve
+0466         %ranked in the end of the model
+0467         endRxnList=unique([model.rxns(ismember(model.rxns,isSpontaneous));model.rxns(ismember(model.rxns,isUndefinedStoich));model.rxns(ismember(model.rxns,isIncomplete));model.rxns(ismember(model.rxns,isGeneral))],'stable');
+0468         rxnList=[model.rxns(~ismember(model.rxns,endRxnList));endRxnList];
+0469         [~,rxnIndexes]=ismember(rxnList,model.rxns);
+0470         model=permuteModel(model,rxnIndexes,'rxns');
+0471         
+0472         %Add information in rxnNotes, whether reaction belongs to any of
+0473         %type i-iv mentioned a few lines above
+0474         for i=(numel(rxnList)-numel(endRxnList)+1):numel(model.rxns)
+0475             if ismember(model.rxns(i),isSpontaneous)
+0476                 model.rxnNotes(i)=strcat(model.rxnNotes(i),'Spontaneous');
+0477             end
+0478             if ismember(model.rxns(i),isUndefinedStoich)
+0479                 if isempty(model.rxnNotes{i})
+0480                     model.rxnNotes(i)=strcat(model.rxnNotes(i),'With undefined stoichiometry');
+0481                 else
+0482                     model.rxnNotes(i)=strcat(model.rxnNotes(i),', with undefined stoichiometry');
+0483                 end
+0484             end
+0485             if ismember(model.rxns(i),isIncomplete)
+0486                 if isempty(model.rxnNotes{i})
+0487                     model.rxnNotes(i)=strcat(model.rxnNotes(i),'Incomplete');
+0488                 else
+0489                     model.rxnNotes(i)=strcat(model.rxnNotes(i),', incomplete');
+0490                 end
+0491             end
+0492             if ismember(model.rxns(i),isGeneral)
+0493                 if isempty(model.rxnNotes{i})
+0494                     model.rxnNotes(i)=strcat(model.rxnNotes(i),'General');
+0495                 else
+0496                     model.rxnNotes(i)=strcat(model.rxnNotes(i),', general');
+0497                 end
+0498             end
+0499             model.rxnNotes(i)=strcat(model.rxnNotes(i),' reaction');
+0500         end
+0501         
+0502         %Save the model structure
+0503         save(rxnsFile,'model','isGeneral','isIncomplete','isUndefinedStoich','isSpontaneous');
+0504     end
+0505 end
+0506 fprintf('COMPLETE\n');
+0507 
+0508 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/external/kegg/getWSLpath.html b/doc/external/kegg/getWSLpath.html new file mode 100644 index 000000000..a6bba443a --- /dev/null +++ b/doc/external/kegg/getWSLpath.html @@ -0,0 +1,83 @@ + + + + Description of getWSLpath + + + + + + + + + +
Home > external > kegg > getWSLpath.m
+ + + +

getWSLpath +

+ +

PURPOSE ^

+
getWSLpath
+ +

SYNOPSIS ^

+
function path=getWSLpath(path)
+ +

DESCRIPTION ^

+
 getWSLpath
+   Translate Windows-style path to its Unix WSL (Windows Subsystem for
+   Linux) equivalent.
+
+   Input:
+   path        string with directory of file path, in Windows-style (e.g.
+               'C:\Directory\')
+
+   Output:
+   path        string with directory of file path, in Unix style (e.g.
+               '/mnt/c/Directory/')
+
+   Uses the WSL function 'wslpath' to translate the path.
+
+ Usage: path=getWSLpath(path)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function path=getWSLpath(path)
+0002 % getWSLpath
+0003 %   Translate Windows-style path to its Unix WSL (Windows Subsystem for
+0004 %   Linux) equivalent.
+0005 %
+0006 %   Input:
+0007 %   path        string with directory of file path, in Windows-style (e.g.
+0008 %               'C:\Directory\')
+0009 %
+0010 %   Output:
+0011 %   path        string with directory of file path, in Unix style (e.g.
+0012 %               '/mnt/c/Directory/')
+0013 %
+0014 %   Uses the WSL function 'wslpath' to translate the path.
+0015 %
+0016 % Usage: path=getWSLpath(path)
+0017 [status,path]=system(['wsl wslpath ''' path '''']);
+0018 if status==-1
+0019     error('Cannot get access to Windows Subsystem for Linux, check your WSL installation')
+0020 end
+0021 path=path(1:end-1);% Remove final character (line-break)
+0022 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/external/kegg/index.html b/doc/external/kegg/index.html new file mode 100644 index 000000000..ee1961280 --- /dev/null +++ b/doc/external/kegg/index.html @@ -0,0 +1,31 @@ + + + + Index for Directory external\kegg + + + + + + + + + + +
< Master indexIndex for external\kegg >
+ +

Index for external\kegg

+ +

Matlab files in this directory:

+ +
 constructMultiFastaconstructMultiFasta
 getGenesFromKEGGgetGenesFromKEGG
 getKEGGModelForOrganismgetKEGGModelForOrganism
 getMetsFromKEGGgetMetsFromKEGG
 getModelFromKEGGgetModelFromKEGG
 getPhylDistgetPhylDist
 getRxnsFromKEGGgetRxnsFromKEGG
 getWSLpathgetWSLpath
+ +

Other Matlab-specific files in this directory:

+
    +
  • keggMets.mat
  • keggPhylDist.mat
  • keggRxns.mat
+ + +
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/external/makeFakeBlastStructure.html b/doc/external/makeFakeBlastStructure.html new file mode 100644 index 000000000..4dde45faf --- /dev/null +++ b/doc/external/makeFakeBlastStructure.html @@ -0,0 +1,129 @@ + + + + Description of makeFakeBlastStructure + + + + + + + + + +
Home > external > makeFakeBlastStructure.m
+ + + +

makeFakeBlastStructure +

+ +

PURPOSE ^

+
makeFakeBlastStructure
+ +

SYNOPSIS ^

+
function blastStructure=makeFakeBlastStructure(orthologList,sourceModelID,getModelFor)
+ +

DESCRIPTION ^

+
 makeFakeBlastStructure
+   Makes a fake blastStructure, that would normally be generated by
+   getBlast. This allows to feed a predefined list of orthologs to
+   getModelFromHomology while retaining the further use of that function.
+   For this function to work, it is crucial that the orthologList is a
+   cell array where the first column contains the genes from the source
+   organism, and the second column contains the genes from the target
+   organism
+  
+   orthologList        cell array of orthologous genes, where the first
+                       column contains the genes from the source organism,
+                       while the second column contains the genes from the
+                       target organism
+   sourceModelID       ID of the model that will be used as template, that
+                       contains the genes in the first column of
+                       orthologList
+   getModelFor         the name of the organism to build a model for,
+                       identical to the getModelFor parameter in the
+                       getModelFromHomology function
+
+   blastStructure      a fake blastStructure, where the evalue, identity
+                       and aligLen are set at extreme values, such that
+                       all orthologous pairs will pass the filter when
+                       running getModelFromHomology
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function blastStructure=makeFakeBlastStructure(orthologList,sourceModelID,getModelFor)
+0002 % makeFakeBlastStructure
+0003 %   Makes a fake blastStructure, that would normally be generated by
+0004 %   getBlast. This allows to feed a predefined list of orthologs to
+0005 %   getModelFromHomology while retaining the further use of that function.
+0006 %   For this function to work, it is crucial that the orthologList is a
+0007 %   cell array where the first column contains the genes from the source
+0008 %   organism, and the second column contains the genes from the target
+0009 %   organism
+0010 %
+0011 %   orthologList        cell array of orthologous genes, where the first
+0012 %                       column contains the genes from the source organism,
+0013 %                       while the second column contains the genes from the
+0014 %                       target organism
+0015 %   sourceModelID       ID of the model that will be used as template, that
+0016 %                       contains the genes in the first column of
+0017 %                       orthologList
+0018 %   getModelFor         the name of the organism to build a model for,
+0019 %                       identical to the getModelFor parameter in the
+0020 %                       getModelFromHomology function
+0021 %
+0022 %   blastStructure      a fake blastStructure, where the evalue, identity
+0023 %                       and aligLen are set at extreme values, such that
+0024 %                       all orthologous pairs will pass the filter when
+0025 %                       running getModelFromHomology
+0026 
+0027 if nargin<3
+0028     error('All three parameters should be set');
+0029 end
+0030 sourceModelID=char(sourceModelID);
+0031 getModelFor=char(getModelFor);
+0032 
+0033 % Check whether orthologList is a cell array, with two columns, and more
+0034 % than 10 rows
+0035 if (~iscell(orthologList) || ~(size(orthologList,2)==2) || ~(size(orthologList,1)>=10))
+0036     error('orthologList should be a cell array with two columns');
+0037 end
+0038 
+0039 blastStructure(1).fromId=sourceModelID;
+0040 blastStructure(1).toId=getModelFor;
+0041 blastStructure(1).fromGenes=orthologList(:,1);
+0042 blastStructure(1).toGenes=orthologList(:,2);
+0043 
+0044 blastStructure(2).fromId=getModelFor;
+0045 blastStructure(2).toId=sourceModelID;
+0046 blastStructure(2).fromGenes=orthologList(:,2);
+0047 blastStructure(2).toGenes=orthologList(:,1);
+0048 
+0049 blastStructure(1).evalue=zeros(size(orthologList,1),1);
+0050 blastStructure(2).evalue=zeros(size(orthologList,1),1);
+0051 blastStructure(1).identity(1:size(orthologList,1),1)=100;
+0052 blastStructure(2).identity(1:size(orthologList,1),1)=100;
+0053 blastStructure(1).aligLen(1:size(orthologList,1),1)=1000;
+0054 blastStructure(2).aligLen(1:size(orthologList,1),1)=1000;
+0055 blastStructure(1).bitscore(1:size(orthologList,1),1)=100;
+0056 blastStructure(2).bitscore(1:size(orthologList,1),1)=100;
+0057 blastStructure(1).ppos(1:size(orthologList,1),1)=100;
+0058 blastStructure(2).ppos(1:size(orthologList,1),1)=100;
+0059 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/external/metacyc/addSpontaneousRxns.html b/doc/external/metacyc/addSpontaneousRxns.html new file mode 100644 index 000000000..631689503 --- /dev/null +++ b/doc/external/metacyc/addSpontaneousRxns.html @@ -0,0 +1,157 @@ + + + + Description of addSpontaneousRxns + + + + + + + + + +
Home > external > metacyc > addSpontaneousRxns.m
+ + + +

addSpontaneousRxns +

+ +

PURPOSE ^

+
addSpontaneousRxns
+ +

SYNOPSIS ^

+
function [spontaneousRxnList, pathwayID]=addSpontaneousRxns(rxnList, metList)
+ +

DESCRIPTION ^

+
 addSpontaneousRxns
+   Retrieve spontaneous reactions based on the pathway-spontaneousRxn
+   associations curated by the MetaCyc database
+
+   Input:
+   rxnList              query list of reactions in cell array
+   metList              query list of metabolites in cell array
+
+   spontaneousRxnList   reterieved spontaneous reactions associated to
+                        the queried MetaCyc reactions and metabolites
+
+   Output:
+   pathwayID            the cell array of relevant pathways
+
+ Usage: spontaneousRxnList=addSpontaneousRxns(rxnList, metList)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function [spontaneousRxnList, pathwayID]=addSpontaneousRxns(rxnList, metList)
+0002 % addSpontaneousRxns
+0003 %   Retrieve spontaneous reactions based on the pathway-spontaneousRxn
+0004 %   associations curated by the MetaCyc database
+0005 %
+0006 %   Input:
+0007 %   rxnList              query list of reactions in cell array
+0008 %   metList              query list of metabolites in cell array
+0009 %
+0010 %   spontaneousRxnList   reterieved spontaneous reactions associated to
+0011 %                        the queried MetaCyc reactions and metabolites
+0012 %
+0013 %   Output:
+0014 %   pathwayID            the cell array of relevant pathways
+0015 %
+0016 % Usage: spontaneousRxnList=addSpontaneousRxns(rxnList, metList)
+0017 
+0018 metList=convertCharArray(metList);
+0019 rxnList=convertCharArray(rxnList);
+0020 rxnList=unique(rxnList);
+0021 
+0022 % Create the matrix of MetaCyc pathways and spontaneous reactions
+0023 load('metaCycRxns.mat');
+0024 pathways={};
+0025 for i=1:numel(metaCycRxns.rxns)
+0026     if ~isempty(metaCycRxns.pwys{i})
+0027         pathways=[pathways;transpose(strsplit(metaCycRxns.pwys{i},';'))];
+0028     end
+0029 end
+0030 pathways=unique(pathways);
+0031 
+0032 % Genearte the matirx, row: spontaneousRxns, column: pathways
+0033 sprxnPwyMat=zeros(numel(isSpontaneous),numel(pathways));
+0034 for i=1:numel(isSpontaneous)
+0035     [a, b]=ismember(isSpontaneous{i},metaCycRxns.rxns);
+0036     if ~isempty(metaCycRxns.pwys{b})
+0037         [crap, indexes]=ismember(strsplit(metaCycRxns.pwys{b},';'),pathways);
+0038         sprxnPwyMat(i,indexes)=1;
+0039     end
+0040 end
+0041 
+0042 % Go through the rxnList to obtain relevant pathways
+0043 pwys={};
+0044 for i=1:numel(rxnList)
+0045     [a, b]=ismember(rxnList{i},metaCycRxns.rxns);
+0046     if a && ~isempty(metaCycRxns.pwys{b})
+0047         pwys=[pwys;transpose(strsplit(metaCycRxns.pwys{b},';'))];
+0048     end
+0049 end
+0050 pwys=unique(pwys);
+0051 
+0052 % Get spontaneous reactions associated with the pathways
+0053 hits=[];
+0054 for i=1:numel(pwys)
+0055     [a, b]=ismember(pwys{i},pathways);
+0056     if ~isempty(find(sprxnPwyMat(:,b)))
+0057         hits=[hits;find(sprxnPwyMat(:,b))];
+0058     end
+0059 end
+0060 spontaneousRxnList=isSpontaneous(unique(hits));
+0061 
+0062 % Check if the reactants/products are included in metList
+0063 for i=1:numel(spontaneousRxnList)
+0064     [a, b]=ismember(spontaneousRxnList{i},metaCycRxns.rxns);
+0065     
+0066     %Obtain the reactants and products
+0067     reactants=all(ismember(metaCycRxns.mets(find(metaCycRxns.S(:,b)==-1)),metList));
+0068     products=all(ismember(metaCycRxns.mets(find(metaCycRxns.S(:,b)==1)),metList));
+0069     
+0070     %Either reactants or products should be present for reversible reaction
+0071     if metaCycRxns.rev(b)==1
+0072         if ~(reactants || products)
+0073             spontaneousRxnList{i}=[];
+0074         end
+0075         %Reactants should be present for irreversible reactions
+0076     else
+0077         if ~reactants
+0078             spontaneousRxnList{i}=[];
+0079         end
+0080     end
+0081 end
+0082 spontaneousRxnList=spontaneousRxnList(~cellfun(@isempty, spontaneousRxnList));
+0083 
+0084 % Remove the spontaneousRxns that have already been included
+0085 spontaneousRxnList=setdiff(spontaneousRxnList,rxnList);
+0086 
+0087 % Generate the cell array of relevant pathways
+0088 pathwayID=cell(numel(spontaneousRxnList),1);
+0089 for i=1:numel(spontaneousRxnList)
+0090     index=find(strcmp(spontaneousRxnList{i},isSpontaneous));
+0091     % locate the relevant pathways
+0092     relevantpwys=intersect(pathways(find(sprxnPwyMat(index,:))),pwys);
+0093     pathwayID{i}=strjoin(relevantpwys,';');
+0094 end
+0095 
+0096 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/external/metacyc/getEnzymesFromMetaCyc.html b/doc/external/metacyc/getEnzymesFromMetaCyc.html new file mode 100644 index 000000000..e1e221272 --- /dev/null +++ b/doc/external/metacyc/getEnzymesFromMetaCyc.html @@ -0,0 +1,366 @@ + + + + Description of getEnzymesFromMetaCyc + + + + + + + + + +
Home > external > metacyc > getEnzymesFromMetaCyc.m
+ + + +

getEnzymesFromMetaCyc +

+ +

PURPOSE ^

+
getEnzymesFromMetaCyc
+ +

SYNOPSIS ^

+
function metaCycEnzymes=getEnzymesFromMetaCyc(metacycPath)
+ +

DESCRIPTION ^

+
 getEnzymesFromMetaCyc
+    Retrieves all enzymes and reaction-enzyme association information in MetaCyc
+
+   Input:
+    metacycPath  if metaCycEnzymes.mat is not in the RAVEN\external\metacyc
+                directory, this function will attempt to build it by reading
+                info from a local dump of MetaCyc database, and metacycPath
+                is the path to the MetaCyc data files
+
+   Output:
+    model        a model structure generated from the database. The following
+                fields are filled
+                id:             'MetaCyc'
+                name:    'Automatically generated from MetaCyc database'
+                rxns:           Reaction id
+                rxnNames:       Reaction name
+                enzymes:        Enzyme id
+                enzrxns:        Enzymatic-reaction id
+                cplxs:          Enzyme complexes
+                cplxComp:       Subunit components of enzyme complexes
+                rxnEnzymeMat    A binary matrix that indicates association of a
+                                specific enzyme to the reactions it catalyze
+                version:        MetaCyc database version
+
+    If the file metaCycEnzymes.mat is in the RAVEN\external\metacyc directory
+    it will be loaded. Otherwise, it will be generated by parsing the MetaCyc
+    database files. In general, this metaCycEnzymes.mat file should be removed
+    and rebuilt when a newer version of MetaCyc is released.
+
+    Usage: model=getEnzymesFromMetaCyc(metacycPath)
+
+NOTE: This is how one entry looks in the files
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function metaCycEnzymes=getEnzymesFromMetaCyc(metacycPath)
+0002 % getEnzymesFromMetaCyc
+0003 %    Retrieves all enzymes and reaction-enzyme association information in MetaCyc
+0004 %
+0005 %   Input:
+0006 %    metacycPath  if metaCycEnzymes.mat is not in the RAVEN\external\metacyc
+0007 %                directory, this function will attempt to build it by reading
+0008 %                info from a local dump of MetaCyc database, and metacycPath
+0009 %                is the path to the MetaCyc data files
+0010 %
+0011 %   Output:
+0012 %    model        a model structure generated from the database. The following
+0013 %                fields are filled
+0014 %                id:             'MetaCyc'
+0015 %                name:    'Automatically generated from MetaCyc database'
+0016 %                rxns:           Reaction id
+0017 %                rxnNames:       Reaction name
+0018 %                enzymes:        Enzyme id
+0019 %                enzrxns:        Enzymatic-reaction id
+0020 %                cplxs:          Enzyme complexes
+0021 %                cplxComp:       Subunit components of enzyme complexes
+0022 %                rxnEnzymeMat    A binary matrix that indicates association of a
+0023 %                                specific enzyme to the reactions it catalyze
+0024 %                version:        MetaCyc database version
+0025 %
+0026 %    If the file metaCycEnzymes.mat is in the RAVEN\external\metacyc directory
+0027 %    it will be loaded. Otherwise, it will be generated by parsing the MetaCyc
+0028 %    database files. In general, this metaCycEnzymes.mat file should be removed
+0029 %    and rebuilt when a newer version of MetaCyc is released.
+0030 %
+0031 %    Usage: model=getEnzymesFromMetaCyc(metacycPath)
+0032 %
+0033 %NOTE: This is how one entry looks in the files
+0034 
+0035 %proteins.dat
+0036 % UNIQUE-ID - MONOMER-8570
+0037 % TYPES - Polypeptides
+0038 % COMMON-NAME - D-carnitine dehydrogenase subunit
+0039 % COMPONENT-OF - CPLX-5143
+0040 % MOLECULAR-WEIGHT-EXP - 23
+0041 % MOLECULAR-WEIGHT-KD - 23
+0042 % SPECIES - ORG-6256
+0043 % //
+0044 
+0045 %enzrxns.dat
+0046 % UNIQUE-ID - ENZRXN-14974
+0047 % TYPES - Enzymatic-Reactions
+0048 % COMMON-NAME - (1S,4R)-iso-dihydrocarvone monooxygenase
+0049 % BASIS-FOR-ASSIGNMENT - :MANUAL
+0050 % CITATIONS - 10769172:EV-EXP-IDA-PURIFIED-PROTEIN:3419689584:caspi
+0051 % COFACTORS - FAD
+0052 % ENZYME - MONOMER-13964
+0053 % PHYSIOLOGICALLY-RELEVANT? - T
+0054 % REACTION - RXN-9435
+0055 % REGULATED-BY - REG-12241
+0056 % REGULATED-BY - REG-12240
+0057 % TEMPERATURE-OPT - 35
+0058 
+0059 % A line that contains only '//' separates each object.
+0060 
+0061 if nargin<1
+0062     ravenPath=findRAVENroot();
+0063     metacycPath=fullfile(ravenPath,'external','metacyc');
+0064 else
+0065     metacycPath=char(metacycPath);
+0066 end
+0067 
+0068 %Check if the enzymatic proteins have been parsed before and saved. If so,
+0069 %load the model.
+0070 enzymesFile=fullfile(metacycPath,'metaCycEnzymes.mat');
+0071 metaCycProteinFile='proteins.dat';
+0072 metaCycEnzrxnsFile='enzrxns.dat';
+0073 
+0074 try
+0075     (['Importing MetaCyc enzymes and reaction-enzyme association from ' strrep(enzymesFile,'\','/') '... ']);
+0076     load(enzymesFile);
+0077     fprintf('done\n');
+0078 catch
+0079     fprintf(['Cannot locate ' strrep(enzymesFile,'\','/') '\nNow try to generate it from local MetaCyc data files...\n']);
+0080     if ~isfile(fullfile(metacycPath,metaCycProteinFile)) || ~isfile(fullfile(metacycPath,metaCycEnzrxnsFile))
+0081         EM=fprintf(['The files of enzymes or proteins cannot be located, and should be downloaded from MetaCyc.\n']);
+0082         dispEM(EM);
+0083     else
+0084         metaCycEnzymes.id='MetaCyc';
+0085         metaCycEnzymes.name='Automatically generated from MetaCyc database';
+0086         
+0087         %Reserve space for 10000 enzyme complexs
+0088         metaCycEnzymes.cplxs=cell(10000,1);
+0089         metaCycEnzymes.cplxComp=cell(10000,1);
+0090         metaCycEnzymes.enzymes=cell(50000,1);
+0091         
+0092         %Get the information of protein complexes and their components
+0093         nCplx=0;
+0094         enzymeCounter=0;
+0095         
+0096         fid = fopen(fullfile(metacycPath,metaCycProteinFile), 'r');
+0097         %Loop through the file
+0098         while 1
+0099             tline = fgetl(fid);
+0100             
+0101             %Abort at end of file
+0102             if ~ischar(tline)
+0103                 break;
+0104             end
+0105             
+0106             %Add Enzyme id
+0107             if numel(tline)>12 && strcmp(tline(1:12),'UNIQUE-ID - ')
+0108                 enzymeCounter=enzymeCounter+1;
+0109                 addMe=false;
+0110                 enzymeID=tline(13:end);
+0111                 metaCycEnzymes.enzymes{enzymeCounter}=enzymeID;
+0112             end
+0113             
+0114             %Check if enzyme complexes
+0115             if strcmp(tline(1:end),'TYPES - Protein-Complexes')
+0116                 nCplx=nCplx+1;
+0117                 nComp=0;
+0118                 
+0119                 %Reserve 100 subunits for each enzyme complex
+0120                 Comp.subunit=cell(100,1);
+0121                 metaCycEnzymes.cplxs{nCplx}=enzymeID;
+0122                 
+0123                 addMe=true;
+0124             end
+0125             
+0126             if numel(tline)>13 && strcmp(tline(1:13),'COMPONENTS - ')
+0127                 if addMe
+0128                     nComp=nComp+1;
+0129                     Comp.subunit{nComp}=tline(14:end);
+0130                 end
+0131             end
+0132             
+0133             if strcmp(tline(1:end),'//')
+0134                 if addMe
+0135                     Comp.subunit=Comp.subunit(1:nComp);
+0136                     metaCycEnzymes.cplxComp{nCplx}=Comp;
+0137                     addMe=false;
+0138                 end
+0139             end
+0140         end
+0141         %Close the file
+0142         fclose(fid);
+0143         
+0144         %If too much space was allocated, shrink the model
+0145         metaCycEnzymes.cplxs=metaCycEnzymes.cplxs(1:nCplx);
+0146         metaCycEnzymes.cplxComp=metaCycEnzymes.cplxComp(1:nCplx);
+0147         metaCycEnzymes.enzymes=metaCycEnzymes.enzymes(1:enzymeCounter);
+0148         
+0149         % Iteratively go through the components of each complex
+0150         for i=1:numel(metaCycEnzymes.cplxComp)
+0151             
+0152             %replace all complex-type components with their subunits
+0153             checkCplx=true;
+0154             while checkCplx
+0155                 x=0;
+0156                 mat=[]; %Matrix for component of protein-complexs
+0157                 for j=1:numel(metaCycEnzymes.cplxComp{i}.subunit)
+0158                     [a, b]=ismember(metaCycEnzymes.cplxComp{i}.subunit{j},metaCycEnzymes.cplxs);
+0159                     if a
+0160                         x=x+1;   %record this value j, and the cplx id b
+0161                         mat(x,:)=[j b];
+0162                     end
+0163                 end
+0164                 
+0165                 if isempty(mat)
+0166                     checkCplx=false; % No complexs found among components
+0167                 else
+0168                     %go through matrix JB
+0169                     for k=1:x
+0170                         %disp(metaCycEnzymes.cplxComp{i}.subunit{mat(k,1)});
+0171                         metaCycEnzymes.cplxComp{i}.subunit(mat(k,1))=[];
+0172                         metaCycEnzymes.cplxComp{i}.subunit=[metaCycEnzymes.cplxComp{i}.subunit; metaCycEnzymes.cplxComp{mat(k,2)}.subunit];
+0173                     end
+0174                 end
+0175                 
+0176             end
+0177             
+0178             % make sure the subunits are all included in the enzyme list
+0179             % since in one case subunit was not found in enzyme dump file
+0180             [a, b] = ismember(metaCycEnzymes.cplxComp{i}.subunit,metaCycEnzymes.enzymes);
+0181             if ~all(a)
+0182                 metaCycEnzymes.cplxComp{i}.subunit = metaCycEnzymes.enzymes(b(find(a)));
+0183             end
+0184         end
+0185         
+0186         %Preallocate space for 500000 enzymatic reactions
+0187         metaCycEnzymes.enzrxns=cell(50000,1);
+0188         metaCycEnzymes.rxns=cell(50000,1);
+0189         metaCycEnzymes.rxnNames=cell(50000,1);
+0190         metaCycEnzymes.commoname=cell(50000,1);
+0191         metaCycEnzymes.rxnEnzymeMat=sparse(50000,enzymeCounter); % row: rxn, column: enzymes
+0192         
+0193         %Load enzyme and reaction association information
+0194         fid = fopen(fullfile(metacycPath,metaCycEnzrxnsFile), 'r');
+0195         
+0196         %Keeps track of how many enzymes and reactions have been added
+0197         enzrxnCounter=0;
+0198         nRxn=0;
+0199         
+0200         %These contain the mapping between Reactions and Enzymes Loop
+0201         %through the file
+0202         while 1
+0203             tline = fgetl(fid);
+0204             
+0205             %Abort at end of file
+0206             if ~ischar(tline)
+0207                 break;
+0208             end
+0209 
+0210             % Get the version of MetaCyc database
+0211             if numel(tline)>11 && strcmp(tline(1:11),'# Version: ')
+0212                 metaCycEnzymes.version=tline(12:end);
+0213             end
+0214 
+0215             %Check if it is a new enzymatic reaction
+0216             if numel(tline)>12 && strcmp(tline(1:12),'UNIQUE-ID - ')
+0217                 enzrxnCounter=enzrxnCounter+1;
+0218                 metaCycEnzymes.enzrxns{enzrxnCounter}=tline(13:end);
+0219                 metaCycEnzymes.commoname{enzrxnCounter}='';
+0220             end
+0221             
+0222             %Add common name of enzymatic reactions
+0223             if numel(tline)>14 && strcmp(tline(1:14),'COMMON-NAME - ')
+0224                 metaCycEnzymes.commoname{enzrxnCounter}=tline(15:end);
+0225                 
+0226                 %Remove HTML symobls
+0227                 metaCycEnzymes.commoname{enzrxnCounter}=regexprep(metaCycEnzymes.commoname{enzrxnCounter},'<(\w+)>','');
+0228                 metaCycEnzymes.commoname{enzrxnCounter}=regexprep(metaCycEnzymes.commoname{enzrxnCounter},'</(\w+)>','');
+0229                 metaCycEnzymes.commoname{enzrxnCounter}=regexprep(metaCycEnzymes.commoname{enzrxnCounter},'[&;]','');
+0230             end
+0231             
+0232             % I add one cell array rxns for checking existing ones by
+0233             % ismember because I cannot manage field rxns in this function
+0234             
+0235             %Add enzyme name
+0236             if numel(tline)>9 && strcmp(tline(1:9),'ENZYME - ')
+0237                 
+0238                 %Save the index in enzymes field to nEnzyme
+0239                 [x, nEnzyme]=ismember(tline(10:end),metaCycEnzymes.enzymes);
+0240                 if ~x
+0241                     %disp(tline(10:end));
+0242                 end
+0243             end
+0244             
+0245             %Add reaction id, and rxnNames by concatenating unique common
+0246             %names
+0247             if numel(tline)>11 && strcmp(tline(1:11),'REACTION - ')
+0248                 nRxn=nRxn+1;
+0249                 rxns{nRxn}='';
+0250                 rxnID=tline(12:end);
+0251                 [c, d]=ismember(rxnID,rxns);
+0252                 if c
+0253                     nRxn=nRxn-1;
+0254                     
+0255                     %Check if this common name has been included by
+0256                     %rxnNames
+0257                     k=strfind(metaCycEnzymes.rxnNames{d},metaCycEnzymes.commoname{enzrxnCounter});
+0258                     if isempty(k)
+0259                         metaCycEnzymes.rxnNames{d}=strcat(metaCycEnzymes.rxnNames{d},';',metaCycEnzymes.commoname{enzrxnCounter});
+0260                     end
+0261                     metaCycEnzymes.rxnEnzymeMat(d,nEnzyme)=1;
+0262                 else
+0263                     metaCycEnzymes.rxns{nRxn}=rxnID;
+0264                     metaCycEnzymes.rxnNames{nRxn}=metaCycEnzymes.commoname{enzrxnCounter};
+0265                     rxns{nRxn}=rxnID;
+0266                     metaCycEnzymes.rxnEnzymeMat(nRxn,nEnzyme)=1;
+0267                 end
+0268             end
+0269             
+0270         end
+0271         
+0272         %Close the file
+0273         fclose(fid);
+0274         
+0275         %Shrink the sizes
+0276         metaCycEnzymes.enzrxns=metaCycEnzymes.enzrxns(1:enzrxnCounter);
+0277         metaCycEnzymes.commoname=metaCycEnzymes.commoname(1:enzrxnCounter);
+0278         metaCycEnzymes.rxns=metaCycEnzymes.rxns(1:nRxn);
+0279         metaCycEnzymes.rxnNames=metaCycEnzymes.rxnNames(1:nRxn);
+0280         metaCycEnzymes.rxnEnzymeMat=metaCycEnzymes.rxnEnzymeMat(1:nRxn,:);
+0281         
+0282         %Save the model structure
+0283         save(enzymesFile,'metaCycEnzymes');
+0284         fprintf(['New metaCycEnzymes.mat has been successfully updated!\n\n']);
+0285     end
+0286     
+0287 end
+0288 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/external/metacyc/getMetaCycModelForOrganism.html b/doc/external/metacyc/getMetaCycModelForOrganism.html new file mode 100644 index 000000000..5809a21cd --- /dev/null +++ b/doc/external/metacyc/getMetaCycModelForOrganism.html @@ -0,0 +1,350 @@ + + + + Description of getMetaCycModelForOrganism + + + + + + + + + +
Home > external > metacyc > getMetaCycModelForOrganism.m
+ + + +

getMetaCycModelForOrganism +

+ +

PURPOSE ^

+
getMetaCycModelForOrganism
+ +

SYNOPSIS ^

+
function [model, metacycBlastStruct] = getMetaCycModelForOrganism(organismID,fastaFile,keepTransportRxns,keepUnbalanced,keepUndetermined,minScore,minPositives,useDiamond,metacycBlastStruct)
+ +

DESCRIPTION ^

+
 getMetaCycModelForOrganism
+   Reconstructs a genome-scale metabolic model based on protein homology to the
+   MetaCyc pathway database
+
+   Input:
+   organismID          the query organism's abbreviation, which is defined
+                       by user
+   fastaFile           a FASTA file that contains the protein sequences of
+                       the organism for which to reconstruct a model
+   keepTransportRxns   include transportation reactions, which often have identical
+                       reactants and products that turn to be all-zero columns in
+                       the S matrix (optional, default false)
+   keepUnbalanced      include reactions cannot be unbalanced reactions, usually
+                       because they are polymeric reactions or because of a
+                       specific difficulty in balancing class structures
+                       (optional, default false)
+   keepUndetermined    include reactions that have substrates lack chemical
+                       structures or with non-numerical coefficients (e.g. n+1)
+                       (optional, default false)
+   minScore            minimum Bit scores of BLASTp search (optional, default 100)
+   minPositives        minimum Positives values of BLASTp search (optional, default 45 %)
+   useDiamond          use DIAMOND alignment tools to perform homology search
+                       if true, otherwise the BLASTP is used (optional, default true)
+   metacycBlastStruct  provided an earlier generated metacycBlastStruct
+                       from getMetaCycModelForOrganism (optional, default empty).
+                       Useful when trying different cutoffs for minScore
+                       and minPositives without having to regenerate the
+                       blastStructure each time.
+
+   Output:
+   model               a model structure for the query organism
+   metacycBlastStruct  result from getBlast or getDiamond, before the
+                       minScore and minPositives cutoffs are applied
+
+ Usage: [model, metacycBlastStruct] = getMetaCycModelForOrganism(organismID,fastaFile,...
+    keepTransportRxns,keepUnbalanced,keepUndetermined,minScore,minPositives,useDiamond,metacycBlastStruct)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function [model, metacycBlastStruct] = getMetaCycModelForOrganism(organismID,fastaFile,...
+0002     keepTransportRxns,keepUnbalanced,keepUndetermined,minScore,minPositives,useDiamond,metacycBlastStruct)
+0003 % getMetaCycModelForOrganism
+0004 %   Reconstructs a genome-scale metabolic model based on protein homology to the
+0005 %   MetaCyc pathway database
+0006 %
+0007 %   Input:
+0008 %   organismID          the query organism's abbreviation, which is defined
+0009 %                       by user
+0010 %   fastaFile           a FASTA file that contains the protein sequences of
+0011 %                       the organism for which to reconstruct a model
+0012 %   keepTransportRxns   include transportation reactions, which often have identical
+0013 %                       reactants and products that turn to be all-zero columns in
+0014 %                       the S matrix (optional, default false)
+0015 %   keepUnbalanced      include reactions cannot be unbalanced reactions, usually
+0016 %                       because they are polymeric reactions or because of a
+0017 %                       specific difficulty in balancing class structures
+0018 %                       (optional, default false)
+0019 %   keepUndetermined    include reactions that have substrates lack chemical
+0020 %                       structures or with non-numerical coefficients (e.g. n+1)
+0021 %                       (optional, default false)
+0022 %   minScore            minimum Bit scores of BLASTp search (optional, default 100)
+0023 %   minPositives        minimum Positives values of BLASTp search (optional, default 45 %)
+0024 %   useDiamond          use DIAMOND alignment tools to perform homology search
+0025 %                       if true, otherwise the BLASTP is used (optional, default true)
+0026 %   metacycBlastStruct  provided an earlier generated metacycBlastStruct
+0027 %                       from getMetaCycModelForOrganism (optional, default empty).
+0028 %                       Useful when trying different cutoffs for minScore
+0029 %                       and minPositives without having to regenerate the
+0030 %                       blastStructure each time.
+0031 %
+0032 %   Output:
+0033 %   model               a model structure for the query organism
+0034 %   metacycBlastStruct  result from getBlast or getDiamond, before the
+0035 %                       minScore and minPositives cutoffs are applied
+0036 %
+0037 % Usage: [model, metacycBlastStruct] = getMetaCycModelForOrganism(organismID,fastaFile,...
+0038 %    keepTransportRxns,keepUnbalanced,keepUndetermined,minScore,minPositives,useDiamond,metacycBlastStruct)
+0039 
+0040 organismID=char(organismID);
+0041 if nargin<2
+0042     EM='No query protein fasta file is specified';
+0043     dispEM(EM);
+0044 else
+0045     fastaFile=char(fastaFile);
+0046 end
+0047 if nargin<3
+0048     keepTransportRxns=false;
+0049 end
+0050 if nargin<4
+0051     keepUnbalanced=false;
+0052 end
+0053 if nargin<5
+0054     keepUndetermined=false;
+0055 end
+0056 if nargin<6
+0057     minScore=100;
+0058 end
+0059 if nargin<7
+0060     minPositives=45;
+0061 end
+0062 if nargin<8
+0063     useDiamond=true;
+0064 end
+0065 if nargin<9
+0066     metacycBlastStruct=[];
+0067 end
+0068 
+0069 if isempty(fastaFile)
+0070     error('*** The query FASTA filename cannot be empty! ***');
+0071 else
+0072     fprintf('\nChecking existence of query FASTA file... ');
+0073     %Check if query fasta exists
+0074     fastaFile=checkFileExistence(fastaFile,2); %Copy file to temp dir
+0075     fprintf('done\n');
+0076 end
+0077 
+0078 %First generate the full MetaCyc model
+0079 metaCycModel=getModelFromMetaCyc([],keepTransportRxns,keepUnbalanced,keepUndetermined);
+0080 fprintf('The full MetaCyc model loaded\n');
+0081 
+0082 %Create the draft model from MetaCyc super model model=metaCycModel;
+0083 model.id=organismID;
+0084 model.name='Generated by homology with MetaCyc database';
+0085 model.rxns=metaCycModel.rxns;
+0086 model.rxnNames=metaCycModel.rxnNames;
+0087 model.eccodes=metaCycModel.eccodes;
+0088 model.subSystems=metaCycModel.subSystems;
+0089 model.rxnMiriams=metaCycModel.rxnMiriams;
+0090 model.rxnReferences=metaCycModel.rxnReferences;
+0091 model.lb=metaCycModel.lb;
+0092 model.ub=metaCycModel.ub;
+0093 model.rev=metaCycModel.rev;
+0094 model.c=metaCycModel.c;
+0095 model.equations=metaCycModel.equations;
+0096 
+0097 %Get the root directory for RAVEN Toolbox.
+0098 ravenPath=findRAVENroot();
+0099 
+0100 %Generate blast strcture by either DIAMOND or BLASTP
+0101 if isempty(metacycBlastStruct)
+0102     if useDiamond
+0103         blastStruc=getDiamond(organismID,fastaFile,{'MetaCyc'},fullfile(ravenPath,'external','metacyc','protseq.fsa'));
+0104     else
+0105         blastStruc=getBlast(organismID,fastaFile,{'MetaCyc'},fullfile(ravenPath,'external','metacyc','protseq.fsa'));
+0106     end
+0107     %Only look the query
+0108     blastStructure=blastStruc(2);
+0109     metacycBlastStruct=blastStructure;
+0110 else
+0111     blastStructure=metacycBlastStruct;
+0112 end
+0113 
+0114 %Remove all blast hits that are below the cutoffs
+0115 indexes=blastStructure.bitscore>=minScore & blastStructure.ppos>=minPositives;
+0116 blastStructure.toGenes(~indexes)=[];
+0117 blastStructure.fromGenes(~indexes)=[];
+0118 blastStructure.evalue(~indexes)=[];
+0119 blastStructure.aligLen(~indexes)=[];
+0120 blastStructure.identity(~indexes)=[];
+0121 blastStructure.bitscore(~indexes)=[];
+0122 blastStructure.ppos(~indexes)=[];
+0123 fprintf('Completed searching against MetaCyc protein sequences.\n');
+0124 
+0125 % Get the qualified genes of query organism from blast structure
+0126 model.genes=cell(100000,1);
+0127 model.proteins=cell(100000,1);
+0128 model.bitscore=zeros(100000,1);
+0129 model.ppos=zeros(100000,1);
+0130 num=1;
+0131 
+0132 %Go through the strucutre and find out the hit with the best bit score
+0133 for i=1:numel(blastStructure.fromGenes)
+0134     if num==1
+0135         model.genes(num)=blastStructure.fromGenes(i);
+0136         model.proteins(num)=strrep(blastStructure.toGenes(i), 'gnl|META|', '');
+0137         model.bitscore(num)=blastStructure.bitscore(i);
+0138         model.ppos(num)=blastStructure.ppos(i);
+0139         num=num+1;
+0140         lastGene=blastStructure.fromGenes(i);
+0141     else
+0142         if ~isequal(lastGene,blastStructure.fromGenes(i))
+0143             model.genes(num)=blastStructure.fromGenes(i);
+0144             model.proteins(num)=strrep(blastStructure.toGenes(i), 'gnl|META|', '');
+0145             model.bitscore(num)=blastStructure.bitscore(i);
+0146             model.ppos(num)=blastStructure.ppos(i);
+0147             num=num+1;
+0148             lastGene=blastStructure.fromGenes(i);
+0149         else
+0150             if model.bitscore(num)<blastStructure.bitscore(i)
+0151                 model.bitscore(num)=blastStructure.bitscore(i);
+0152                 model.proteins(num)=strrep(blastStructure.toGenes(i), 'gnl|META|', '');
+0153                 model.ppos(num)=blastStructure.ppos(i);
+0154             end
+0155         end
+0156     end
+0157 end
+0158 model.genes=model.genes(1:num-1);
+0159 model.proteins=model.proteins(1:num-1);
+0160 model.bitscore=model.bitscore(1:num-1);
+0161 model.ppos=model.ppos(1:num-1);
+0162 
+0163 % Get the indexes of matched genes in the metaCycModel
+0164 % because some enzymes in the FASTA file cannot be found in the dump file
+0165 [hits, indexes]=ismember(model.proteins,metaCycModel.genes);
+0166 found = find(hits);
+0167 model.genes=model.genes(found);
+0168 
+0169 % Restructure the rxnGeneMat matrix
+0170 model.rxnGeneMat=sparse(metaCycModel.rxnGeneMat(:,indexes(found)));
+0171 
+0172 %Remove all reactions without genes
+0173 hasGenes=any(model.rxnGeneMat,2);
+0174 model=removeReactions(model,~hasGenes,true);
+0175 
+0176 %Generate grRules, only consider the or relationship here Matched enzymes
+0177 %are stored in field rxnScores,
+0178 rxnNum=numel(model.rxns);
+0179 model.rxnConfidenceScores=NaN(rxnNum,1);
+0180 model.rxnConfidenceScores(:)=2;
+0181 model.grRules=cell(rxnNum,1);
+0182 %model.rxnScores=cell(rxnNum,1);
+0183 for j=1:rxnNum
+0184     model.grRules{j}='';
+0185     I=find(model.rxnGeneMat(j,:));
+0186     for k=1:numel(I)
+0187         if isempty(model.grRules{j})
+0188             model.grRules(j)=model.genes(I(k));
+0189             %model.rxnScores(j)=model.proteins(I(k));
+0190         else
+0191             model.grRules(j)=strcat(model.grRules(j),{' or '},model.genes(I(k)));
+0192             %model.rxnScores(j)=strcat(model.rxnScores(j),{' or
+0193             %'},model.proteins(I(k)));
+0194         end
+0195     end
+0196 end
+0197 %update genes field
+0198 model.genes=model.genes(any(model.rxnGeneMat));
+0199 
+0200 %Construct the S matrix and list of metabolites
+0201 [S, mets, badRxns]=constructS(model.equations);
+0202 model.S=S;
+0203 model.mets=mets;
+0204 
+0205 %model=removeReactions(model,badRxns,true,true);
+0206 
+0207 %Then match up metabolites
+0208 metaCycMets=getMetsFromMetaCyc([]);
+0209 
+0210 %Add information about all metabolites to the model
+0211 [a, b]=ismember(model.mets,metaCycMets.mets);
+0212 a=find(a);
+0213 b=b(a);
+0214 
+0215 if ~isfield(model,'metNames')
+0216     model.metNames=cell(numel(model.mets),1);
+0217     model.metNames(:)={''};
+0218 end
+0219 model.metNames(a)=metaCycMets.metNames(b);
+0220 
+0221 if ~isfield(model,'metFormulas')
+0222     model.metFormulas=cell(numel(model.mets),1);
+0223     model.metFormulas(:)={''};
+0224 end
+0225 model.metFormulas(a)=metaCycMets.metFormulas(b);
+0226 
+0227 if ~isfield(model,'metCharges')
+0228     model.metCharges=zeros(numel(model.mets),1);
+0229 end
+0230 model.metCharges(a)=metaCycMets.metCharges(b);
+0231 
+0232 if ~isfield(model,'b')
+0233     model.b=zeros(numel(model.mets),1);
+0234 end
+0235 %model.b(a)=metaCycMets.b(b);
+0236 
+0237 if ~isfield(model,'inchis')
+0238     model.inchis=cell(numel(model.mets),1);
+0239     model.inchis(:)={''};
+0240 end
+0241 model.inchis(a)=metaCycMets.inchis(b);
+0242 
+0243 if ~isfield(model,'metMiriams')
+0244     model.metMiriams=cell(numel(model.mets),1);
+0245 end
+0246 model.metMiriams(a)=metaCycMets.metMiriams(b);
+0247 
+0248 %Put all metabolites in one compartment called 's' (for system). This is
+0249 %done just to be more compatible with the rest of the code
+0250 model.comps={'s'};
+0251 model.compNames={'System'};
+0252 model.metComps=ones(numel(model.mets),1);
+0253 
+0254 %It could also be that the metabolite names are empty for some reason In
+0255 %that case, use the ID instead
+0256 I=cellfun(@isempty,model.metNames);
+0257 model.metNames(I)=model.mets(I);
+0258 
+0259 %Remove additional fields
+0260 model=rmfield(model,{'proteins','bitscore','ppos'});
+0261 
+0262 %In the end fix grRules and rxnGeneMat
+0263 [grRules,rxnGeneMat] = standardizeGrRules(model,false); %Get detailed output
+0264 model.grRules = grRules;
+0265 model.rxnGeneMat = rxnGeneMat;
+0266 %Remove the temp fasta file
+0267 delete(fastaFile)
+0268 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/external/metacyc/getMetsFromMetaCyc.html b/doc/external/metacyc/getMetsFromMetaCyc.html new file mode 100644 index 000000000..fa08c3b39 --- /dev/null +++ b/doc/external/metacyc/getMetsFromMetaCyc.html @@ -0,0 +1,362 @@ + + + + Description of getMetsFromMetaCyc + + + + + + + + + +
Home > external > metacyc > getMetsFromMetaCyc.m
+ + + +

getMetsFromMetaCyc +

+ +

PURPOSE ^

+
getMetsFromMetaCyc
+ +

SYNOPSIS ^

+
function metaCycMets=getMetsFromMetaCyc(metacycPath)
+ +

DESCRIPTION ^

+
 getMetsFromMetaCyc
+   Retrieves information of all metabolites in MetaCyc database
+
+   Input:
+   metacycPath  if metacycMets.mat is not in the RAVEN\external\metacyc directory,
+                this function will attempt to build it by reading info from
+                a local dump of MetaCyc database, and metacycPath is the path
+                to the MetaCyc data files
+
+   Output:
+   model        a model structure generated from the database. The following
+                fields are filled
+                id:             'MetaCyc'
+                name:    'Automatically generated from MetaCyc database'
+                mets:           MetaCyc compound ids
+                metNames:       Compound name. Reuse compound id here if
+                                there is no name provided
+                metFormulas:    The chemical composition of the metabolite.
+                inchis:         InChI string for the metabolite
+                metCharges:     Compound charge state
+                metMiriams:     If there is a CHEBI id available, then that
+                                will be saved here
+                keggid:         The corresponding KEGG compound id if available
+                version:        MetaCyc database version
+
+   If the file metaCycMets.mat is in the RAVEN\external\metacyc directory
+   it will be directly loaded. Otherwise, it will be generated by parsing
+   the MetaCyc database files. In general, this metaCycMets.mat file should
+   be removed and rebuilt when a newer version of MetaCyc is released.
+               
+ Usage: model=getMetsFromMetaCyc(metacycPath)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function metaCycMets=getMetsFromMetaCyc(metacycPath)
+0002 % getMetsFromMetaCyc
+0003 %   Retrieves information of all metabolites in MetaCyc database
+0004 %
+0005 %   Input:
+0006 %   metacycPath  if metacycMets.mat is not in the RAVEN\external\metacyc directory,
+0007 %                this function will attempt to build it by reading info from
+0008 %                a local dump of MetaCyc database, and metacycPath is the path
+0009 %                to the MetaCyc data files
+0010 %
+0011 %   Output:
+0012 %   model        a model structure generated from the database. The following
+0013 %                fields are filled
+0014 %                id:             'MetaCyc'
+0015 %                name:    'Automatically generated from MetaCyc database'
+0016 %                mets:           MetaCyc compound ids
+0017 %                metNames:       Compound name. Reuse compound id here if
+0018 %                                there is no name provided
+0019 %                metFormulas:    The chemical composition of the metabolite.
+0020 %                inchis:         InChI string for the metabolite
+0021 %                metCharges:     Compound charge state
+0022 %                metMiriams:     If there is a CHEBI id available, then that
+0023 %                                will be saved here
+0024 %                keggid:         The corresponding KEGG compound id if available
+0025 %                version:        MetaCyc database version
+0026 %
+0027 %   If the file metaCycMets.mat is in the RAVEN\external\metacyc directory
+0028 %   it will be directly loaded. Otherwise, it will be generated by parsing
+0029 %   the MetaCyc database files. In general, this metaCycMets.mat file should
+0030 %   be removed and rebuilt when a newer version of MetaCyc is released.
+0031 %
+0032 % Usage: model=getMetsFromMetaCyc(metacycPath)
+0033 
+0034 % NOTE: This is how one entry looks in the file
+0035 
+0036 % //
+0037 % UNIQUE-ID - CPD-18846
+0038 % TYPES - CPD-18866
+0039 % COMMON-NAME - 12-ethyl-8-propyl-bacteriochlorophyllide <i>d</i>
+0040 % ATOM-CHARGES - (43 -1)
+0041 % ATOM-CHARGES - (12 -1)
+0042 % CHEMICAL-FORMULA - (C 35)
+0043 % CHEMICAL-FORMULA - (H 36)
+0044 % CHEMICAL-FORMULA - (N 4)
+0045 % CHEMICAL-FORMULA - (O 4)
+0046 % CHEMICAL-FORMULA - (MG 1)
+0047 % CITATIONS - 26331578
+0048 % CITATIONS - 2350541
+0049 % CREDITS - SRI
+0050 % CREDITS - caspi
+0051 % MOLECULAR-WEIGHT - 600.999
+0052 % MONOISOTOPIC-MW - 602.274347629
+0053 % NON-STANDARD-INCHI - InChI=1S/C35H39N4O4.Mg/c1-7-9-21-16(3)24-14-29-32(19(6)40)18(5)26(37-29)13-25-17(4)22(10-11-31(42)43)34(38-25)23-12-30(41)33-20(8-2)27(39-35(23)33)15-28(21)36-24;/h12-15,17,19,22,40H,7-11H2,1-6H3,(H3,36,37,38,39,41,42,43);/q-1;+2/p-3/t17-,19?,22-;/m0./s1
+0054 % SMILES - CCCC5(=C(C)C9(N6([Mg]27(N1(C(C(C)C(CCC(=O)[O-])C=1C4([C-]C(=O)C3(=C(CC)C(N2C3=4)=CC5=6)))=CC8(=C(C)C(C(O)C)=C(N78)C=9))))))
+0055 
+0056 % A line that contains only '//' separates each object.
+0057 
+0058 % Check if the metabolites have been parsed before and saved. If so, load
+0059 % the model.
+0060 if nargin<1
+0061     ravenPath=findRAVENroot();
+0062     metacycPath=fullfile(ravenPath,'external','metacyc');
+0063 else
+0064     metacycPath=char(metacycPath);
+0065 end
+0066 
+0067 metsFile=fullfile(metacycPath,'metaCycMets.mat');
+0068 metaCycMetFile='compounds.dat';
+0069 
+0070 if exist(metsFile, 'file')
+0071     fprintf(['Importing MetaCyc metabolites from ' strrep(metsFile,'\','/') '... ']);
+0072     load(metsFile);
+0073     fprintf('done\n');
+0074 else
+0075     fprintf(['Cannot locate ' strrep(metsFile,'\','/') '\nNow try to generate it from local MetaCyc data files...\n']);
+0076     if ~isfile(fullfile(metacycPath,metaCycMetFile))
+0077         EM=fprintf(['The file of metabolites cannot be located, and should be downloaded from MetaCyc.\n']);
+0078         dispEM(EM);
+0079     else
+0080         %Add new functionality in the order specified in models
+0081         metaCycMets.id='MetaCyc';
+0082         metaCycMets.name='Automatically generated from MetaCyc database';
+0083         
+0084         %Preallocate memory for 50000 metabolites
+0085         metaCycMets.mets=cell(50000,1);
+0086         metaCycMets.metNames=cell(50000,1);
+0087         metaCycMets.metFormulas=cell(50000,1);
+0088         metaCycMets.inchis=cell(50000,1);
+0089         metaCycMets.metCharges=zeros(50000,1);
+0090         metaCycMets.metMiriams=cell(50000,1);
+0091         metaCycMets.keggid=cell(50000,1);
+0092         
+0093         %First load information on metabolite ID, name, formula, and others
+0094         fid = fopen(fullfile(metacycPath,metaCycMetFile), 'r');
+0095         
+0096         %Keeps track of how many metabolites that have been added
+0097         metCounter=0;
+0098         
+0099         %Loop through the file
+0100         while 1
+0101             %Get the next line
+0102             tline = fgetl(fid);
+0103             %disp(tline);
+0104             
+0105             % Abort at end of file
+0106             if ~ischar(tline)
+0107                 break;
+0108             end
+0109             
+0110             % Get the version of MetaCyc database
+0111             if numel(tline)>11 && strcmp(tline(1:11),'# Version: ')
+0112                 metaCycMets.version=tline(12:end);
+0113             end
+0114 
+0115             %Check if it is a new entry
+0116             if numel(tline)>12 && strcmp(tline(1:12),'UNIQUE-ID - ')
+0117                 metCounter=metCounter+1;
+0118                 
+0119                 %Add empty strings as initial values
+0120                 metaCycMets.metNames{metCounter}='';
+0121                 metaCycMets.metFormulas{metCounter}='';
+0122                 metaCycMets.inchis{metCounter}='';
+0123                 %metaCycMets.smiles{metCounter}='';
+0124                 %metaCycMets.pubchem{metCounter}='';
+0125                 metaCycMets.keggid{metCounter}='';
+0126                 nonStandardInchis = '';
+0127                 
+0128                 %Add compound ID
+0129                 metaCycMets.mets{metCounter}=tline(13:end);
+0130             end
+0131             
+0132             
+0133             %Add name
+0134             if numel(tline)>14 &&    strcmp(tline(1:14),'COMMON-NAME - ')
+0135                 metaCycMets.metNames{metCounter}=tline(15:end);
+0136                 
+0137                 %Romve HTML symbols
+0138                 metaCycMets.metNames{metCounter}=regexprep(metaCycMets.metNames{metCounter},'<(\w+)>','');
+0139                 metaCycMets.metNames{metCounter}=regexprep(metaCycMets.metNames{metCounter},'</(\w+)>','');
+0140                 metaCycMets.metNames{metCounter}=regexprep(metaCycMets.metNames{metCounter},'[&;]','');
+0141             end
+0142             
+0143             %Add charge
+0144             if numel(tline)>16 &&    strcmp(tline(1:16),'ATOM-CHARGES - (')
+0145                 atomCharge=tline(17:end-1);
+0146                 
+0147                 s=strfind(atomCharge,' ');
+0148                 if any(s)
+0149                     atomCharge=atomCharge(s+1:end);
+0150                     metaCycMets.metCharges(metCounter,1)=metaCycMets.metCharges(metCounter,1)+str2num(atomCharge);
+0151                 end
+0152             end
+0153             
+0154             %Add inchis
+0155             if numel(tline)>14 && strcmp(tline(1:14),'INCHI - InChI=')
+0156                 metaCycMets.inchis{metCounter}=tline(15:end);
+0157             end
+0158             
+0159             %Add non-standard inchis
+0160             if numel(tline)>27 && strcmp(tline(1:27),'NON-STANDARD-INCHI - InChI=')
+0161                 nonStandardInchis=tline(28:end);
+0162             end
+0163             
+0164             %Add SMILES
+0165             if numel(tline)>9 && strcmp(tline(1:9),'SMILES - ')
+0166                 
+0167                 if isstruct(metaCycMets.metMiriams{metCounter})
+0168                     addToIndex=numel(metaCycMets.metMiriams{metCounter}.name)+1;
+0169                 else
+0170                     addToIndex=1;
+0171                 end
+0172                 tempStruct=metaCycMets.metMiriams{metCounter};
+0173                 tempStruct.name{addToIndex,1}='SMILES';
+0174                 tempStruct.value{addToIndex,1}=tline(10:end);
+0175                 metaCycMets.metMiriams{metCounter}=tempStruct;
+0176             end
+0177             
+0178             %Add formula
+0179             if numel(tline)>20 && strcmp(tline(1:20),'CHEMICAL-FORMULA - (')
+0180                 metaCycMets.metFormulas{metCounter}=strcat(metaCycMets.metFormulas{metCounter},tline(21:end-1));
+0181                 metaCycMets.metFormulas{metCounter}(isspace(metaCycMets.metFormulas{metCounter})) = [];
+0182             end
+0183             
+0184             %Add KEGG id
+0185             if numel(tline)>23 && strcmp(tline(1:23),'DBLINKS - (LIGAND-CPD "')
+0186                 keggid=tline(24:end);
+0187                 
+0188                 s=strfind(keggid,'"');
+0189                 if any(s)
+0190                     keggid=keggid(1:s-1);
+0191                 end
+0192                 
+0193                 metaCycMets.keggid{metCounter}=keggid;
+0194             end
+0195             
+0196             %Add CHEBI id
+0197             if numel(tline)>18 && strcmp(tline(1:18),'DBLINKS - (CHEBI "')
+0198                 chebiID=tline(20:end); %This is because there is sometimes more than one CHEBI index
+0199                 
+0200                 s=strfind(chebiID,'"');
+0201                 if any(s)
+0202                     chebiID=chebiID(1:s-1);
+0203                 end
+0204                 
+0205                 if isstruct(metaCycMets.metMiriams{metCounter})
+0206                     addToIndex=numel(metaCycMets.metMiriams{metCounter}.name)+1;
+0207                 else
+0208                     addToIndex=1;
+0209                 end
+0210                 tempStruct=metaCycMets.metMiriams{metCounter};
+0211                 tempStruct.name{addToIndex,1}='chebi';
+0212                 tempStruct.value{addToIndex,1}=strcat('CHEBI:',chebiID);
+0213                 metaCycMets.metMiriams{metCounter}=tempStruct;
+0214             end
+0215             
+0216             %Add PubChem
+0217             if numel(tline)>20 && strcmp(tline(1:20),'DBLINKS - (PUBCHEM "')
+0218                 pubchemID=tline(21:end);
+0219                 
+0220                 s=strfind(pubchemID,'"');
+0221                 if any(s)
+0222                     pubchemID=pubchemID(1:s-1);
+0223                 end
+0224                 
+0225                 if isstruct(metaCycMets.metMiriams{metCounter})
+0226                     addToIndex=numel(metaCycMets.metMiriams{metCounter}.name)+1;
+0227                 else
+0228                     addToIndex=1;
+0229                 end
+0230                 tempStruct=metaCycMets.metMiriams{metCounter};
+0231                 tempStruct.name{addToIndex,1}='pubchem.compound';
+0232                 tempStruct.value{addToIndex,1}=pubchemID;
+0233                 metaCycMets.metMiriams{metCounter}=tempStruct;
+0234             end
+0235             
+0236             %Add non-standard inchis when standard one is unavailable
+0237             if strcmp(tline,'//') && strcmp(metaCycMets.inchis{metCounter},'')
+0238                 metaCycMets.inchis{metCounter}=nonStandardInchis;
+0239                 nonStandardInchis = '';
+0240                 
+0241                 %Refine formula from inchis
+0242                 s=strfind(metaCycMets.inchis{metCounter},'/');
+0243                 if any(s)
+0244                     inchiFormula=metaCycMets.inchis{metCounter}(s(1)+1:s(2)-1);
+0245                     
+0246                     %And remove dot characters
+0247                     inchiFormula(regexp(inchiFormula,'[.]'))=[];
+0248                     if ~strcmp(metaCycMets.metFormulas{metCounter},inchiFormula)
+0249                         metaCycMets.metFormulas{metCounter}=inchiFormula;
+0250                     end
+0251                 end
+0252                 
+0253             end
+0254             
+0255         end
+0256         
+0257         %Close the file
+0258         fclose(fid);
+0259         
+0260         %If too much space was allocated, shrink the model
+0261         metaCycMets.mets=metaCycMets.mets(1:metCounter);
+0262         metaCycMets.metNames=metaCycMets.metNames(1:metCounter);
+0263         metaCycMets.metFormulas=metaCycMets.metFormulas(1:metCounter);
+0264         metaCycMets.metMiriams=metaCycMets.metMiriams(1:metCounter);
+0265         metaCycMets.inchis=metaCycMets.inchis(1:metCounter);
+0266         metaCycMets.metCharges=metaCycMets.metCharges(1:metCounter,:);
+0267         %metaCycMets.smiles=metaCycMets.smiles(1:metCounter);
+0268         %metaCycMets.pubchem=metaCycMets.pubchem(1:metCounter);
+0269         metaCycMets.keggid=metaCycMets.keggid(1:metCounter);
+0270         
+0271         %If the metMiriams structure is empty, use MetaCyc id as metMiriams
+0272         for i=1:numel(metaCycMets.mets)
+0273             if ~isstruct(metaCycMets.metMiriams{i})
+0274                 miriamStruct.name{1}='metacyc.compound';
+0275                 miriamStruct.value{1}=metaCycMets.mets{i};
+0276                 metaCycMets.metMiriams{i}=miriamStruct;
+0277             end
+0278         end
+0279         
+0280         %Saves the model
+0281         save(metsFile,'metaCycMets');
+0282         fprintf(['New metaCycMets.mat has been successfully updated!\n\n']);
+0283     end
+0284 end
+0285 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/external/metacyc/getModelFromMetaCyc.html b/doc/external/metacyc/getModelFromMetaCyc.html new file mode 100644 index 000000000..4e38fde03 --- /dev/null +++ b/doc/external/metacyc/getModelFromMetaCyc.html @@ -0,0 +1,261 @@ + + + + Description of getModelFromMetaCyc + + + + + + + + + +
Home > external > metacyc > getModelFromMetaCyc.m
+ + + +

getModelFromMetaCyc +

+ +

PURPOSE ^

+
getModelFromMetaCyc
+ +

SYNOPSIS ^

+
function metaCycModel=getModelFromMetaCyc(metacycPath,keepTransportRxns,keepUnbalanced,keepUndetermined)
+ +

DESCRIPTION ^

+
 getModelFromMetaCyc
+   Retrieves information stored in MetaCyc flat files and generates a super model
+
+   Input:
+   metacycPath         By setting this parameter as empty (default ''), a 
+                       super model of MetaCyc can be directly generated from
+                       the Matlab files (metaCycRxns, metaCycMets and metaCycEnzymes)
+                       that are in the RAVEN\external\metacyc directory.
+                       Alternatively, this function attempts to re-generate
+                       the Matlab files from a local dump of MetaCyc data files
+                       (e.g. reactions.dat, proteins.dat, compounds.dat),
+                       to which the path should be defined by this parameter
+   keepTransportRxns   include transportation reactions, which often have identical
+                       reactants and products that turn to be all-zero columns in
+                       the S matrix (optional, default false)
+   keepUnbalanced      include reactions cannot be unbalanced reactions, usually
+                       because they are polymeric reactions or because of a
+                       specific difficulty in balancing class structures
+                       (optional, default false)
+   keepUndetermined    include reactions that have substrates lack chemical
+                       structures or with non-numerical coefficients (e.g. n+1)
+                       (optional, default false)
+
+   Output:
+   metaCycModel        a model structure generated from MetaCyc database
+                       including all reactions, metabolites and enzymes
+                       in MetaCyc
+
+   NOTE: This function allows users to update the MetaCyc Matlab files from
+   a local dump of data files, which can be obtained through subscribing to
+   the database (https://metacyc.org/download.shtml).
+
+ Usage: getModelFromMetaCyc(metacycPath,keepTransportRxns,keepUnbalanced,keepUndetermined)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function metaCycModel=getModelFromMetaCyc(metacycPath,keepTransportRxns,keepUnbalanced,keepUndetermined)
+0002 % getModelFromMetaCyc
+0003 %   Retrieves information stored in MetaCyc flat files and generates a super model
+0004 %
+0005 %   Input:
+0006 %   metacycPath         By setting this parameter as empty (default ''), a
+0007 %                       super model of MetaCyc can be directly generated from
+0008 %                       the Matlab files (metaCycRxns, metaCycMets and metaCycEnzymes)
+0009 %                       that are in the RAVEN\external\metacyc directory.
+0010 %                       Alternatively, this function attempts to re-generate
+0011 %                       the Matlab files from a local dump of MetaCyc data files
+0012 %                       (e.g. reactions.dat, proteins.dat, compounds.dat),
+0013 %                       to which the path should be defined by this parameter
+0014 %   keepTransportRxns   include transportation reactions, which often have identical
+0015 %                       reactants and products that turn to be all-zero columns in
+0016 %                       the S matrix (optional, default false)
+0017 %   keepUnbalanced      include reactions cannot be unbalanced reactions, usually
+0018 %                       because they are polymeric reactions or because of a
+0019 %                       specific difficulty in balancing class structures
+0020 %                       (optional, default false)
+0021 %   keepUndetermined    include reactions that have substrates lack chemical
+0022 %                       structures or with non-numerical coefficients (e.g. n+1)
+0023 %                       (optional, default false)
+0024 %
+0025 %   Output:
+0026 %   metaCycModel        a model structure generated from MetaCyc database
+0027 %                       including all reactions, metabolites and enzymes
+0028 %                       in MetaCyc
+0029 %
+0030 %   NOTE: This function allows users to update the MetaCyc Matlab files from
+0031 %   a local dump of data files, which can be obtained through subscribing to
+0032 %   the database (https://metacyc.org/download.shtml).
+0033 %
+0034 % Usage: getModelFromMetaCyc(metacycPath,keepTransportRxns,keepUnbalanced,keepUndetermined)
+0035 
+0036 if nargin<1
+0037     ravenPath=findRAVENroot();
+0038     metacycPath=fullfile(ravenPath,'external','metacyc');
+0039 else
+0040     metacycPath=char(metacycPath);
+0041 end
+0042 if nargin<2
+0043     keepTransportRxns=false;
+0044 end
+0045 if nargin<3
+0046     keepUnbalanced=false;
+0047 end
+0048 if nargin<4
+0049     keepUndetermined=false;
+0050 end
+0051 
+0052 %First get all reactions
+0053 metaCycModel=getRxnsFromMetaCyc(metacycPath,keepTransportRxns,keepUnbalanced,keepUndetermined);
+0054 
+0055 %Get reaction and enzyme association
+0056 metaCycEnzymes=getEnzymesFromMetaCyc(metacycPath);
+0057 
+0058 %Replace rxnNames with those from metaCycEnzymes
+0059 [a, b]=ismember(metaCycModel.rxns,metaCycEnzymes.rxns);
+0060 a=find(a);
+0061 b=b(a);
+0062 metaCycModel.rxnNames(a)=metaCycEnzymes.rxnNames(b);
+0063 
+0064 fprintf('Reorganizing reaction-enzyme associations... ')
+0065 %Create the rxnGeneMat for the reactions, by geting all enzymes and
+0066 %corresponding subunits
+0067 rxnNum=numel(metaCycModel.rxns);
+0068 metaCycModel.genes=metaCycEnzymes.enzymes;
+0069 metaCycModel.rxnGeneMat=sparse(rxnNum,numel(metaCycEnzymes.enzymes));
+0070 metaCycModel.grRules=cell(rxnNum,1);
+0071 
+0072 %Loop through all reactions to generate rxnGeneMat matrix and grRules This
+0073 %step also cross-link reactions to their catalyzing enzymes
+0074 for i=1:rxnNum
+0075     
+0076     metaCycModel.grRules{i}='';
+0077     %Find out if this is an enzymatic reaction
+0078     [a, b]=ismember(metaCycModel.rxns(i),metaCycEnzymes.rxns);
+0079     if a
+0080         I=[];   %Find out all catalyzing enzymes, which are treated as isoenzymes
+0081         I=find(metaCycEnzymes.rxnEnzymeMat(b,:));
+0082         if ~isempty(I)
+0083             
+0084             grRule='';
+0085             for j=1:numel(I)
+0086                 
+0087                 subgrRule=''; %Find out if enzyme complex
+0088                 [c, d]=ismember(metaCycEnzymes.enzymes(I(j)),metaCycEnzymes.cplxs);
+0089                 if c   %In cases of an enzyme complex
+0090                     %With single subunit
+0091                     if numel(metaCycEnzymes.cplxComp{d}.subunit)==1
+0092                         subgrRule=metaCycEnzymes.cplxComp{d}.subunit{1};
+0093                         %With multiple subunits
+0094                     else
+0095                         subgrRule=strjoin(metaCycEnzymes.cplxComp{d}.subunit,' and ');
+0096                         subgrRule=strcat('(',subgrRule,')');
+0097                     end
+0098                     [x, geneIndex]=ismember(metaCycEnzymes.cplxComp{d}.subunit,metaCycModel.genes);
+0099                     metaCycModel.rxnGeneMat(i,geneIndex)=1;
+0100                     
+0101                 else  %In cases of NOT an enzyme complex
+0102                     subgrRule=metaCycEnzymes.enzymes(I(j));
+0103                     metaCycModel.rxnGeneMat(i,I(j))=1;
+0104                 end
+0105                 
+0106                 %Generating grRules
+0107                 if ~strcmp(subgrRule,'')
+0108                     if ~strcmp(grRule,'')
+0109                         grRule=strcat(grRule,{' or '},subgrRule);
+0110                     else
+0111                         grRule=subgrRule;
+0112                     end
+0113                 end
+0114                 
+0115             end
+0116             if iscell(grRule)
+0117                 metaCycModel.grRules{i}=grRule{1};
+0118             else
+0119                 metaCycModel.grRules{i}=grRule;
+0120             end
+0121             
+0122         end
+0123         
+0124     end
+0125 end
+0126 fprintf('done\n')
+0127 %Then get all metabolites
+0128 metaCycMets=getMetsFromMetaCyc(metacycPath);
+0129 
+0130 %Add information about all metabolites to the model
+0131 [a, b]=ismember(metaCycModel.mets,metaCycMets.mets);
+0132 a=find(a);
+0133 b=b(a);
+0134 
+0135 if ~isfield(metaCycModel,'metNames')
+0136     metaCycModel.metNames=cell(numel(metaCycModel.mets),1);
+0137     metaCycModel.metNames(:)={''};
+0138 end
+0139 metaCycModel.metNames(a)=metaCycMets.metNames(b);
+0140 
+0141 if ~isfield(metaCycModel,'metFormulas')
+0142     metaCycModel.metFormulas=cell(numel(metaCycModel.mets),1);
+0143     metaCycModel.metFormulas(:)={''};
+0144 end
+0145 metaCycModel.metFormulas(a)=metaCycMets.metFormulas(b);
+0146 
+0147 if ~isfield(metaCycModel,'metCharges')
+0148     metaCycModel.metCharges=zeros(numel(metaCycModel.mets),1);
+0149 end
+0150 metaCycModel.metCharges(a)=metaCycMets.metCharges(b);
+0151 
+0152 if ~isfield(metaCycModel,'inchis')
+0153     metaCycModel.inchis=cell(numel(metaCycModel.mets),1);
+0154     metaCycModel.inchis(:)={''};
+0155 end
+0156 metaCycModel.inchis(a)=metaCycMets.inchis(b);
+0157 
+0158 if ~isfield(metaCycModel,'metMiriams')
+0159     metaCycModel.metMiriams=cell(numel(metaCycModel.mets),1);
+0160 end
+0161 metaCycModel.metMiriams(a)=metaCycMets.metMiriams(b);
+0162 
+0163 if ~isfield(metaCycModel,'keggid')
+0164     metaCycModel.keggid=cell(numel(metaCycModel.mets),1);
+0165 end
+0166 metaCycModel.keggid(a)=metaCycMets.keggid(b);
+0167 
+0168 %Put all metabolites in one compartment called 's' (for system). This is
+0169 %done just to be more compatible with the rest of the code
+0170 metaCycModel.comps={'s'};
+0171 metaCycModel.compNames={'System'};
+0172 metaCycModel.metComps=ones(numel(metaCycModel.mets),1);
+0173 
+0174 
+0175 %It could also be that the metabolite and reaction names are empty for some
+0176 %reasons. In that case, use the ID instead
+0177 I=cellfun(@isempty,metaCycModel.metNames);
+0178 metaCycModel.metNames(I)=metaCycModel.mets(I);
+0179 I=cellfun(@isempty,metaCycModel.rxnNames);
+0180 metaCycModel.rxnNames(I)=metaCycModel.rxns(I);
+0181 
+0182 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/external/metacyc/getRxnsFromMetaCyc.html b/doc/external/metacyc/getRxnsFromMetaCyc.html new file mode 100644 index 000000000..f3b265898 --- /dev/null +++ b/doc/external/metacyc/getRxnsFromMetaCyc.html @@ -0,0 +1,629 @@ + + + + Description of getRxnsFromMetaCyc + + + + + + + + + +
Home > external > metacyc > getRxnsFromMetaCyc.m
+ + + +

getRxnsFromMetaCyc +

+ +

PURPOSE ^

+
getRxnsFromMetaCyc
+ +

SYNOPSIS ^

+
function model=getRxnsFromMetaCyc(metacycPath,keepTransportRxns,keepUnbalanced,keepUndetermined)
+ +

DESCRIPTION ^

+
 getRxnsFromMetaCyc
+   Retrieves reactions information from MetaCyc database
+
+   Input:
+   metacycPath         if metaCycRxns.mat is not in the RAVEN\external\metacyc
+                       directory, this function will attempt to build it by
+                       reading info from a local dump of MetaCyc database,
+                       metacycPath is the path to the MetaCyc data files
+   keepTransportRxns   include transportation reactions, which often have identical
+                       reactants and products that turn to be all-zero columns in
+                       the S matrix (optional, default false)
+   keepUnbalanced      include reactions cannot be balanced, usually
+                       because they are polymeric reactions or with
+                       specific difficulty in balancing class structures
+                       (optional, default false)
+   keepUndetermined    include reactions that have substrates lack chemical
+                       structures or with non-numerical coefficients (e.g. n+1)
+                       (optional, default false)
+
+   Output:
+   model     a model structure generated from the database. The following
+             fields are filled
+             id:             'MetaCyc'
+             name:    'Automatically generated from MetaCyc database'
+             rxns:           MetaCyc reaction ids
+             rxnNames:       Name for each reaction entry
+             mets:           MetaCyc compound ids. If the equations use
+                             stoichiometry such as ID(n+1) then the whole
+                             expression is saved as the id
+             pwys:           MetaCyc pathway id
+             eccodes:        Corresponding ec-number if available
+             rxnMiriams:     Contains reaction specific information such as
+                             associated RHEA and KEGG reaction ids
+             S:              Stoichiometric matrix
+             lb:             -1000 for all reactions
+             ub:             1000 for all reactions
+             rev:            1 for reversible and 0 for irreversible. For
+                             reactions present in pathway maps the reversibility
+                             is taken from there
+             b:              0 for all metabolites
+             version:        MetaCyc database version
+
+   If the file metaCycRxns.mat is in the RAVEN/external/metacyc directory, it
+   will be directly loaded instead of parsing the MetaCyc data files and
+   pre-prepared lists of MetaCyc transport and undetermined reactions.
+
+ Usage: model=getRxnsFromMetaCyc(metacycPath,keepTransportRxns,keepUnbalanced,keepUndetermined)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 function model=getRxnsFromMetaCyc(metacycPath,keepTransportRxns,keepUnbalanced,keepUndetermined)
+0002 % getRxnsFromMetaCyc
+0003 %   Retrieves reactions information from MetaCyc database
+0004 %
+0005 %   Input:
+0006 %   metacycPath         if metaCycRxns.mat is not in the RAVEN\external\metacyc
+0007 %                       directory, this function will attempt to build it by
+0008 %                       reading info from a local dump of MetaCyc database,
+0009 %                       metacycPath is the path to the MetaCyc data files
+0010 %   keepTransportRxns   include transportation reactions, which often have identical
+0011 %                       reactants and products that turn to be all-zero columns in
+0012 %                       the S matrix (optional, default false)
+0013 %   keepUnbalanced      include reactions cannot be balanced, usually
+0014 %                       because they are polymeric reactions or with
+0015 %                       specific difficulty in balancing class structures
+0016 %                       (optional, default false)
+0017 %   keepUndetermined    include reactions that have substrates lack chemical
+0018 %                       structures or with non-numerical coefficients (e.g. n+1)
+0019 %                       (optional, default false)
+0020 %
+0021 %   Output:
+0022 %   model     a model structure generated from the database. The following
+0023 %             fields are filled
+0024 %             id:             'MetaCyc'
+0025 %             name:    'Automatically generated from MetaCyc database'
+0026 %             rxns:           MetaCyc reaction ids
+0027 %             rxnNames:       Name for each reaction entry
+0028 %             mets:           MetaCyc compound ids. If the equations use
+0029 %                             stoichiometry such as ID(n+1) then the whole
+0030 %                             expression is saved as the id
+0031 %             pwys:           MetaCyc pathway id
+0032 %             eccodes:        Corresponding ec-number if available
+0033 %             rxnMiriams:     Contains reaction specific information such as
+0034 %                             associated RHEA and KEGG reaction ids
+0035 %             S:              Stoichiometric matrix
+0036 %             lb:             -1000 for all reactions
+0037 %             ub:             1000 for all reactions
+0038 %             rev:            1 for reversible and 0 for irreversible. For
+0039 %                             reactions present in pathway maps the reversibility
+0040 %                             is taken from there
+0041 %             b:              0 for all metabolites
+0042 %             version:        MetaCyc database version
+0043 %
+0044 %   If the file metaCycRxns.mat is in the RAVEN/external/metacyc directory, it
+0045 %   will be directly loaded instead of parsing the MetaCyc data files and
+0046 %   pre-prepared lists of MetaCyc transport and undetermined reactions.
+0047 %
+0048 % Usage: model=getRxnsFromMetaCyc(metacycPath,keepTransportRxns,keepUnbalanced,keepUndetermined)
+0049 
+0050 %NOTE: This is how one entry looks in the file
+0051 
+0052 % UNIQUE-ID - 4-HYDROXY-2-KETOPIMELATE-LYSIS-RXN
+0053 % TYPES - Small-Molecule-Reactions
+0054 % TYPES - Chemical-Reactions
+0055 % ATOM-MAPPINGS - (:NO-HYDROGEN-ENCODING (6 7 0 8 1 9 2 10 3 12 11 5 4) (((PYRUVATE 0 5) (SUCC-S-ALD 6 12)) ((CPD-804 0 12))))
+0056 % DBLINKS - (LIGAND-RXN "R01647" NIL |kr| 3650824949 NIL NIL)
+0057 % DBLINKS - (LIGAND-RXN "R01645" NIL |taltman| 3459474590 NIL NIL)
+0058 % EC-NUMBER - EC-4.1.2.52
+0059 % ^OFFICIAL? - T
+0060 % ENZYMATIC-REACTION - ENZRXN-3009
+0061 % IN-PATHWAY - 3-HYDROXYPHENYLACETATE-DEGRADATION-PWY
+0062 % LEFT - CPD-804
+0063 % ORPHAN? - :NO
+0064 % PHYSIOLOGICALLY-RELEVANT? - T
+0065 % REACTION-DIRECTION - LEFT-TO-RIGHT
+0066 % RIGHT - SUCC-S-ALD
+0067 % RIGHT - PYRUVATE
+0068 % //
+0069 
+0070 % A line that contains only '//' separates each object.
+0071 if nargin<1
+0072     ravenPath=findRAVENroot();
+0073     metacycPath=fullfile(ravenPath,'external','metacyc');
+0074 else
+0075     metacycPath=char(metacycPath);
+0076 end
+0077 if nargin<2
+0078     keepTransportRxns=false;
+0079 end
+0080 if nargin<3
+0081     keepUnbalanced=false;
+0082 end
+0083 if nargin<4
+0084     keepUndetermined=false;
+0085 end
+0086 
+0087 %Check if the reactions have been parsed before and saved. Directly load
+0088 %the model if so.
+0089 rxnsFile=fullfile(metacycPath,'metaCycRxns.mat');
+0090 metaCycRxnFile='reactions.dat';
+0091 metaCycPwyFile='pathway-links.dat';
+0092 
+0093 if exist(rxnsFile, 'file')
+0094     fprintf(['Importing MetaCyc reactions from ' strrep(rxnsFile,'\','/') '... ']);
+0095     load(rxnsFile);
+0096     fprintf('done\n');
+0097 else
+0098     fprintf(['Cannot locate ' strrep(rxnsFile,'\','/') '\nNow try to generate it from local MetaCyc data files...\n']);
+0099     if ~isfile(fullfile(metacycPath,metaCycRxnFile)) || ~isfile(fullfile(metacycPath,metaCycPwyFile))
+0100         EM=fprintf(['The files of reactions or pathways cannot be located, and should be downloaded from MetaCyc.\n']);
+0101         dispEM(EM);
+0102     else
+0103         metaCycRxns.id='MetaCyc';
+0104         metaCycRxns.name='Automatically generated from MetaCyc database';
+0105         
+0106         %Get pathway names and add them to the field of subSystems
+0107         fid = fopen(fullfile(metacycPath,metaCycPwyFile), 'r');
+0108         
+0109         %Keeps track of how many pathways that have been added
+0110         pwyCounter=0;
+0111         pwys=cell(10000,1);
+0112         pwyNames=cell(10000,1);
+0113         
+0114         %Loop through the file
+0115         while 1
+0116             %Get the next line
+0117             tline = fgetl(fid);
+0118             
+0119             %Abort at end of file
+0120             if ~ischar(tline)
+0121                 break;
+0122             end
+0123             
+0124             %Read in pathway ids and names
+0125             if ~strcmp(tline(1),'#')
+0126                 pwyCounter=pwyCounter+1;
+0127                 vars = regexp(tline, '\t', 'split');
+0128                 pwys{pwyCounter}=vars{1};
+0129                 pwyNames{pwyCounter}=vars{2};
+0130                 
+0131                 %Romve HTML symbols
+0132                 pwyNames{pwyCounter}=removeHTMLcodes(pwyNames{pwyCounter});
+0133                 
+0134             end
+0135         end
+0136         fclose(fid);
+0137         pwys=pwys(1:pwyCounter);
+0138         pwyNames=pwyNames(1:pwyCounter);
+0139         
+0140         %Preallocate memory for 50000 reactions
+0141         metaCycRxns.rxns=cell(50000,1);
+0142         metaCycRxns.rxnNames=cell(50000,1);
+0143         metaCycRxns.eccodes=cell(50000,1);
+0144         metaCycRxns.subSystems=cell(50000,1);
+0145         metaCycRxns.pwys=cell(50000,1);
+0146         metaCycRxns.rxnMiriams=cell(50000,1);
+0147         metaCycRxns.rxnReferences=cell(50000,1);
+0148         metaCycRxns.rev=ones(50000,1); %reversibility;
+0149         
+0150         rxnLinks.metacyc=cell(10000,1);
+0151         rxnLinks.kegg=cell(10000,1);
+0152         rxnLinks.check=cell(10000,1);
+0153         isSpontaneous=false(10000,1); %spontaneous;
+0154         UNBALANCED=false(10000,1);
+0155         UNDETERMINED=false(10000,1);
+0156         TRANSPORT={};                 %transport reactions;
+0157         
+0158         metaCycRxns.equations=cell(50000,1); %reaction equations
+0159         left=cell(50000,1); %Temporarily stores the equations
+0160         right=cell(50000,1); %Temporarily stores the equations
+0161         
+0162         %First load information on reaction ID, reaction name,, pathway,
+0163         %and ec-number
+0164         fid = fopen(fullfile(metacycPath,metaCycRxnFile), 'r');
+0165         
+0166         %Keeps track of how many reactions that have been added
+0167         rxnCounter=0;
+0168         addSpont=false;
+0169         dbLinkCounter=0;
+0170         
+0171         %Loop through the file
+0172         while 1
+0173             %Get the next line
+0174             tline = fgetl(fid);
+0175             
+0176             %Abort at end of file
+0177             if ~ischar(tline)
+0178                 break;
+0179             end
+0180 
+0181             % Get the version of MetaCyc database
+0182             if numel(tline)>11 && strcmp(tline(1:11),'# Version: ')
+0183                 version=tline(12:end);
+0184             end
+0185 
+0186             %Check if it is a new reaction
+0187             if numel(tline)>12 && strcmp(tline(1:12),'UNIQUE-ID - ')
+0188                 rxnCounter=rxnCounter+1;
+0189                 nPwys=0;
+0190                 
+0191                 %Add empty strings where there should be such
+0192                 metaCycRxns.rxnNames{rxnCounter}='';
+0193                 metaCycRxns.eccodes{rxnCounter}='';
+0194                 metaCycRxns.subSystems{rxnCounter}='';
+0195                 metaCycRxns.pwys{rxnCounter}='';
+0196                 metaCycRxns.equations{rxnCounter}='';
+0197                 metaCycRxns.rxnReferences{rxnCounter}='';
+0198                 reverse=0;   %Value for reversing the equation when necessary
+0199                 
+0200                 % A complex evaluation system for generating the equations
+0201                 left{rxnCounter}='';
+0202                 right{rxnCounter}='';
+0203                 coefficient='';
+0204                 templeft='';
+0205                 tempright='';
+0206                 % might be simplified with a better algorithem
+0207                 
+0208                 %Add reaction ID
+0209                 metaCycRxns.rxns{rxnCounter}=tline(13:end);
+0210                 
+0211             end
+0212             
+0213             %Add name
+0214             if numel(tline)>14 && strcmp(tline(1:14),'COMMON-NAME - ')
+0215                 metaCycRxns.rxnNames{rxnCounter}=tline(15:end);
+0216                 
+0217                 %Romve HTML symbols
+0218                 metaCycRxns.rxnNames{rxnCounter}=removeHTMLcodes(metaCycRxns.rxnNames{rxnCounter});
+0219             end
+0220             
+0221             %Add eccodes
+0222             if numel(tline)>15 && strcmp(tline(1:15),'EC-NUMBER - EC-')
+0223                 if isempty(metaCycRxns.eccodes{rxnCounter})
+0224                     metaCycRxns.eccodes{rxnCounter}=strcat('ec-code/',tline(16:end));
+0225                 else
+0226                     metaCycRxns.eccodes{rxnCounter}=strcat(metaCycRxns.eccodes{rxnCounter},';ec-code/',tline(16:end));
+0227                 end
+0228             end
+0229             if numel(tline)>16 && strcmp(tline(1:16),'EC-NUMBER - |EC-')
+0230                 if isempty(metaCycRxns.eccodes{rxnCounter})
+0231                     metaCycRxns.eccodes{rxnCounter}=strcat('ec-code/',tline(17:end-1));
+0232                 else
+0233                     metaCycRxns.eccodes{rxnCounter}=strcat(metaCycRxns.eccodes{rxnCounter},';ec-code/',tline(17:end-1));
+0234                 end
+0235             end
+0236             
+0237             %Add pathway id and assign pathway name to subSystem field
+0238             if numel(tline)>13 && strcmp(tline(1:13),'IN-PATHWAY - ')
+0239                 if isempty(metaCycRxns.pwys{rxnCounter})
+0240                     metaCycRxns.pwys{rxnCounter}=tline(14:end);
+0241                 else
+0242                     metaCycRxns.pwys{rxnCounter}=strcat(metaCycRxns.pwys{rxnCounter},';',tline(14:end));
+0243                 end
+0244                 
+0245                 [x, y]=ismember(tline(14:end),pwys);
+0246                 if x
+0247                     metaCycRxns.subSystems{rxnCounter,1}{numel(metaCycRxns.subSystems{rxnCounter,1})+1,1}=pwyNames{y};
+0248                 end
+0249             end
+0250             
+0251             %Add references (pubmed ids)
+0252             if numel(tline)>12 && strcmp(tline(1:12),'CITATIONS - ')
+0253                 if isempty(metaCycRxns.rxnReferences{rxnCounter})
+0254                     metaCycRxns.rxnReferences{rxnCounter}=strcat('pubmed/',tline(13:end));
+0255                 else
+0256                     metaCycRxns.rxnReferences{rxnCounter}=strcat(metaCycRxns.rxnReferences{rxnCounter},';pubmed/',tline(13:end));
+0257                 end
+0258             end
+0259             
+0260             %Add Miriam info (cross-links other database)
+0261             if numel(tline)>11 && strcmp(tline(1:11),'DBLINKS - (')
+0262                 dblink=tline(12:end);
+0263                 %KEGG reaction id
+0264                 if strcmp(dblink(1:12),'LIGAND-RXN "')
+0265                     dblink=dblink(13:end);
+0266                     s=strfind(dblink,'"');
+0267                     if any(s)
+0268                         dblink=dblink(1:s-1);
+0269                     end
+0270                     
+0271                     if isstruct(metaCycRxns.rxnMiriams{rxnCounter})
+0272                         addToIndex=numel(metaCycRxns.rxnMiriams{rxnCounter}.name)+1;
+0273                     else
+0274                         addToIndex=1;
+0275                     end
+0276                     tempStruct=metaCycRxns.rxnMiriams{rxnCounter};
+0277                     tempStruct.name{addToIndex,1}='kegg.reaction';
+0278                     tempStruct.value{addToIndex,1}=dblink;
+0279                     metaCycRxns.rxnMiriams{rxnCounter}=tempStruct;
+0280                     
+0281                     %For generating the rxnLinks structure
+0282                     dbLinkCounter=dbLinkCounter+1;
+0283                     rxnLinks.metacyc{dbLinkCounter}=metaCycRxns.rxns{rxnCounter};
+0284                     rxnLinks.kegg{dbLinkCounter}=dblink;
+0285                     rxnLinks.check{dbLinkCounter}=strcat(metaCycRxns.rxns{rxnCounter},dblink);
+0286                 end
+0287                 
+0288                 %RHEA reaction id
+0289                 if strcmp(dblink(1:6),'RHEA "')
+0290                     dblink=dblink(7:end);
+0291                     s=strfind(dblink,'"');
+0292                     if any(s)
+0293                         dblink=dblink(1:s-1);
+0294                     end
+0295                     
+0296                     if isstruct(metaCycRxns.rxnMiriams{rxnCounter})
+0297                         addToIndex=numel(metaCycRxns.rxnMiriams{rxnCounter}.name)+1;
+0298                     else
+0299                         addToIndex=1;
+0300                     end
+0301                     tempStruct=metaCycRxns.rxnMiriams{rxnCounter};
+0302                     tempStruct.name{addToIndex,1}='rhea';
+0303                     tempStruct.value{addToIndex,1}=dblink;
+0304                     metaCycRxns.rxnMiriams{rxnCounter}=tempStruct;
+0305                 end
+0306             end
+0307             
+0308             if numel(tline)>21 && strcmp(tline(1:21),'REACTION-DIRECTION - ')
+0309                 rxnDirection=tline(22:end);
+0310                 switch(rxnDirection)
+0311                     case 'IRREVERSIBLE-LEFT-TO-RIGHT'
+0312                         metaCycRxns.rev(rxnCounter,1)=0;
+0313                     case 'LEFT-TO-RIGHT'
+0314                         metaCycRxns.rev(rxnCounter,1)=0;
+0315                     case 'PHYSIOL-LEFT-TO-RIGHT'
+0316                         metaCycRxns.rev(rxnCounter,1)=0;
+0317                     case 'IRREVERSIBLE-RIGHT-TO-LEFT'
+0318                         metaCycRxns.rev(rxnCounter,1)=0;
+0319                         reverse=1;
+0320                     case 'RIGHT-TO-LEFT'
+0321                         metaCycRxns.rev(rxnCounter,1)=0;
+0322                         reverse=1;
+0323                     case 'PHYSIOL-RIGHT-TO-LEFT'
+0324                         metaCycRxns.rev(rxnCounter,1)=0;
+0325                         reverse=1;
+0326                 end
+0327             end
+0328             
+0329             %Tag transport reactions
+0330             if strcmp(tline,'TYPES - Transport-Reactions')
+0331                 TRANSPORT=[TRANSPORT;metaCycRxns.rxns{rxnCounter}];
+0332             end
+0333             
+0334             %Add spontaneous
+0335             if strcmp(tline,'SPONTANEOUS? - T')
+0336                 %metaCycRxns.spontaneous(rxnCounter,1)=1;
+0337                 isSpontaneous(rxnCounter)=true;
+0338             end
+0339             
+0340             %Extract mass-balance status
+0341             if numel(tline)>27 && strcmp(tline(1:27),'REACTION-BALANCE-STATUS - :')
+0342                 if isequal(tline(28:35), 'UNBALANC')
+0343                     UNBALANCED(rxnCounter)=true;
+0344                 elseif isequal(tline(28:35), 'UNDETERM')
+0345                     UNDETERMINED(rxnCounter)=true;
+0346                 end
+0347             end
+0348             
+0349             %Add left side equation
+0350             if numel(tline)>7 && strcmp(tline(1:7),'LEFT - ')
+0351                 if strcmp(left{rxnCounter},'')
+0352                     if strcmp(templeft,'')
+0353                         templeft=tline(8:end); % this is the real first, save to a temp variable
+0354                     else % count in the coefficient here
+0355                         if strcmp(coefficient,'')
+0356                             left{rxnCounter}=templeft;
+0357                         else
+0358                             left{rxnCounter}=strcat(coefficient,32,templeft);
+0359                             coefficient='';
+0360                         end
+0361                         templeft=tline(8:end);
+0362                     end
+0363                 else
+0364                     if strcmp(coefficient,'')
+0365                         left{rxnCounter}=strcat(left{rxnCounter},' +',32,templeft);
+0366                     else
+0367                         left{rxnCounter}=strcat(left{rxnCounter},' +',32,coefficient,32,templeft);
+0368                         coefficient='';
+0369                     end
+0370                     templeft=tline(8:end);
+0371                 end
+0372             end
+0373             
+0374             %Add right side equation
+0375             if numel(tline)>8 && strcmp(tline(1:8),'RIGHT - ')
+0376                 if strcmp(right{rxnCounter},'')
+0377                     if strcmp(tempright,'')
+0378                         
+0379                         % a complicated process for the last left
+0380                         % metabolite
+0381                         if strcmp(coefficient,'')
+0382                             if strcmp(left{rxnCounter},'')
+0383                                 left{rxnCounter}=templeft;
+0384                             else
+0385                                 left{rxnCounter}=strcat(left{rxnCounter},' +',32,templeft);
+0386                             end
+0387                             
+0388                         else
+0389                             if strcmp(left{rxnCounter},'')
+0390                                 left{rxnCounter}=strcat(coefficient,32,templeft);
+0391                             else
+0392                                 left{rxnCounter}=strcat(left{rxnCounter},' +',32,coefficient,32,templeft);
+0393                             end
+0394                             coefficient='';
+0395                         end
+0396                         % process end
+0397                         
+0398                         tempright=tline(9:end); % this is the real first, save to a temp variable
+0399                     else
+0400                         if strcmp(coefficient,'')
+0401                             right{rxnCounter}=tempright;
+0402                         else
+0403                             right{rxnCounter}=strcat(coefficient,32,tempright);
+0404                             coefficient='';
+0405                         end
+0406                         tempright=tline(9:end);
+0407                     end
+0408                 else
+0409                     if strcmp(coefficient,'')
+0410                         right{rxnCounter}=strcat(right{rxnCounter},' +',32,tempright);
+0411                     else
+0412                         right{rxnCounter}=strcat(right{rxnCounter},' +',32,coefficient,32,tempright);
+0413                         coefficient='';
+0414                     end
+0415                     tempright=tline(9:end);
+0416                 end
+0417                 
+0418             end
+0419             
+0420             if numel(tline)>15 && strcmp(tline(1:15),'^COEFFICIENT - ')
+0421                 coefficient=tline(16:end);
+0422             end
+0423             
+0424             %Generate equation at the end of each object section
+0425             if strcmp(tline,'//')
+0426                 
+0427                 % a complicated process for the last right metabolite,
+0428                 % sub-function is needed here
+0429                 if strcmp(coefficient,'')
+0430                     if strcmp(right{rxnCounter},'')
+0431                         right{rxnCounter}=tempright;
+0432                     else
+0433                         right{rxnCounter}=strcat(right{rxnCounter},' +',32,tempright);
+0434                     end
+0435                     
+0436                 else
+0437                     if strcmp(right{rxnCounter},'')
+0438                         right{rxnCounter}=strcat(coefficient,32,tempright);
+0439                     else
+0440                         right{rxnCounter}=strcat(right{rxnCounter},' +',32,coefficient,32,tempright);
+0441                     end
+0442                     coefficient='';
+0443                 end
+0444                 % process end
+0445                 
+0446                 %get the right direction symbol
+0447                 if metaCycRxns.rev(rxnCounter,1)
+0448                     symbol = ' <=>';
+0449                 else
+0450                     symbol = ' =>';
+0451                 end
+0452                 
+0453                 if reverse
+0454                     metaCycRxns.equations{rxnCounter}=strcat(right{rxnCounter},symbol,32,left{rxnCounter});
+0455                 else
+0456                     metaCycRxns.equations{rxnCounter}=strcat(left{rxnCounter},symbol,32,right{rxnCounter});
+0457                 end
+0458                 
+0459                 %Final equation check
+0460                 if strcmp(left{rxnCounter},'') || strcmp(right{rxnCounter},'')
+0461                     rxnCounter=rxnCounter-1;
+0462                     
+0463                 end
+0464                 
+0465             end
+0466             
+0467         end
+0468         %Close the file
+0469         fclose(fid);
+0470         
+0471         %===
+0472         UNBALANCED=metaCycRxns.rxns(UNBALANCED);
+0473         UNDETERMINED=metaCycRxns.rxns(UNDETERMINED);
+0474         isSpontaneous=metaCycRxns.rxns(isSpontaneous);
+0475         
+0476         %If too much space was allocated, shrink the model
+0477         metaCycRxns.rxns=metaCycRxns.rxns(1:rxnCounter);
+0478         metaCycRxns.rxnNames=metaCycRxns.rxnNames(1:rxnCounter);
+0479         metaCycRxns.eccodes=metaCycRxns.eccodes(1:rxnCounter);
+0480         metaCycRxns.equations=metaCycRxns.equations(1:rxnCounter);
+0481         metaCycRxns.rxnMiriams=metaCycRxns.rxnMiriams(1:rxnCounter);
+0482         metaCycRxns.rxnReferences=metaCycRxns.rxnReferences(1:rxnCounter);
+0483         metaCycRxns.subSystems=metaCycRxns.subSystems(1:rxnCounter);
+0484         metaCycRxns.pwys=metaCycRxns.pwys(1:rxnCounter);
+0485         metaCycRxns.rev=metaCycRxns.rev(1:rxnCounter,:);
+0486         
+0487         rxnLinks.kegg=rxnLinks.kegg(1:dbLinkCounter);
+0488         rxnLinks.metacyc=rxnLinks.metacyc(1:dbLinkCounter);
+0489         rxnLinks.check=rxnLinks.check(1:dbLinkCounter);
+0490         [~,index]=unique(rxnLinks.check);
+0491         rxnLinks.kegg=rxnLinks.kegg(index);
+0492         rxnLinks.metacyc=rxnLinks.metacyc(index);
+0493         rxnLinks=rmfield(rxnLinks,'check');
+0494         
+0495         %Construct the S matrix and list of metabolites
+0496         [S, mets, badRxns]=constructS(metaCycRxns.equations);
+0497         metaCycRxns.S=S;
+0498         metaCycRxns.mets=mets;
+0499         
+0500         %Add some stuff to get a correct model structure
+0501         metaCycRxns.ub=ones(rxnCounter,1)*1000;
+0502         metaCycRxns.lb=metaCycRxns.rev*-1000;
+0503         metaCycRxns.c=zeros(rxnCounter,1);
+0504         metaCycRxns.b=zeros(numel(metaCycRxns.mets),1);
+0505         metaCycRxns.version=version;
+0506         
+0507         %Save the model structure
+0508         save(rxnsFile,'metaCycRxns','rxnLinks','TRANSPORT','UNBALANCED','UNDETERMINED','isSpontaneous');
+0509         fprintf(['New metaCycRxns.mat has been successfully updated!\n\n']);
+0510     end
+0511 end
+0512 
+0513 %Deal with reactions that are labeled as "TRANSPORT", "UNBALANCED", or
+0514 %"UNDETERMINED" (depending on settings).
+0515 model=metaCycRxns;
+0516 if keepTransportRxns==false
+0517     model=removeReactions(model,intersect(TRANSPORT,model.rxns),true,true);
+0518 end
+0519 if keepUnbalanced==false
+0520     model=removeReactions(model,intersect(UNBALANCED,model.rxns),true,true);
+0521 end
+0522 if keepUndetermined==false
+0523     model=removeReactions(model,intersect(UNDETERMINED,model.rxns),true,true);
+0524 end
+0525 end
+0526 
+0527 %Sub function for romving HTML symbols from the names of reaction and
+0528 %pathway
+0529 function newString=removeHTMLcodes(string)
+0530 string=regexprep(string,'<(\w+)>','');
+0531 string=regexprep(string,'</(\w+)>','');
+0532 string=regexprep(string,'[&;]','');
+0533 newString=string;
+0534 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/external/metacyc/index.html b/doc/external/metacyc/index.html new file mode 100644 index 000000000..10337f067 --- /dev/null +++ b/doc/external/metacyc/index.html @@ -0,0 +1,31 @@ + + + + Index for Directory external\metacyc + + + + + + + + + + +
< Master indexIndex for external\metacyc >
+ +

Index for external\metacyc

+ +

Matlab files in this directory:

+ +
 addSpontaneousRxnsaddSpontaneousRxns
 getEnzymesFromMetaCycgetEnzymesFromMetaCyc
 getMetaCycModelForOrganismgetMetaCycModelForOrganism
 getMetsFromMetaCycgetMetsFromMetaCyc
 getModelFromMetaCycgetModelFromMetaCyc
 getRxnsFromMetaCycgetRxnsFromMetaCyc
 linkMetaCycKEGGRxnslinkMetaCycKEGGRxns
+ +

Other Matlab-specific files in this directory:

+
    +
  • metaCycEnzymes.mat
  • metaCycMets.mat
  • metaCycRxns.mat
+ + +
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/external/metacyc/linkMetaCycKEGGRxns.html b/doc/external/metacyc/linkMetaCycKEGGRxns.html new file mode 100644 index 000000000..0ffecbbe1 --- /dev/null +++ b/doc/external/metacyc/linkMetaCycKEGGRxns.html @@ -0,0 +1,159 @@ + + + + Description of linkMetaCycKEGGRxns + + + + + + + + + +
Home > external > metacyc > linkMetaCycKEGGRxns.m
+ + + +

linkMetaCycKEGGRxns +

+ +

PURPOSE ^

+
linkMetaCycKEGGRxns
+ +

SYNOPSIS ^

+
function linkMetaCycKEGGRxns
+ +

DESCRIPTION ^

+
 linkMetaCycKEGGRxns
+   Link additional MetaCyc and KEGG reactions through metabolite mapping
+   This function only need to run once when the MetaCyc database is updated
+
+   NOTE: No arguments are required
+
+ Usage: linkMetaCycKEGGRxns
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function linkMetaCycKEGGRxns
+0002 % linkMetaCycKEGGRxns
+0003 %   Link additional MetaCyc and KEGG reactions through metabolite mapping
+0004 %   This function only need to run once when the MetaCyc database is updated
+0005 %
+0006 %   NOTE: No arguments are required
+0007 %
+0008 % Usage: linkMetaCycKEGGRxns
+0009 
+0010 load('metaCycRxns.mat'); %load MetaCyc reactions
+0011 fprintf('NOTE: Importing MetaCyc reactions...\n');
+0012 metaCycModel = metaCycRxns;
+0013 metaCycModel.rxnFrom=cell(numel(metaCycModel.rxns),1);
+0014 metaCycModel.rxnFrom(:)={'MetaCyc'};
+0015 metaCycModel.grRules={};
+0016 metaCycModel.genes={};
+0017 metaCycModel.rxnGeneMat=sparse(numel(metaCycModel.rxns),1);
+0018 
+0019 
+0020 keggModel=getRxnsFromKEGG(); %load KEGG reactions
+0021 
+0022 %Remove KEGG reactions with MetaCyc links based on original rxnLinks
+0023 rxnToRemove=intersect(rxnLinks.kegg,keggModel.rxns);
+0024 rxnToRemove=unique(rxnToRemove);
+0025 shrinkedKeggModel=removeReactions(keggModel,rxnToRemove,true,true);
+0026 
+0027 fprintf('Mapping MetaCyc and KEGG reactions...\n');
+0028 %Resolve the shared but unmapped reactions (through mapping the involved
+0029 %metabolites). Replace mets information in KEGG model with the
+0030 %corresponding ones in MetaCyc.
+0031 load('metaCycMets.mat');
+0032 for i=1:numel(shrinkedKeggModel.mets)
+0033     [a, b]=ismember(shrinkedKeggModel.mets{i},metaCycMets.keggid);
+0034     if a
+0035         %Replace the met ids
+0036         shrinkedKeggModel.mets{i}=metaCycMets.mets{b};
+0037         shrinkedKeggModel.metNames{i}=metaCycMets.mets{b};
+0038     end
+0039 end
+0040 
+0041 %Prepare for the merge of KEGG and MetaCyc super models
+0042 
+0043 %Adding fields (comps, compNames, metNames, metComps)
+0044 metaCycModel.comps={'s'};
+0045 metaCycModel.compNames={'System'};
+0046 metaCycModel.metNames=metaCycModel.mets;
+0047 if ~isfield(metaCycModel,'metComps')
+0048     metaCycModel.metComps=ones(numel(metaCycModel.mets),1);
+0049 end
+0050 
+0051 shrinkedKeggModel.comps={'s'};
+0052 shrinkedKeggModel.compNames={'System'};
+0053 shrinkedKeggModel.metNames=shrinkedKeggModel.mets;
+0054 if ~isfield(shrinkedKeggModel,'metComps')
+0055     shrinkedKeggModel.metComps=ones(numel(shrinkedKeggModel.mets),1);
+0056 end
+0057 
+0058 %Merge models
+0059 mappingModel=mergeModels({shrinkedKeggModel metaCycModel},'metNames');
+0060 
+0061 %Remove compounds proton and water because KEGG reactions often miss them
+0062 mappingModel=removeMets(mappingModel,{'PROTON','WATER'});
+0063 
+0064 %Find same/similiar reactions by check identical columns in S matrix Go
+0065 %through the pure KEGG model and collect rxns id that have identical
+0066 %reactions to the ones in MetaCyc
+0067 I=find(ismember(mappingModel.rxnFrom,'KEGG'));
+0068 for i=1:numel(I)
+0069     testRxn=mappingModel.S(:,I(i));
+0070     match=find(~any(bsxfun(@minus, mappingModel.S,testRxn))); %Figure out the matched columns in S matrix
+0071     % if ~isequal(match,I(i))
+0072     count=numel(match);
+0073     if count>1 %Only consider one-to-one match here
+0074         for j=2:count
+0075             %Only consider the match between KEGG and MetaCyc
+0076             if isequal(mappingModel.rxnFrom{match(j)},'MetaCyc')
+0077                 %disp([mappingModel.rxns(match(1))
+0078                 %mappingModel.rxns(match(j))]); %keep this for later
+0079                 %checking
+0080                 rxnLinks.kegg=[rxnLinks.kegg;mappingModel.rxns(match(1))];
+0081                 rxnLinks.metacyc=[rxnLinks.metacyc;mappingModel.rxns(match(j))];
+0082             end
+0083         end
+0084     end
+0085     % end
+0086 end
+0087 
+0088 % Load orginal rxnLinks
+0089 numLink=numel(rxnLinks.kegg);
+0090 rxnLinks.check=cell(numLink,1);
+0091 for i=1:numLink
+0092     rxnLinks.check{i}=strcat(rxnLinks.kegg{i},rxnLinks.metacyc{i});
+0093 end
+0094 
+0095 [~, index]=unique(rxnLinks.check);
+0096 rxnLinks.kegg=rxnLinks.kegg(index);
+0097 rxnLinks.metacyc=rxnLinks.metacyc(index);
+0098 rxnLinks=rmfield(rxnLinks,'check');
+0099 
+0100 %Get the MetaCyc path and update the metaCycRxns.mat
+0101 ravenPath=findRAVENroot();
+0102 rxnsFile=fullfile(ravenPath,'external','metacyc','metaCycRxns.mat');
+0103 save(rxnsFile,'metaCycRxns','rxnLinks','TRANSPORT','UNBALANCED','UNDETERMINED','isSpontaneous');
+0104 fprintf(['Reaction associations between MetaCyc and KEGG have been successfully updated!\n\n']);
+0105 
+0106 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/external/parseScores.html b/doc/external/parseScores.html new file mode 100644 index 000000000..d82f859d4 --- /dev/null +++ b/doc/external/parseScores.html @@ -0,0 +1,189 @@ + + + + Description of parseScores + + + + + + + + + +
Home > external > parseScores.m
+ + + +

parseScores +

+ +

PURPOSE ^

+
parseScores
+ +

SYNOPSIS ^

+
function GSS = parseScores(inputFile, predictor)
+ +

DESCRIPTION ^

+
 parseScores
+    Parse the output from a predictor to generate the GSS
+
+    Input:
+    inputFile    a file with the output from the predictor
+    predictor    the predictor that was used. 'wolf' for WoLF PSORT, 'cello'
+               for CELLO, 'deeploc' for DeepLoc (optional, default 'wolf')
+
+    Output:
+    GSS         a gene scoring structure to be used in predictLocalization
+
+    The function normalizes the scores so that the best score for each gene
+    is 1.0.
+
+    Usage: GSS = parseScores(inputFile, predictor)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function GSS = parseScores(inputFile, predictor)
+0002 % parseScores
+0003 %    Parse the output from a predictor to generate the GSS
+0004 %
+0005 %    Input:
+0006 %    inputFile    a file with the output from the predictor
+0007 %    predictor    the predictor that was used. 'wolf' for WoLF PSORT, 'cello'
+0008 %               for CELLO, 'deeploc' for DeepLoc (optional, default 'wolf')
+0009 %
+0010 %    Output:
+0011 %    GSS         a gene scoring structure to be used in predictLocalization
+0012 %
+0013 %    The function normalizes the scores so that the best score for each gene
+0014 %    is 1.0.
+0015 %
+0016 %    Usage: GSS = parseScores(inputFile, predictor)
+0017 
+0018 if nargin<2
+0019     predictor='wolf';
+0020 else
+0021     predictor=char(predictor);
+0022 end
+0023 
+0024 fid=fopen(inputFile,'r');
+0025 
+0026 if fid<1
+0027     EM='Could not open file';
+0028     dispEM(EM);
+0029 end
+0030 
+0031 if strcmpi(predictor,'wolf')
+0032     A=textscan(fid,'%s','Delimiter','\n','CommentStyle','#');
+0033     
+0034     %Each element should be for one gene, but some of them are on the form
+0035     %"Pc20g11350: treating 9 X's as Glycines". Those should be removed
+0036     I=~cellfun(@any,strfind(A{1},'treating'));
+0037     
+0038     B=regexp(A{1}(I),' ','split');
+0039     
+0040     %Reserve space for stuff
+0041     GSS.compartments={};
+0042     GSS.scores=[]; %Do not know number of comps yet
+0043     GSS.genes=cell(numel(B),1);
+0044     
+0045     %Parsing is a bit cumbersome as ', ' is used as a delimiter in some
+0046     %cases and ' ' in others. Use strrep to get rid of ','
+0047     for i=1:numel(B)
+0048         b=strrep(B{i},',','');
+0049         GSS.genes{i}=b{1};
+0050         
+0051         %Then go through the compartments and add new ones as they are
+0052         %found
+0053         for j=2:2:numel(b)-1
+0054             [~, J]=ismember(b(j),GSS.compartments);
+0055             
+0056             %Add new compartment if it does not exist
+0057             if J==0
+0058                 GSS.compartments=[GSS.compartments;b(j)];
+0059                 J=numel(GSS.compartments);
+0060                 GSS.scores=[GSS.scores zeros(numel(B),1)];
+0061             end
+0062             
+0063             GSS.scores(i,J)=str2double(b(j+1));
+0064         end
+0065     end
+0066 elseif strcmpi(predictor,'cello')
+0067     fid=fopen(inputFile,'r');
+0068     %Read the title line and fetch the list of compartments
+0069     tline = fgetl(fid);
+0070     tline=regexprep(tline,'^.+#Combined:\t','');
+0071     tline=regexprep(tline,'\t#Most-likely-Location.+','');
+0072     GSS.compartments=transpose(regexp(tline,'\t','split'));
+0073     
+0074     %Now iterate through the following lines in the file. Each row
+0075     %corresponds to one gene and it consists of the scores for
+0076     %compartments. Gene name is in the end of each line
+0077     row=0;
+0078     while 1
+0079         row=row+1;
+0080         tline = fgetl(fid);
+0081         if ~ischar(tline)
+0082             break;
+0083         end
+0084         tline=regexprep(tline,'^.+:\t','');
+0085         tline=regexprep(tline,' .+','');
+0086         tline=regexp(tline,'\t','split');
+0087         GSS.scores(row,:)=str2double(tline(1:numel(GSS.compartments)));
+0088         GSS.genes{row,1}=tline{1,end};
+0089     end
+0090 elseif strcmpi(predictor,'deeploc')
+0091     fid=fopen(inputFile,'r');
+0092     %Read the title line and fetch the list of compartments
+0093     tline = fgetl(fid);
+0094     GSS.compartments=regexp(tline,',','split');
+0095     GSS.compartments=transpose(GSS.compartments(4:end));
+0096     
+0097     %Now iterate through the following lines in the file. Each row
+0098     %corresponds to one gene and it consists of the scores for
+0099     %compartments. Gene name is in the end of each line
+0100     row=0;
+0101     while 1
+0102         row=row+1;
+0103         tline = fgetl(fid);
+0104         if ~ischar(tline)
+0105             break;
+0106         end
+0107         tline=regexp(tline,',','split');
+0108         GSS.scores(row,:)=str2double(tline(4:end));
+0109         GSS.genes{row,1}=tline{1,1};
+0110     end
+0111 end
+0112 
+0113 %Check if there are duplicate genes
+0114 [~, J, K]=unique(GSS.genes);
+0115 
+0116 if numel(J)~=numel(K)
+0117     EM='There are duplicate genes in the input file';
+0118     dispEM(EM,false);
+0119     GSS.genes=GSS.genes(J);
+0120     GSS.scores=GSS.scores(J,:);
+0121 end
+0122 
+0123 %Normalize
+0124 I=max(GSS.scores,[],2);
+0125 GSS.scores=bsxfun(@times, GSS.scores, 1./I);
+0126 
+0127 fclose(fid);
+0128 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/external/updateDocumentation.html b/doc/external/updateDocumentation.html new file mode 100644 index 000000000..8967f8766 --- /dev/null +++ b/doc/external/updateDocumentation.html @@ -0,0 +1,95 @@ + + + + Description of updateDocumentation + + + + + + + + + +
Home > external > updateDocumentation.m
+ + + +

updateDocumentation +

+ +

PURPOSE ^

+
updateDocumentation
+ +

SYNOPSIS ^

+
function updateDocumentation()
+ +

DESCRIPTION ^

+
 updateDocumentation
+    Updates HTML documentation files for all RAVEN functions. It should
+    only be used when preparing `develop` branch for a new RAVEN release
+
+    Usage: updateDocumentation()
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function updateDocumentation()
+0002 % updateDocumentation
+0003 %    Updates HTML documentation files for all RAVEN functions. It should
+0004 %    only be used when preparing `develop` branch for a new RAVEN release
+0005 %
+0006 %    Usage: updateDocumentation()
+0007 
+0008 %Get the RAVEN path
+0009 ravenDir=findRAVENroot();
+0010 %Make sure that RAVEN-provided m2html is used
+0011 path(fullfile(ravenDir,'software','m2html'),path);
+0012 %Get a non-redundant list of RAVEN subdirectories containing MATLAB
+0013 %functions. Absolute paths are not compatible with M2HTML, so convert them
+0014 %to the relative paths instead.
+0015 ravenDirs=dir(fullfile(ravenDir,'**/*.m'));
+0016 ravenDirs=unique({ravenDirs.folder})';
+0017 
+0018 %Get rid of MATLAB functions from external software
+0019 ravenDirs(startsWith(ravenDirs,strcat(ravenDir,filesep,'software')))=[];
+0020 ravenDirs(startsWith(ravenDirs,strcat(ravenDir,filesep,'legacy',filesep,'software')))=[];
+0021 
+0022 %Remove keggModel.mat if it exists
+0023 if exist(fullfile(ravenDir,'external','kegg','keggModel.mat'), 'file') == 2
+0024     delete(fullfile(ravenDir,'external','kegg','keggModel.mat'));
+0025 end
+0026 
+0027 %Remove existing "doc" directory from RAVEN
+0028 rmdir(fullfile(ravenDir,'doc'),'s');
+0029 
+0030 %Make relative path
+0031 relStart = numel(ravenDir)+2;
+0032 for i=1:numel(ravenDirs)
+0033     ravenDirs{i,1} = ravenDirs{i,1}(relStart:end);
+0034 end
+0035 
+0036 %Save the current working directory and go to RAVEN root directory
+0037 originalDir=pwd;
+0038 cd(ravenDir);
+0039 %Generate HTML documentation files for RAVEN MATLAB functions
+0040 m2html('mFiles',ravenDirs,'htmldir','doc');
+0041 %Go back to the original working directory
+0042 cd(originalDir);
+0043 
+0044 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/fortran.png b/doc/fortran.png new file mode 100644 index 0000000000000000000000000000000000000000..350c572ee38fc5aa8cef025284caa41a46921cbf GIT binary patch literal 265 zcmV+k0rvihP)z zQ4Yf(2!?U#(c~&{CVCaUn|okwjJWCAv@Y{YACUYt5I|c;L@*Nz0Eo!wFm8gG7quL( z=eJ8jF~;-zT!i-?03M^mxSQz{PD1(=o)3a5h-huxIH1YJR@TpAUHLpGAzkjqF33Gq z5HW;M#1ulv?Ojv&dqVG&6;xWfSwIyu&pDe3Y?b*+^Nvd@T*dL)Y-z<7!R9u;!a16o zt!IDE1;u=7(6;lN@7iT2j)+8Ll6#n$r@xl|p4XvuY#=TA`S#1W+5VQEsg98Zwj;#Z P00000NkvXXu0mjf06Tac literal 0 HcmV?d00001 diff --git a/doc/hp.png b/doc/hp.png new file mode 100644 index 0000000000000000000000000000000000000000..d09f988fb289d659869dbb1b2f199fd967a93958 GIT binary patch literal 255 zcmVz z%MHUI3_wlAXs`;N$*f{_qX$Rw9FO zez{B`r8K|JmvGJjz-@IJXS2Omg-^gRJ-6O z&=syLR&U^^a}=eRZLpT@KTChlV@n^^it_t*Wz253r911aWh5p(A;kay002ovPDHLk FV1l-WYkL3y literal 0 HcmV?d00001 diff --git a/doc/hpa/index.html b/doc/hpa/index.html new file mode 100644 index 000000000..a659dab22 --- /dev/null +++ b/doc/hpa/index.html @@ -0,0 +1,29 @@ + + + + Index for Directory hpa + + + + + + + + + + +
< Master indexIndex for hpa >
+ +

Index for hpa

+ +

Matlab files in this directory:

+ +
 parseHPAparseHPA
 parseHPArnaparseHPA
 scoreModelscoreRxns
+ + + + +
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/hpa/parseHPA.html b/doc/hpa/parseHPA.html new file mode 100644 index 000000000..c6064594f --- /dev/null +++ b/doc/hpa/parseHPA.html @@ -0,0 +1,188 @@ + + + + Description of parseHPA + + + + + + + + + +
Home > hpa > parseHPA.m
+ + + +

parseHPA +

+ +

PURPOSE ^

+
parseHPA
+ +

SYNOPSIS ^

+
function hpaData=parseHPA(fileName, version)
+ +

DESCRIPTION ^

+
 parseHPA
+   Parses a database dump of the Human Protein Atlas (HPA)
+
+   Input:
+   fileName            comma- or tab-separated database dump of HPA. For details
+                       regarding the format, see
+                       http://www.proteinatlas.org/about/download.
+   version             version of HPA [optional, default=19]
+
+
+   Output:
+   hpaData
+       genes               cell array with the unique gene names. In
+                           version >=18 this is the ensemble name, see
+                           geneNames below for the names in ver >=18
+       geneNames           cell array with the gene names, indexed the
+                           same way as genes.
+       tissues             cell array with the tissue names. The list may not be
+                           unique, as there can be multiple cell types per tissue
+       celltypes           cell array with the cell type names for each tissue
+       levels              cell array with the unique expression levels
+       types               cell array with the unique evidence types
+       reliabilities       cell array with the unique reliability levels
+
+       gene2Level          gene-to-expression level mapping in sparse matrix form.
+                           The value for element i,j is the index in
+                           hpaData.levels of gene i in cell type j
+       gene2Type           gene-to-evidence type mapping in sparse matrix form.
+                           The value for element i,j is the index in
+                           hpaData.types of gene i in cell type j. Doesn't
+                           exist in version >=18.
+       gene2Reliability    gene-to-reliability level mapping in sparse matrix form.
+                           The value for element i,j is the index in
+                           hpaData.reliabilities of gene i in cell type j
+
+ Usage: hpaData=parseHPA(fileName,version)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function hpaData=parseHPA(fileName, version)
+0002 % parseHPA
+0003 %   Parses a database dump of the Human Protein Atlas (HPA)
+0004 %
+0005 %   Input:
+0006 %   fileName            comma- or tab-separated database dump of HPA. For details
+0007 %                       regarding the format, see
+0008 %                       http://www.proteinatlas.org/about/download.
+0009 %   version             version of HPA [optional, default=19]
+0010 %
+0011 %
+0012 %   Output:
+0013 %   hpaData
+0014 %       genes               cell array with the unique gene names. In
+0015 %                           version >=18 this is the ensemble name, see
+0016 %                           geneNames below for the names in ver >=18
+0017 %       geneNames           cell array with the gene names, indexed the
+0018 %                           same way as genes.
+0019 %       tissues             cell array with the tissue names. The list may not be
+0020 %                           unique, as there can be multiple cell types per tissue
+0021 %       celltypes           cell array with the cell type names for each tissue
+0022 %       levels              cell array with the unique expression levels
+0023 %       types               cell array with the unique evidence types
+0024 %       reliabilities       cell array with the unique reliability levels
+0025 %
+0026 %       gene2Level          gene-to-expression level mapping in sparse matrix form.
+0027 %                           The value for element i,j is the index in
+0028 %                           hpaData.levels of gene i in cell type j
+0029 %       gene2Type           gene-to-evidence type mapping in sparse matrix form.
+0030 %                           The value for element i,j is the index in
+0031 %                           hpaData.types of gene i in cell type j. Doesn't
+0032 %                           exist in version >=18.
+0033 %       gene2Reliability    gene-to-reliability level mapping in sparse matrix form.
+0034 %                           The value for element i,j is the index in
+0035 %                           hpaData.reliabilities of gene i in cell type j
+0036 %
+0037 % Usage: hpaData=parseHPA(fileName,version)
+0038 
+0039 if nargin<2
+0040     version=19; %Change this and add code for more versions when the current HPA version is increased and the format is changed
+0041 end
+0042 
+0043 fileName=char(fileName);
+0044 if ~isfile(fileName)
+0045     error('HPA file %s cannot be found',string(fileName));
+0046 end
+0047 
+0048 if (version >= 17)
+0049     fid=fopen(fileName,'r');
+0050     hpa=textscan(fid,'%q %q %q %q %q %q','Delimiter','\t');
+0051     fclose(fid);
+0052     
+0053     %Go through and see if the headers match what was expected
+0054     headers={'Gene' 'Gene name' 'Tissue' 'Cell type' 'Level' 'Reliability'};
+0055     for i=1:numel(headers)
+0056         if ~strcmpi(headers(i),hpa{i}(1))
+0057             EM=['Could not find the header "' headers{i} '". Make sure that the input file matches the format specified at http://www.proteinatlas.org/about/download'];
+0058             dispEM(EM);
+0059         end
+0060         %Remove the header line here
+0061         hpa{i}(1)=[];
+0062     end
+0063     
+0064     %Get the unique values of each data type
+0065     [hpaData.genes, P, I]=unique(hpa{1});
+0066     hpaData.geneNames=hpa{2}(P); %make this vector use the index as genes
+0067     [~, J, K]=unique(strcat(hpa{3},'€',hpa{4}));
+0068     hpaData.tissues=hpa{3}(J);
+0069     hpaData.celltypes=hpa{4}(J);
+0070     [hpaData.levels, ~, L]=unique(hpa{5});
+0071     [hpaData.reliabilities, ~, N]=unique(hpa{6});
+0072     
+0073     %Map the data to be sparse matrises instead
+0074     hpaData.gene2Level=sparse(I,K,L,numel(hpaData.genes),numel(hpaData.tissues));
+0075     hpaData.gene2Reliability=sparse(I,K,N,numel(hpaData.genes),numel(hpaData.tissues));
+0076 else
+0077     fid=fopen(fileName,'r');
+0078     hpa=textscan(fid,'%q %q %q %q %q %q','Delimiter',',');
+0079     fclose(fid);
+0080     
+0081     %Go through and see if the headers match what was expected
+0082     headers={'Gene' 'Tissue' 'Cell type' 'Level' 'Expression type' 'Reliability'};
+0083     for i=1:numel(headers)
+0084         if ~strcmpi(headers(i),hpa{i}(1))
+0085             EM=['Could not find the header "' headers{i} '". Make sure that the input file matches the format specified at http://www.proteinatlas.org/about/download'];
+0086             dispEM(EM);
+0087         end
+0088         %Remove the header line here
+0089         hpa{i}(1)=[];
+0090     end
+0091     
+0092     %Get the unique values of each data type
+0093     [hpaData.genes, ~, I]=unique(hpa{1});
+0094     [~, J, K]=unique(strcat(hpa{2},'€',hpa{3}));
+0095     hpaData.tissues=hpa{2}(J);
+0096     hpaData.celltypes=hpa{3}(J);
+0097     [hpaData.levels, ~, L]=unique(hpa{4});
+0098     [hpaData.types, ~, M]=unique(hpa{5});
+0099     [hpaData.reliabilities, ~, N]=unique(hpa{6});
+0100     
+0101     %Map the data to be sparse matrises instead
+0102     hpaData.gene2Level=sparse(I,K,L,numel(hpaData.genes),numel(hpaData.tissues));
+0103     hpaData.gene2Type=sparse(I,K,M,numel(hpaData.genes),numel(hpaData.tissues));
+0104     hpaData.gene2Reliability=sparse(I,K,N,numel(hpaData.genes),numel(hpaData.tissues));
+0105 end
+0106 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/hpa/parseHPArna.html b/doc/hpa/parseHPArna.html new file mode 100644 index 000000000..8aae52fce --- /dev/null +++ b/doc/hpa/parseHPArna.html @@ -0,0 +1,136 @@ + + + + Description of parseHPArna + + + + + + + + + +
Home > hpa > parseHPArna.m
+ + + +

parseHPArna +

+ +

PURPOSE ^

+
parseHPA
+ +

SYNOPSIS ^

+
function arrayData=parseHPArna(fileName, version)
+ +

DESCRIPTION ^

+
 parseHPA
+   Parses a database dump of the Human Protein Atlas (HPA) RNA-Seq data.
+
+   Input:
+   fileName            tab-separated database dump of HPA RNA data. For
+                       details regarding the format, see
+                       http://www.proteinatlas.org/about/download.
+   version             version of HPA [optional, default=19]
+
+
+   Output:
+   arrayData
+       genes               cell array with the unique ensemble gene IDs
+       geneNames           cell array with the gene names (gene abbrevs)
+       tissues             cell array with the tissue names
+       levels              matrix of gene expression levels (TPM), where
+                           rows correspond to genes, and columns
+                           correspond to tissues
+
+ Usage: arrayData=parseHPArna(fileName,version)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function arrayData=parseHPArna(fileName, version)
+0002 % parseHPA
+0003 %   Parses a database dump of the Human Protein Atlas (HPA) RNA-Seq data.
+0004 %
+0005 %   Input:
+0006 %   fileName            tab-separated database dump of HPA RNA data. For
+0007 %                       details regarding the format, see
+0008 %                       http://www.proteinatlas.org/about/download.
+0009 %   version             version of HPA [optional, default=19]
+0010 %
+0011 %
+0012 %   Output:
+0013 %   arrayData
+0014 %       genes               cell array with the unique ensemble gene IDs
+0015 %       geneNames           cell array with the gene names (gene abbrevs)
+0016 %       tissues             cell array with the tissue names
+0017 %       levels              matrix of gene expression levels (TPM), where
+0018 %                           rows correspond to genes, and columns
+0019 %                           correspond to tissues
+0020 %
+0021 % Usage: arrayData=parseHPArna(fileName,version)
+0022 
+0023 if nargin<2
+0024     %Change this and add code for more versions when the current HPA
+0025     %version is increased and the format is changed
+0026     version=19;
+0027 end
+0028 
+0029 fileName=char(fileName);
+0030 if ~isfile(fileName)
+0031     error('HPA file %s cannot be found', string(fileName));
+0032 end
+0033 
+0034 %NOTE! This function assumes that the first 4 columns contain (in order):
+0035 % (1) gene ensembl ID, (2) gene abbrev, (3) tissue name,  (4) TPM value
+0036 if (version == 19)
+0037     headers={'Gene' 'Gene name' 'Tissue' 'TPM' 'pTPM' 'NX'};
+0038 elseif (version == 18)
+0039     headers={'Gene' 'Gene name' 'Sample' 'Value' 'Unit'};
+0040 else
+0041     error('Only HPA versions 18 and 19 are currently supported.');
+0042 end
+0043 
+0044 %extract data from file
+0045 formatSpec = strip(repmat('%q ', 1, numel(headers)));
+0046 fid=fopen(fileName, 'r');
+0047 hpa=textscan(fid, formatSpec, 'Delimiter', '\t');
+0048 fclose(fid);
+0049 
+0050 %Go through and see if the headers match what was expected
+0051 for i=1:numel(headers)
+0052     if ~strcmpi(headers(i),hpa{i}(1))
+0053         EM=['Could not find the header "' headers{i} '". Make sure that the input file matches the format specified at http://www.proteinatlas.org/about/download'];
+0054         dispEM(EM);
+0055     end
+0056     %Remove the header line here
+0057     hpa{i}(1)=[];
+0058 end
+0059 
+0060 %Get unique gene IDs and tissue names
+0061 [arrayData.genes, P, I] = unique(hpa{1});
+0062 arrayData.geneNames = hpa{2}(P);  % retrieve corresponding gene names
+0063 [arrayData.tissues, ~, J] = unique(hpa{3});
+0064 
+0065 %Now extract the gene levels and organize into matrix
+0066 arrayData.levels = NaN(max(I),max(J));
+0067 linearInd = sub2ind(size(arrayData.levels),I,J);
+0068 arrayData.levels(linearInd) = str2double(hpa{4});
+0069     
+0070
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/hpa/scoreModel.html b/doc/hpa/scoreModel.html new file mode 100644 index 000000000..5e37f5449 --- /dev/null +++ b/doc/hpa/scoreModel.html @@ -0,0 +1,428 @@ + + + + Description of scoreModel + + + + + + + + + +
Home > hpa > scoreModel.m
+ + + +

scoreModel +

+ +

PURPOSE ^

+
scoreRxns
+ +

SYNOPSIS ^

+
function [rxnScores, geneScores, hpaScores, arrayScores]=scoreModel(model,hpaData,arrayData,tissue,celltype,noGeneScore,multipleGeneScoring,multipleCellScoring,hpaLevelScores)
+ +

DESCRIPTION ^

+
 scoreRxns
+   Scores the reactions and genes in a model based on expression data
+   from HPA and/or gene arrays
+
+   Input:
+   model               a model structure
+   hpaData             HPA data structure from parseHPA (optional if arrayData is
+                       supplied, default [])
+   arrayData           gene expression data structure (optional if hpaData is
+                       supplied, default [])
+       genes           cell array with the unique gene names
+       tissues         cell array with the tissue names. The list may not be
+                       unique, as there can be multiple cell types per tissue
+       celltypes       cell array with the cell type names for each tissue
+       levels          GENESxTISSUES array with the expression level for
+                       each gene in each tissue/celltype. NaN should be
+                       used when no measurement was performed
+       threshold       a single value or a vector of gene expression 
+                       thresholds, above which genes are considered to be
+                       "expressed". (optional, by default, the mean expression
+                       levels of each gene across all tissues in arrayData
+                       will be used as the threshold values)
+   tissue              tissue to score for. Should exist in either
+                       hpaData.tissues or arrayData.tissues
+   celltype            cell type to score for. Should exist in either
+                       hpaData.celltypes or arrayData.celltypes for this
+                       tissue (optional, default is to use the best values
+                       among all the cell types for the tissue. Use [] if
+                       you want to supply more arguments)
+   noGeneScore         score for reactions without genes (optional, default -2)
+   multipleGeneScoring determines how scores are calculated for reactions
+                       with several genes ('best' or 'average')
+                       (optional, default 'best')
+   multipleCellScoring determines how scores are calculated when several
+                       cell types are used ('best' or 'average')
+                       (optional, default 'best')
+   hpaLevelScores      structure with numerical scores for the expression
+                       level categories from HPA. The structure should have a
+                       "names" and a "scores" field (optional, see code for
+                       default scores)
+
+
+   Output:
+   rxnScores       scores for each of the reactions in model
+   geneScores      scores for each of the genes in model. Genes which are
+                   not in the dataset(s) have -Inf as scores
+   hpaScores       scores for each of the genes in model if only taking hpaData
+                   into account. Genes which are not in the dataset(s)
+                   have -Inf as scores
+   arrayScores     scores for each of the genes in model if only taking arrayData
+                   into account. Genes which are not in the dataset(s)
+                   have -Inf as scores
+
+ Usage: [rxnScores, geneScores, hpaScores, arrayScores]=scoreModel(model,...
+               hpaData,arrayData,tissue,celltype,noGeneScore,multipleGeneScoring,...
+               multipleCellScoring,hpaLevelScores)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 function [rxnScores, geneScores, hpaScores, arrayScores]=scoreModel(model,hpaData,arrayData,tissue,celltype,noGeneScore,multipleGeneScoring,multipleCellScoring,hpaLevelScores)
+0002 % scoreRxns
+0003 %   Scores the reactions and genes in a model based on expression data
+0004 %   from HPA and/or gene arrays
+0005 %
+0006 %   Input:
+0007 %   model               a model structure
+0008 %   hpaData             HPA data structure from parseHPA (optional if arrayData is
+0009 %                       supplied, default [])
+0010 %   arrayData           gene expression data structure (optional if hpaData is
+0011 %                       supplied, default [])
+0012 %       genes           cell array with the unique gene names
+0013 %       tissues         cell array with the tissue names. The list may not be
+0014 %                       unique, as there can be multiple cell types per tissue
+0015 %       celltypes       cell array with the cell type names for each tissue
+0016 %       levels          GENESxTISSUES array with the expression level for
+0017 %                       each gene in each tissue/celltype. NaN should be
+0018 %                       used when no measurement was performed
+0019 %       threshold       a single value or a vector of gene expression
+0020 %                       thresholds, above which genes are considered to be
+0021 %                       "expressed". (optional, by default, the mean expression
+0022 %                       levels of each gene across all tissues in arrayData
+0023 %                       will be used as the threshold values)
+0024 %   tissue              tissue to score for. Should exist in either
+0025 %                       hpaData.tissues or arrayData.tissues
+0026 %   celltype            cell type to score for. Should exist in either
+0027 %                       hpaData.celltypes or arrayData.celltypes for this
+0028 %                       tissue (optional, default is to use the best values
+0029 %                       among all the cell types for the tissue. Use [] if
+0030 %                       you want to supply more arguments)
+0031 %   noGeneScore         score for reactions without genes (optional, default -2)
+0032 %   multipleGeneScoring determines how scores are calculated for reactions
+0033 %                       with several genes ('best' or 'average')
+0034 %                       (optional, default 'best')
+0035 %   multipleCellScoring determines how scores are calculated when several
+0036 %                       cell types are used ('best' or 'average')
+0037 %                       (optional, default 'best')
+0038 %   hpaLevelScores      structure with numerical scores for the expression
+0039 %                       level categories from HPA. The structure should have a
+0040 %                       "names" and a "scores" field (optional, see code for
+0041 %                       default scores)
+0042 %
+0043 %
+0044 %   Output:
+0045 %   rxnScores       scores for each of the reactions in model
+0046 %   geneScores      scores for each of the genes in model. Genes which are
+0047 %                   not in the dataset(s) have -Inf as scores
+0048 %   hpaScores       scores for each of the genes in model if only taking hpaData
+0049 %                   into account. Genes which are not in the dataset(s)
+0050 %                   have -Inf as scores
+0051 %   arrayScores     scores for each of the genes in model if only taking arrayData
+0052 %                   into account. Genes which are not in the dataset(s)
+0053 %                   have -Inf as scores
+0054 %
+0055 % Usage: [rxnScores, geneScores, hpaScores, arrayScores]=scoreModel(model,...
+0056 %               hpaData,arrayData,tissue,celltype,noGeneScore,multipleGeneScoring,...
+0057 %               multipleCellScoring,hpaLevelScores)
+0058 
+0059 if nargin<3
+0060     arrayData=[];
+0061 end
+0062 if nargin<5
+0063     celltype=[];
+0064 else
+0065     celltype=char(celltype);
+0066 end
+0067 if nargin<6
+0068     noGeneScore=-2;
+0069 end
+0070 if nargin<7
+0071     multipleGeneScoring='best';
+0072 else
+0073     multipleGeneScoring=char(multipleGeneScoring);
+0074 end
+0075 if nargin<8
+0076     multipleCellScoring='best';
+0077 else
+0078     multipleCellScoring=char(multipleCellScoring);    
+0079 end
+0080 if nargin<9
+0081     %The first four are for APE, the other ones for staining
+0082     hpaLevelScores.names={'High' 'Medium' 'Low' 'None' 'Strong' 'Moderate' 'Weak' 'Negative' 'Not detected'};
+0083     hpaLevelScores.scores=[20 15 10 -8 20 15 10 -8 -8];
+0084 end
+0085 
+0086 if isempty(hpaData) && isempty(arrayData)
+0087     EM='Must supply hpaData, arrayData or both';
+0088     dispEM(EM);
+0089 end
+0090 if ~strcmpi(multipleGeneScoring,'best') && ~strcmpi(multipleGeneScoring,'average')
+0091     EM='Valid options for multipleGeneScoring are "best" or "average"';
+0092     dispEM(EM);
+0093 end
+0094 if ~strcmpi(multipleCellScoring,'best') && ~strcmpi(multipleCellScoring,'average')
+0095     EM='Valid options for multipleCellScoring are "best" or "average"';
+0096     dispEM(EM);
+0097 end
+0098 
+0099 
+0100 %Throw an error if array data for only one tissue is supplied without
+0101 %specifying threshold values
+0102 if ~isempty(arrayData)
+0103     if numel(unique(arrayData.tissues))<2
+0104         if ~isfield(arrayData,'threshold') || isempty(arrayData.threshold)
+0105             EM='arrayData must contain measurements for at least two celltypes/tissues since the score is calculated based on the expression level compared to the overall average';
+0106             dispEM(EM);
+0107         end
+0108     end
+0109 end
+0110 
+0111 %Process arrayData.threshold if necessary
+0112 if isfield(arrayData,'threshold') && (numel(arrayData.threshold) == 1)
+0113     % if only a single gene threshold value is provided, then just
+0114     % duplicate this value for all genes.
+0115     arrayData.threshold = arrayData.threshold*ones(size(arrayData.genes));
+0116 end
+0117 
+0118 %This is so that the code can ignore which combination of input data that is
+0119 %used
+0120 if isempty(arrayData)
+0121     arrayData.genes={};
+0122     arrayData.tissues={};
+0123     arrayData.celltypes={};
+0124     arrayData.levels=[];
+0125     arrayData.threshold=[];
+0126 end
+0127 if isempty(hpaData)
+0128     hpaData.genes={};
+0129     hpaData.tissues={};
+0130     hpaData.celltypes={};
+0131     hpaData.levels={};
+0132     hpaData.types={};
+0133     hpaData.reliabilities={};
+0134     hpaData.gene2Level=[];
+0135     hpaData.gene2Type=[];
+0136     hpaData.gene2Reliability=[];
+0137 end
+0138 
+0139 %Check that the tissue exists
+0140 if ~ismember(upper(tissue),upper(hpaData.tissues)) && ~ismember(upper(tissue),upper(arrayData.tissues))
+0141     EM='The tissue name does not match';
+0142     dispEM(EM);
+0143 end
+0144 if any(celltype)
+0145     %Check that both data types has cell type defined if that is to be used
+0146     if ~isfield(hpaData,'celltypes') || ~isfield(arrayData,'celltypes')
+0147         EM='Both hpaData and arrayData must contain cell type information if cell type is to be used';
+0148         dispEM(EM);
+0149     end
+0150     if ~ismember(upper(celltype),upper(hpaData.celltypes)) && ~ismember(upper(celltype),upper(arrayData.celltypes))
+0151         EM='The cell type name does not match';
+0152         dispEM(EM);
+0153     end
+0154 end
+0155 
+0156 %Some preprocessing of the structures to speed up a little Remove all
+0157 %tissues that are not the correct one
+0158 J=~strcmpi(hpaData.tissues,tissue);
+0159 
+0160 %If cell type is supplied, then only keep that cell type
+0161 if any(celltype)
+0162     J=J | ~strcmpi(hpaData.celltypes,celltype);
+0163 end
+0164 
+0165 hpaData.tissues(J)=[];
+0166 if isfield(hpaData,'celltypes')
+0167     hpaData.celltypes(J)=[];
+0168 end
+0169 if isfield(hpaData,'gene2Level')
+0170     hpaData.gene2Level(:,J)=[];
+0171 end
+0172 if isfield(hpaData,'gene2Type')
+0173     hpaData.gene2Type(:,J)=[];
+0174 end
+0175 if isfield(hpaData,'gene2Reliability')
+0176     hpaData.gene2Reliability(:,J)=[];
+0177 end
+0178 
+0179 %Remove all genes from the structures that are not in model or that aren't
+0180 %measured in the tissue
+0181 if ~isempty(hpaData.genes) %This should not be necessary, but the summation is a 0x1 matrix and the other is []
+0182     I=~ismember(hpaData.genes,model.genes) | sum(hpaData.gene2Level,2)==0;
+0183 else
+0184     I=[];
+0185 end
+0186 hpaData.genes(I)=[];
+0187 if isfield(hpaData,'gene2Level')
+0188     hpaData.gene2Level(I,:)=[];
+0189 end
+0190 if isfield(hpaData,'gene2Type')
+0191     hpaData.gene2Type(I,:)=[];
+0192 end
+0193 if isfield(hpaData,'gene2Reliability')
+0194     hpaData.gene2Reliability(I,:)=[];
+0195 end
+0196 
+0197 I=strcmpi(arrayData.tissues,tissue);
+0198 %If cell type is supplied, then only keep that cell type
+0199 if any(celltype)
+0200     I=I & strcmpi(arrayData.celltypes,celltype);
+0201 end
+0202 
+0203 %Remove all genes from the structures that are not in model or that aren't
+0204 %measured in the tissue
+0205 J=~ismember(arrayData.genes,model.genes) | myAll(isnan(arrayData.levels(:,I)),2);
+0206 arrayData.genes(J)=[];
+0207 arrayData.levels(J,:)=[];
+0208 if isfield(arrayData,'threshold')
+0209     arrayData.threshold(J) = [];
+0210 end
+0211 
+0212 %Calculate the scores for the arrayData. These scores are calculated for
+0213 %each genes from its fold change between the tissue/celltype(s) in question
+0214 %and all other celltypes. This is a lower quality data than protein
+0215 %abundance, since a gene that is equally highly expressed in all cell types
+0216 %will have a score of 0.0. These scores are therefore only used for genes
+0217 %for which there is no HPA data available. The fold changes are transformed
+0218 %as min(log(x),10) for x>1 and max(log(x),-5) for x<1 in order to have
+0219 %negative scores for lower expressed genes and to scale the scrores to have
+0220 %somewhat lower weights than the HPA scores
+0221 tempArrayLevels=arrayData.levels;
+0222 tempArrayLevels(isnan(tempArrayLevels))=0;
+0223 if isfield(arrayData,'threshold') && ~isempty(arrayData.threshold)
+0224     % if provided, the user-supplied expression threshold value(s) will be
+0225     % used as the "average" expression level to which each gene is
+0226     % compared.
+0227     average=arrayData.threshold;
+0228 else
+0229     average=sum(tempArrayLevels,2)./sum(~isnan(arrayData.levels),2);
+0230 end
+0231 if strcmpi(multipleCellScoring,'best')
+0232     current=max(tempArrayLevels(:,I),[],2);
+0233 else
+0234     current=sum(tempArrayLevels(:,I),2)./sum(~isnan(arrayData.levels(:,I)),2);
+0235 end
+0236 if ~isempty(current)
+0237     aScores=5*log(current./average);
+0238 else
+0239     aScores=[];
+0240 end
+0241 aScores(aScores>0)=min(aScores(aScores>0),10);
+0242 aScores(aScores<0)=max(aScores(aScores<0),-5);
+0243 aScores(isnan(aScores)) = -5;  % NaNs occur when gene expression is zero across all tissues
+0244 
+0245 %Map the HPA levels to scores
+0246 [I, J]=ismember(upper(hpaData.levels),upper(hpaLevelScores.names));
+0247 if ~all(I)
+0248     EM='There are expression level categories that do not match to hpaLevelScores';
+0249     dispEM(EM);
+0250 end
+0251 [K, L, M]=find(hpaData.gene2Level);
+0252 scores=hpaLevelScores.scores(J);
+0253 if strcmpi(multipleCellScoring,'best')
+0254     hScores=max(sparse(K,L,scores(M),numel(hpaData.genes),numel(hpaData.tissues)),[],2);
+0255 else
+0256     hScores=mean(sparse(K,L,scores(M),numel(hpaData.genes),numel(hpaData.tissues)),2);
+0257 end
+0258 
+0259 %Get the scores for the genes, only use HPA if available
+0260 geneScores=inf(numel(model.genes),1)*-1;
+0261 hpaScores=geneScores;
+0262 arrayScores=geneScores;
+0263 
+0264 [I, J]=ismember(model.genes,hpaData.genes);
+0265 hpaScores(I)=hScores(J(I));
+0266 geneScores(I)=hScores(J(I));
+0267 [I, J]=ismember(model.genes,arrayData.genes);
+0268 arrayScores(I)=aScores(J(I));
+0269 geneScores(I & myIsInf(geneScores))=aScores(J(I & myIsInf(geneScores)));
+0270 
+0271 %Remove the genes that have no data from the model
+0272 I=ismember(model.genes,hpaData.genes) | ismember(model.genes,arrayData.genes);
+0273 model.genes(~I)=[];
+0274 model.rxnGeneMat(:,~I)=[];
+0275 
+0276 %Map the genes to the HPA/array genes
+0277 [hpaExist, hpaMap]=ismember(model.genes,hpaData.genes);
+0278 [arrayExist, arrayMap]=ismember(model.genes,arrayData.genes);
+0279 
+0280 %Set the default scores for reactions without genes
+0281 rxnScores=ones(numel(model.rxns),1)*noGeneScore;
+0282 
+0283 %Loop through the reactions and calculate the scores
+0284 for i=1:numel(model.rxns)
+0285     %Check if it has genes
+0286     I=find(model.rxnGeneMat(i,:));
+0287     if any(I)
+0288         %If any of the genes exist in hpaData, then don't use arrayData
+0289         if any(hpaExist(I))
+0290             %At least one gene was found in HPA
+0291             if strcmpi(multipleGeneScoring,'best')
+0292                 rxnScores(i)=max(hScores(hpaMap(I(hpaExist(I)))));
+0293             else
+0294                 rxnScores(i)=mean(hScores(hpaMap(I(hpaExist(I)))));
+0295             end
+0296         else
+0297             %Use array data
+0298             if any(arrayExist(I))
+0299                 %At least one gene was found in the array data
+0300                 if strcmpi(multipleGeneScoring,'best')
+0301                     rxnScores(i)=max(aScores(arrayMap(I(arrayExist(I)))));
+0302                 else
+0303                     rxnScores(i)=mean(aScores(arrayMap(I(arrayExist(I)))));
+0304                 end
+0305             end
+0306         end
+0307     end
+0308 end
+0309 end
+0310 
+0311 %This is because isinf and all returns 0x1 for empty set, which gives a
+0312 %concatenation error. Do like this instead of having many if statements
+0313 function y=myIsInf(x)
+0314 y=isinf(x);
+0315 if isempty(y)
+0316     y=[];
+0317 end
+0318 end
+0319 function y=myAll(x,dim)
+0320 y=all(x,dim);
+0321 if isempty(y)
+0322     y=[];
+0323 end
+0324 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/index.html b/doc/index.html new file mode 100644 index 000000000..c9521aa81 --- /dev/null +++ b/doc/index.html @@ -0,0 +1,81 @@ + + + + Matlab Index + + + + + + + + + +

Matlab Index

+

Matlab Directories

+ +

Matlab Files found in these Directories

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FSEOF emptyOrTextOrCellOfText getObjectiveString ravenCobraWrapper
INITStepDesc emptyOrTextScalar getPathwayDimensions readYAMLmodel
ManualINITTests expandModel getPhylDist removeBadRxns
SBMLFromExcel exportForGit getRxnsFromKEGG removeGenes
addExchangeRxns exportModel getRxnsFromMetaCyc removeIdentifierPrefix
addGenesRaven exportModelToSIF getRxnsInComp removeLowScoreGenes
addIdentifierPrefix exportToExcelFormat getToolboxVersion removeMets
addJavaPaths exportToTabDelimited getTransportRxns removeRavenFromPath
addMets extractMiriam getWSLpath removeReactions
addRavenToUserPath fillGaps getWoLFScores replaceMets
addRxns fillGapsLargeTests groupRxnScores reporterMetabolites
addRxnsGenesMets fillGapsSmallTests guessComposition rescaleModelForINIT
addSpontaneousRxns findGeneDeletions haveFlux reverseRxns
addTransport findRAVENroot hmmerTests runDynamicFBA
analyzeSampling fitParameters importExcelModel runINIT
blastPlusTests fitTasks importExportTests runPhenotypePhasePlane
buildEquation followChanged importModel runProductionEnvelope
canConsume followFluxes linkMetaCycKEGGRxns runRAVENtests
canProduce ftINIT loadSheet runRobustnessAnalysis
cdhitTests ftINITFillGaps loadWorkbook runSimpleOptKnock
changeGeneAssoc ftINITFillGapsForAllTasks mafftTests scoreComplexModel
changeGrRules ftINITFillGapsMILP makeFakeBlastStructure scoreModel
changeRxns ftINITInternalAlg makeSomething setColorToMapRxns
checkFileExistence gapReport mapCompartments setExchangeBounds
checkFunctionUniqueness generateNewIds mapPathwayRxnNames setOmicDataToRxns
checkInstallation getAllRxnsFromGenes markPathwayWithExpression setParam
checkModelStruct getAllSubGraphs markPathwayWithFluxes setRavenSolver
checkProduction getAllowedBounds mergeCompartments setTitle
checkRxn getBlast mergeLinear simplifyModel
checkSolution getBlastFromExcel mergeModels solveLP
checkTasks getColorCodes mergeModelsTests solveQP
checkTasksTests getDiamond miriamTests solverTests
cleanSheet getElementalBalance modelAbilitiesTests sortIdentifiers
closeModel getEnzymesFromMetaCyc modelConversionTests sortModel
colorPathway getEssentialRxns modelCurationTests standardizeGrRules
colorSubsystem getExchangeRxns modelSortingTests standardizeModelFieldOrder
combineMetaCycKEGGModels getExprForRxnScore optimizeProb startup
compareMultipleModels getExpressionStructure parallelPoolRAVEN tinitTests
compareRxnsGenesMetsComps getFluxZ parseFormulas trimPathway
constructEquations getFullPath parseHPA tutorial1
constructMultiFasta getGenesFromGrRules parseHPArna tutorial2
constructPathwayFromCelldesigner getGenesFromKEGG parseRxnEqu tutorial2_solutions
constructS getINITModel parseScores tutorial3
consumeSomething getINITSteps parseTaskList tutorial3_solutions
contractModel getIndexes permuteModel tutorial4
convertCharArray getKEGGModelForOrganism plotAdditionalInfo tutorial4_solutions
convertToIrrev getMD5Hash plotLabels tutorial5
copyToComps getMetaCycModelForOrganism predictLocalization tutorial6
deleteUnusedGenes getMetsFromKEGG prepINITModel updateDocumentation
diamondTests getMetsFromMetaCyc printFluxes writeSheet
dispEM getMetsInComp printModel writeYAMLmodel
drawMap getMinNrFluxes printModelStats
drawPathway getModelFromHomology printOrange
editMiriam getModelFromKEGG qMOMA
emptyOrLogicalScalar getModelFromMetaCyc randomSampling
+ + +
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/installation/addRavenToUserPath.html b/doc/installation/addRavenToUserPath.html new file mode 100644 index 000000000..aeef3805d --- /dev/null +++ b/doc/installation/addRavenToUserPath.html @@ -0,0 +1,98 @@ + + + + Description of addRavenToUserPath + + + + + + + + + +
Home > installation > addRavenToUserPath.m
+ + + +

addRavenToUserPath +

+ +

PURPOSE ^

+
This function writes a startup.m file in the userpath, adding RAVEN (and
+ +

SYNOPSIS ^

+
function addRavenToUserPath(overwrite)
+ +

DESCRIPTION ^

+
 This function writes a startup.m file in the userpath, adding RAVEN (and
+ all subdirectories) to the path each time Matlab is started.
+ This function is useful if the user has no rights to save paths to the
+ pathdef.m file in the matlabroot, for instance due to a lack of admin
+ rights. As the startup.m file in the userpath automatically runs with
+ each Matlab start, the paths are automatically loaded.
+
+   overwrite       logical, whether startup.m in the userpath should
+                   overwritten (otherwise the RAVEN paths are appended)
+                   (optional, default true)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function addRavenToUserPath(overwrite)
+0002 % This function writes a startup.m file in the userpath, adding RAVEN (and
+0003 % all subdirectories) to the path each time Matlab is started.
+0004 % This function is useful if the user has no rights to save paths to the
+0005 % pathdef.m file in the matlabroot, for instance due to a lack of admin
+0006 % rights. As the startup.m file in the userpath automatically runs with
+0007 % each Matlab start, the paths are automatically loaded.
+0008 %
+0009 %   overwrite       logical, whether startup.m in the userpath should
+0010 %                   overwritten (otherwise the RAVEN paths are appended)
+0011 %                   (optional, default true)
+0012 
+0013 if nargin<1
+0014     overwrite=true;
+0015 end
+0016 
+0017 % Get current RAVEN directory
+0018 ravenDir=findRAVENroot();
+0019 
+0020 % Lists all subdirectories
+0021 subpath=regexp(genpath(ravenDir),pathsep,'split');
+0022 % Remove .git and doc folders
+0023 pathsToKeep=cellfun(@(x) isempty(strfind(x,'.git')),subpath) & cellfun(@(x) isempty(strfind(x,'doc')),subpath);
+0024 % Only keep useful paths
+0025 subpath = subpath(pathsToKeep);
+0026 subpath = subpath(1:end-1); % Remove last entry, is empty field
+0027 
+0028 % Write startup.m file
+0029 if overwrite
+0030     fid=fopen(fullfile(userpath,'startup.m'),'w');
+0031     fprintf(fid,'%sn','%%% RAVEN path');
+0032 else
+0033     fid=fopen(fullfile(userpath,'startup.m'),'a');
+0034     fprintf(fid,'n%sn','%%% RAVEN path');
+0035 end
+0036 fprintf(fid,'%sn',strcat('addpath(''',subpath{1},''',...'));
+0037 for i=2(length(subpath)-1)
+0038     fprintf(fid,'t%sn',strcat('''',subpath{i},''',...'));
+0039 end
+0040 fprintf(fid,'t%s',strcat('''',subpath{length(subpath)},''');'));
+0041 fclose(fid);
+0042 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/installation/checkFunctionUniqueness.html b/doc/installation/checkFunctionUniqueness.html new file mode 100644 index 000000000..5b55f77af --- /dev/null +++ b/doc/installation/checkFunctionUniqueness.html @@ -0,0 +1,161 @@ + + + + Description of checkFunctionUniqueness + + + + + + + + + +
Home > installation > checkFunctionUniqueness.m
+ + + +

checkFunctionUniqueness +

+ +

PURPOSE ^

+
checkFunctionUniqueness
+ +

SYNOPSIS ^

+
function status = checkFunctionUniqueness(altDirs)
+ +

DESCRIPTION ^

+
 checkFunctionUniqueness
+   Checks whether RAVEN toolbox functions are unique across other
+   toolboxes or user-created functions accessible in Matlab pathlist.
+
+ Input:
+   altDirs     cell array of alternative directories with functions,
+               should only be specified if this function is used for other
+               purposes, NOT when looking for RAVEN toolbox functions.
+
+ Output:
+   status      true if all functions are unique, otherwise false
+
+ Usage: checkFunctionUniqueness()
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function status = checkFunctionUniqueness(altDirs)
+0002 % checkFunctionUniqueness
+0003 %   Checks whether RAVEN toolbox functions are unique across other
+0004 %   toolboxes or user-created functions accessible in Matlab pathlist.
+0005 %
+0006 % Input:
+0007 %   altDirs     cell array of alternative directories with functions,
+0008 %               should only be specified if this function is used for other
+0009 %               purposes, NOT when looking for RAVEN toolbox functions.
+0010 %
+0011 % Output:
+0012 %   status      true if all functions are unique, otherwise false
+0013 %
+0014 % Usage: checkFunctionUniqueness()
+0015 
+0016 if nargin<1
+0017     %Get the RAVEN path
+0018     ravenDir=findRAVENroot();
+0019     
+0020     %Now getting all RAVEN functions recursively;
+0021     temp_res1=dir([ravenDir '/*/*.m']);
+0022     temp_res2=dir([ravenDir '/*/*/*.m']);
+0023     
+0024     ravenFunctions={temp_res1.name,temp_res2.name}';
+0025 else
+0026     if ispc
+0027         splitChar = ';';
+0028     else
+0029         splitChar = ':';
+0030     end
+0031     altDirs = strsplit(altDirs,splitChar)';
+0032     ravenFunctions={};
+0033     for i=1:numel(altDirs)
+0034         temp_res=dir(fullfile(char(altDirs(i)),'*.m'));
+0035         ravenFunctions = [ravenFunctions, temp_res.name];
+0036     end
+0037     ravenFunctions=ravenFunctions';
+0038     ravenDir=altDirs;
+0039 end
+0040 
+0041 %startup.m is not a normal function, any startup.m in the path should run
+0042 %during startup, so duplicate use of this name is fine
+0043 ravenFunctions=ravenFunctions(~ismember(ravenFunctions,'startup.m'));
+0044 
+0045 %Getting all the paths added to Matlab
+0046 if ispc
+0047     matlabPaths=regexp(path, ';', 'split')';
+0048 elseif isunix
+0049     matlabPaths=regexp(path, ':', 'split')';
+0050 end
+0051 
+0052 overlapPath={};
+0053 overlapFunctions={};
+0054 multiRaven=false;
+0055 multiFunction=false;
+0056 
+0057 for i=1:numel(matlabPaths)
+0058     if ~startsWith(matlabPaths{i},ravenDir)
+0059         temp_res=dir([matlabPaths{i} '/*.m']);
+0060         if ~isempty(temp_res)
+0061             pathFunctions={temp_res.name}';
+0062         else
+0063             pathFunctions='';
+0064         end
+0065         if ~isempty(pathFunctions) && ~any(ismember('Contents.m',pathFunctions))
+0066             if any(ismember(ravenFunctions,pathFunctions))
+0067                 if sum(ismember(ravenFunctions,pathFunctions))>(numel(ravenFunctions)/4)
+0068                     multiRaven=true;
+0069                 else
+0070                     multiFunction=true;
+0071                     overlapPath = [overlapPath, matlabPaths(i)];
+0072                     overlapFunctions = [overlapFunctions, {ravenFunctions(ismember(ravenFunctions,pathFunctions))}];
+0073                 end
+0074             end
+0075         end
+0076     end
+0077 end
+0078 
+0079 if multiRaven==true || multiFunction == true
+0080         if nargout > 0
+0081             status = false;
+0082         else
+0083             fprintf('Fail\n')
+0084         end
+0085     if multiRaven==true && nargin < 1
+0086         error(['Multiple RAVEN versions detected in MATLAB path. Remove all ',...
+0087                'RAVEN directories from the MATLAB path with removeRavenFromPath(), ',...
+0088                'or manually remove them. Afterwards, re-run checkInstallation']);
+0089     elseif multiFunction == true
+0090         for i=1:numel(overlapPath)
+0091             fprintf(['   Duplicate functions in ',regexprep(overlapPath{i},'(\\)','\\$1'),'\n']);
+0092             fprintf(['     ' strjoin(overlapFunctions{i},'\n     ') '\n']);
+0093         end
+0094     fprintf('   Resolve conflicting functions to avoid unexpected behaviour\n');
+0095     end
+0096 else
+0097     if nargout > 0
+0098         status = true;
+0099     else
+0100         fprintf('Pass\n')
+0101     end
+0102 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/installation/checkInstallation.html b/doc/installation/checkInstallation.html new file mode 100644 index 000000000..a36271d48 --- /dev/null +++ b/doc/installation/checkInstallation.html @@ -0,0 +1,501 @@ + + + + Description of checkInstallation + + + + + + + + + +
Home > installation > checkInstallation.m
+ + + +

checkInstallation +

+ +

PURPOSE ^

+
checkInstallation
+ +

SYNOPSIS ^

+
function [currVer, installType] = checkInstallation(developMode,checkBinaries)
+ +

DESCRIPTION ^

+
 checkInstallation
+   The purpose of this function is to check if all necessary functions are
+   installed and working. It also checks whether there are any functions
+   with overlapping names between RAVEN and other toolboxes or
+   user-defined functions, which are accessible from MATLAB pathlist
+
+ Input: 
+   developMode     logical indicating development mode, which includes
+                   testing of binaries that are required to update KEGG
+                   HMMs (optional, default false). If 'versionOnly' is
+                   specified, only the version is reported as currVer, no
+                   further installation or tests are performed.
+   checkBinaries   logical whether non-developMode binaries should be
+                   checked for functionality. If false, it overwrites
+                   developMode. Default true.
+
+ Output:
+   currVer         current RAVEN version
+   installType     how RAVEN is installed
+                   0:  via git (as .git folder is found)
+                   1:  as MATLAB Add-On
+                   2:  neither of the above, direct download of ZIP file
+                   This matches the installations mentioned in the wiki:
+                   https://github.com/SysBioChalmers/RAVEN/wiki/Installation
+                   0 = advanced / 1 = easy / 2 = medium
+
+ Usage: [currVer, installType] = checkInstallation(developMode)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 function [currVer, installType] = checkInstallation(developMode,checkBinaries)
+0002 % checkInstallation
+0003 %   The purpose of this function is to check if all necessary functions are
+0004 %   installed and working. It also checks whether there are any functions
+0005 %   with overlapping names between RAVEN and other toolboxes or
+0006 %   user-defined functions, which are accessible from MATLAB pathlist
+0007 %
+0008 % Input:
+0009 %   developMode     logical indicating development mode, which includes
+0010 %                   testing of binaries that are required to update KEGG
+0011 %                   HMMs (optional, default false). If 'versionOnly' is
+0012 %                   specified, only the version is reported as currVer, no
+0013 %                   further installation or tests are performed.
+0014 %   checkBinaries   logical whether non-developMode binaries should be
+0015 %                   checked for functionality. If false, it overwrites
+0016 %                   developMode. Default true.
+0017 %
+0018 % Output:
+0019 %   currVer         current RAVEN version
+0020 %   installType     how RAVEN is installed
+0021 %                   0:  via git (as .git folder is found)
+0022 %                   1:  as MATLAB Add-On
+0023 %                   2:  neither of the above, direct download of ZIP file
+0024 %                   This matches the installations mentioned in the wiki:
+0025 %                   https://github.com/SysBioChalmers/RAVEN/wiki/Installation
+0026 %                   0 = advanced / 1 = easy / 2 = medium
+0027 %
+0028 % Usage: [currVer, installType] = checkInstallation(developMode)
+0029 
+0030 if nargin<1
+0031     developMode=false;
+0032 end
+0033 if nargin<2
+0034     checkBinaries=true;
+0035 end
+0036 if ischar(developMode) && strcmp(developMode,'versionOnly')
+0037     versionOnly = true;
+0038 else
+0039     versionOnly = false;
+0040 end
+0041 
+0042 %Get the RAVEN path
+0043 [ST, I]=dbstack('-completenames');
+0044 [ravenDir,~,~]=fileparts(fileparts(ST(I).file));
+0045 
+0046 installType = 2; % If neither git nor add-on, then ZIP was downloaded
+0047 addList = matlab.addons.installedAddons;
+0048 if isfolder(fullfile(ravenDir,'.git'))
+0049     installType = 0;
+0050 elseif any(strcmp(addList.Name,'RAVEN Toolbox'))
+0051     installType = 1;
+0052 end
+0053 
+0054 % Do not print first few lines if only version should be reported
+0055 if ~versionOnly
+0056     fprintf('\n*** THE RAVEN TOOLBOX ***\n\n');
+0057     %Print the RAVEN version if it is not the development version
+0058     fprintf(myStr(' > Installation type',40));
+0059     switch installType
+0060         case 0
+0061             fprintf('Advanced (via git)\n');
+0062         case 1
+0063             fprintf('Easy (as MATLAB Add-On)\n');
+0064         case 2
+0065             fprintf('Medium (as downloaded ZIP file)\n');
+0066     end
+0067     fprintf(myStr(' > Installing from location',40));
+0068     fprintf('%s\n',ravenDir)
+0069     fprintf(myStr(' > Checking RAVEN release',40));
+0070 end
+0071                        
+0072 if exist(fullfile(ravenDir,'version.txt'), 'file') == 2
+0073     currVer = fgetl(fopen(fullfile(ravenDir,'version.txt')));
+0074     fclose('all');
+0075     if ~versionOnly
+0076         fprintf([currVer '\n']);
+0077         try
+0078             newVer=strtrim(webread('https://raw.githubusercontent.com/SysBioChalmers/RAVEN/main/version.txt'));
+0079             newVerNum=str2double(strsplit(newVer,'.'));
+0080             currVerNum=str2double(strsplit(currVer,'.'));
+0081             for i=1:3
+0082                 if currVerNum(i)<newVerNum(i)
+0083                     fprintf(myStr('   > Latest RAVEN release available',40))
+0084                     printOrange([newVer,'\n'])
+0085                     switch installType
+0086                         case 0
+0087                             printOrange('     Run git pull in your favourite git client\n')
+0088                             printOrange('     to get the latest RAVEN release\n');
+0089                         case 1
+0090                             printOrange(myStr('     Instructions on how to upgrade',40))
+0091                             fprintf('<a href="https://github.com/SysBioChalmers/RAVEN/wiki/Installation#upgrade-raven-after-easy-installation">here</a>\n');
+0092                         case 2
+0093                             printOrange(myStr('     Instructions on how to upgrade',40))
+0094                             fprintf('<a href="https://github.com/SysBioChalmers/RAVEN/wiki/Installation#upgrade-raven-after-medium-installation">here</a>\n');                            
+0095                     end
+0096                     break
+0097                 elseif i==3
+0098                     fprintf('   > You are running the latest RAVEN release\n');
+0099                 end
+0100             end
+0101         catch
+0102             fprintf(myStr('   > Checking for latest RAVEN release',40))
+0103             printOrange('Fail\n');
+0104             printOrange('     Cannot reach GitHub for release info\n');
+0105         end
+0106     end
+0107 else
+0108     currVer = 'develop';
+0109     if ~versionOnly; fprintf('DEVELOPMENT\n'); end
+0110 end
+0111 if strcmp(developMode,'versionOnly')
+0112     return;
+0113 end
+0114 
+0115 fprintf(myStr(' > Checking MATLAB release',40))
+0116 fprintf([version('-release') '\n'])
+0117 fprintf(myStr(' > Checking system architecture',40))
+0118 fprintf([computer('arch'),'\n'])
+0119 
+0120 fprintf(myStr(' > Set RAVEN in MATLAB path',40))
+0121 subpath=regexp(genpath(ravenDir),pathsep,'split'); %List all subdirectories
+0122 pathsToKeep=cellfun(@(x) ~contains(x,'.git'),subpath) & cellfun(@(x) ~contains(x,'doc'),subpath);
+0123 try
+0124     addpath(strjoin(subpath(pathsToKeep),pathsep));
+0125     fprintf('Pass\n');
+0126     fprintf(myStr(' > Save MATLAB path',40))
+0127     try
+0128         savepath
+0129         fprintf('Pass\n')   
+0130     catch
+0131         printOrange('Fail\n')
+0132         fprintf(['   You might have to rerun checkInstallation again\n'...
+0133                  '   next time you start up MATLAB\n'])        
+0134     end
+0135 catch
+0136     printOrange('Fail\n')
+0137 end
+0138 fprintf(myStr(' > Store RAVEN path as MATLAB pref',40))
+0139 try
+0140     setpref('RAVEN','ravenPath',ravenDir);
+0141     fprintf('Pass\n');
+0142 catch
+0143     printOrange('Fail\n')
+0144 end
+0145 
+0146 if isunix
+0147     fprintf(myStr('   > Make binaries executable',40))
+0148     status = makeBinaryExecutable(ravenDir);
+0149     if status == 0
+0150         fprintf('Pass\n')
+0151     else
+0152         printOrange('Fail\n')
+0153     end
+0154 end
+0155 
+0156 %Check if it is possible to parse an Excel file
+0157 fprintf('\n=== Model import and export ===\n');
+0158 fprintf(myStr(' > Add Java paths for Excel format',40))
+0159 try
+0160     %Add the required classes to the static Java path if not already added
+0161     addJavaPaths();
+0162     fprintf('Pass\n')
+0163 catch
+0164     printOrange('Fail\n')
+0165 end
+0166 fprintf(myStr(' > Checking libSBML version',40))
+0167 try
+0168     evalc('importModel(fullfile(ravenDir,''tutorial'',''empty.xml''))');
+0169     try
+0170         libSBMLver=OutputSBML_RAVEN; % Only works in libSBML 5.17.0+
+0171         fprintf([libSBMLver.libSBML_version_string '\n']);
+0172     catch
+0173         printOrange('Fail\n')
+0174         fprintf('   An older libSBML version was found, update to version 5.17.0 or higher for a significant improvement of model import\n');
+0175     end
+0176 catch
+0177     printOrange('Fail\n')
+0178     fprintf('   Download libSBML from http://sbml.org/Software/libSBML/Downloading_libSBML and add to MATLAB path\n');
+0179 end
+0180 fprintf(' > Checking model import and export\n')
+0181 [~,res]=evalc("runtests('importExportTests.m');");
+0182 
+0183 fprintf(myStr('   > Import Excel format',40))
+0184 if res(1).Passed == 1
+0185     fprintf('Pass\n')
+0186 else
+0187     printOrange('Fail\n')
+0188     if any(strcmpi(addList.Name,'Text Analytics Toolbox'))
+0189         fprintf(['   Excel import/export is incompatible with MATLAB Text Analytics Toolbox.\n' ...
+0190                  '   Further instructions => https://github.com/SysBioChalmers/RAVEN/issues/55#issuecomment-1514369299\n'])
+0191     end
+0192 end
+0193 
+0194 fprintf(myStr('   > Export Excel format',40))
+0195 if res(4).Passed == 1
+0196     fprintf('Pass\n')
+0197 else
+0198     printOrange('Fail\n')
+0199 end
+0200 
+0201 fprintf(myStr('   > Import SBML format',40))
+0202 if res(2).Passed == 1
+0203     fprintf('Pass\n')
+0204 else
+0205     printOrange('Fail\n')
+0206 end
+0207 
+0208 fprintf(myStr('   > Export SBML format',40))
+0209 if res(5).Passed == 1
+0210     fprintf('Pass\n')
+0211 else
+0212     printOrange('Fail\n')
+0213 end
+0214 
+0215 fprintf(myStr('   > Import YAML format',40))
+0216 if res(3).Passed == 1
+0217     fprintf('Pass\n')
+0218 else
+0219     printOrange('Fail\n')
+0220 end
+0221 
+0222 fprintf(myStr('   > Export YAML format',40))
+0223 if res(6).Passed == 1
+0224     fprintf('Pass\n')
+0225 else
+0226     printOrange('Fail\n')
+0227 end
+0228 
+0229 fprintf('\n=== Model solvers ===\n');
+0230 
+0231 %Get current solver. Set it to 'none', if it is not set
+0232 fprintf(' > Checking for LP solvers\n')
+0233 [~,res]=evalc("runtests('solverTests.m');");
+0234 
+0235 fprintf(myStr('   > glpk',40))
+0236 if res(1).Passed == 1
+0237     fprintf('Pass\n')
+0238 else
+0239     printOrange('Fail\n')
+0240 end
+0241 
+0242 fprintf(myStr('   > gurobi',40))
+0243 if res(2).Passed == 1
+0244     fprintf('Pass\n')
+0245 else
+0246     printOrange('Fail\n')
+0247 end
+0248 
+0249 fprintf(myStr('   > scip',40))
+0250 if res(3).Passed == 1
+0251     fprintf('Pass\n')
+0252 else
+0253     printOrange('Fail\n')
+0254 end
+0255 
+0256 fprintf(myStr('   > cobra',40))
+0257 if res(4).Passed == 1
+0258     fprintf('Pass\n')
+0259 else
+0260     printOrange('Fail\n')
+0261 end
+0262 fprintf(myStr(' > Set RAVEN solver',40))
+0263 try
+0264     oldSolver=getpref('RAVEN','solver');
+0265     solverIdx=find(strcmp(oldSolver,{'glpk','gurobi','scip','cobra'}));
+0266 catch
+0267     solverIdx=0;
+0268 end
+0269 % Do not change old solver if functional
+0270 if solverIdx~=0 && res(solverIdx).Passed == 1
+0271     fprintf([oldSolver '\n'])
+0272 % Order of preference: gurobi > glpk > scip > cobra
+0273 elseif res(2).Passed == 1
+0274     fprintf('gurobi\n')
+0275     setRavenSolver('gurobi');
+0276 elseif res(1).Passed == 1
+0277     fprintf('glpk\n')
+0278     setRavenSolver('glpk');
+0279 elseif res(3).Passed == 1
+0280     fprintf('scip\n')
+0281     setRavenSolver('scip');    
+0282 elseif res(4).Passed == 1
+0283     fprintf('cobra\n')
+0284     setRavenSolver('cobra');
+0285 else
+0286     fprintf('None, no functional solvers\n')
+0287     fprintf('    The glpk should always be working, check your RAVEN installation to make sure all files are present\n')
+0288 end
+0289 
+0290 fprintf('\n=== Essential binary executables ===\n');
+0291 if ~checkBinaries
+0292     printOrange('    Skipping check of binary executables\n')
+0293 else
+0294     fprintf(myStr(' > Checking BLAST+',40))
+0295     [~,res]=evalc("runtests('blastPlusTests.m');");
+0296     res=interpretResults(res);
+0297     if res==false
+0298         fprintf('   This is essential to run getBlast()\n')
+0299     end
+0300 
+0301     fprintf(myStr(' > Checking DIAMOND',40))
+0302     [~,res]=evalc("runtests('diamondTests.m');");
+0303     res=interpretResults(res);
+0304     if res==false
+0305         fprintf('   This is essential to run the getDiamond()\n')
+0306     end
+0307 
+0308     fprintf(myStr(' > Checking HMMER',40))
+0309     [~,res]=evalc("runtests('hmmerTests.m')");
+0310     res=interpretResults(res);
+0311     if res==false
+0312         fprintf(['   HMMER is only required by getKEGGModelForOrganism() when\n'...
+0313             '   using a FASTA file as input. If you do not use this function,\n'...
+0314             '   this failure can be ignored.\n'])
+0315         % On Windows, HMMER runs through Windows Subsystem for Linux
+0316         if ispc
+0317             [status,~]=system('where wsl');
+0318             if status~=0
+0319                 printOrange(['   MATLAB cannot find wsl.exe. On Windows, HMMER runs through WSL.\n'...
+0320                     '   Install it with "wsl --install" in a Command Prompt, then restart\n'...
+0321                     '   MATLAB (it inherits the system PATH at startup) and rerun checkInstallation\n'])
+0322             else
+0323                 [status,~]=system('wsl -e true');
+0324                 if status~=0
+0325                     printOrange(['   MATLAB finds wsl.exe, but cannot start a Linux distribution\n'...
+0326                         '   through it. Run "wsl -l -v" in a Command Prompt to check that a\n'...
+0327                         '   distribution is installed and set up, then restart MATLAB and\n'...
+0328                         '   rerun checkInstallation\n'])
+0329                 else
+0330                     try
+0331                         [status,~]=system(['wsl "' getWSLpath(fullfile(ravenDir,'software','hmmer','hmmsearch')) '" -h']);
+0332                     catch
+0333                         status=1;
+0334                     end
+0335                     if status~=0
+0336                         printOrange(['   WSL works, but the RAVEN HMMER binary cannot be run in it.\n'...
+0337                             '   Check that the files in software/hmmer are present and that\n'...
+0338                             '   the drive holding RAVEN is accessible from WSL\n'])
+0339                     end
+0340                 end
+0341             end
+0342         end
+0343     end
+0344 
+0345     if developMode
+0346         fprintf('\n=== Development binary executables ===\n');
+0347         fprintf('NOTE: These binaries are only required when using KEGG FTP dump files in getKEGGModelForOrganism\n');
+0348 
+0349         fprintf(myStr(' > Checking CD-HIT',40))
+0350         [~,res]=evalc("runtests('cdhitTests.m');");
+0351         interpretResults(res);
+0352 
+0353         fprintf(myStr(' > Checking MAFFT',40))
+0354         [~,res]=evalc("runtests('mafftTests.m');");
+0355         interpretResults(res);
+0356     end
+0357 end
+0358 
+0359 fprintf('\n=== Compatibility ===\n');
+0360 fprintf(myStr(' > Checking function uniqueness',40))
+0361 checkFunctionUniqueness();
+0362 
+0363 fprintf('\n*** checkInstallation complete ***\n');
+0364 end
+0365 
+0366 function res = interpretResults(results)
+0367 if results.Failed==0 && results.Incomplete==0
+0368     fprintf('Pass\n');
+0369     res=true;
+0370 else
+0371     printOrange('Fail\n')
+0372     fprintf('   Download/compile the binary and rerun checkInstallation\n');
+0373     res=false;
+0374 end
+0375 end
+0376 
+0377 function str = myStr(InputStr,len)
+0378 str=InputStr;
+0379 lenDiff = len - length(str);
+0380 if lenDiff < 0
+0381     warning('String too long');
+0382 else
+0383     str = [str blanks(lenDiff)];
+0384 end
+0385 end
+0386 
+0387 function status = makeBinaryExecutable(ravenDir)
+0388 % This function is required to run when RAVEN is downloaded as MATLAB
+0389 % Add-On, in which case the file permissions are not correctly set
+0390 if ispc
+0391     status = 0; % No need to run on Windows
+0392     return;
+0393 end
+0394 binDir = fullfile(ravenDir,'software');
+0395 
+0396 binList = {fullfile(binDir,'blast+','blastp');                      fullfile(binDir,'blast+','blastp.mac');
+0397            fullfile(binDir,'blast+','makeblastdb');                 fullfile(binDir,'blast+','makeblastdb.mac');
+0398            fullfile(binDir,'cd-hit','cd-hit');                      fullfile(binDir,'cd-hit','cd-hit.mac');
+0399            fullfile(binDir,'diamond','diamond');                    fullfile(binDir,'diamond','diamond.mac');
+0400            fullfile(binDir,'hmmer','hmmbuild');                     fullfile(binDir,'hmmer','hmmbuild.mac');
+0401            fullfile(binDir,'hmmer','hmmsearch');                    fullfile(binDir,'hmmer','hmmsearch.mac');
+0402            fullfile(binDir,'GLPKmex','glpkcc.mexa64');              fullfile(binDir,'GLPKmex','glpkcc.mexglx');                 fullfile(binDir,'GLPKmex','glpkcc.mexmaci64');              fullfile(binDir,'GLPKmex','glpkcc.mexmaca64');
+0403            fullfile(binDir,'libSBML','TranslateSBML_RAVEN.mexa64'); fullfile(binDir,'libSBML','TranslateSBML_RAVEN.mexglx');    fullfile(binDir,'libSBML','TranslateSBML_RAVEN.mexmaci64');  fullfile(binDir,'libSBML','TranslateSBML_RAVEN.mexmaca64');
+0404            fullfile(binDir,'libSBML','OutputSBML_RAVEN.mexa64');    fullfile(binDir,'libSBML','OutputSBML_RAVEN.mexglx');       fullfile(binDir,'libSBML','OutputSBML_RAVEN.mexmaci64');     fullfile(binDir,'libSBML','OutputSBML_RAVEN.mexmaca64');
+0405            fullfile(binDir,'mafft','mafft-linux64','mafft.bat');
+0406            fullfile(binDir,'mafft','mafft-mac','mafft.bat');};
+0407 
+0408 for i=1:numel(binList)
+0409     [status,cmdout] = system(['chmod +x "' binList{i} '"']);
+0410     if status ~= 0
+0411         warning('Failed to make %s executable: %s ',binList{i},strip(cmdout))
+0412     end
+0413 end
+0414 end
+0415 
+0416 function printOrange(stringToPrint)
+0417 % printOrange
+0418 %   Duplicate of RAVEN/core/printOrange is also kept here, as this function
+0419 %   should be able to run before adding RAVEN to the MATLAB path.
+0420 try useDesktop = usejava('desktop'); catch, useDesktop = false; end
+0421 if useDesktop
+0422     fprintf(['[\b' stringToPrint,']\b'])
+0423 else
+0424     fprintf(stringToPrint)
+0425 end
+0426 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/installation/index.html b/doc/installation/index.html new file mode 100644 index 000000000..8eef48a3a --- /dev/null +++ b/doc/installation/index.html @@ -0,0 +1,29 @@ + + + + Index for Directory installation + + + + + + + + + + +
< Master indexIndex for installation >
+ +

Index for installation

+ +

Matlab files in this directory:

+ +
 addRavenToUserPathThis function writes a startup.m file in the userpath, adding RAVEN (and
 checkFunctionUniquenesscheckFunctionUniqueness
 checkInstallationcheckInstallation
 removeRavenFromPathremoveRavenFromPath
+ + + + +
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/installation/removeRavenFromPath.html b/doc/installation/removeRavenFromPath.html new file mode 100644 index 000000000..1f81cf8ae --- /dev/null +++ b/doc/installation/removeRavenFromPath.html @@ -0,0 +1,97 @@ + + + + Description of removeRavenFromPath + + + + + + + + + +
Home > installation > removeRavenFromPath.m
+ + + +

removeRavenFromPath +

+ +

PURPOSE ^

+
removeRavenFromPath
+ +

SYNOPSIS ^

+
function removeRavenFromPath()
+ +

DESCRIPTION ^

+
 removeRavenFromPath
+   This function removes all RAVEN directories and subdirectories from the
+   MATLAB path. This function only removes RAVEN from the MATLAB path, it
+   does not delete the RAVEN folder itself. If RAVEN was installed as
+   MATLAB Add-On, the user is prompted to instead uninstall RAVEN via the
+   Add-On Manager.
+
+ Usage: removeRavenFromPath()
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function removeRavenFromPath()
+0002 % removeRavenFromPath
+0003 %   This function removes all RAVEN directories and subdirectories from the
+0004 %   MATLAB path. This function only removes RAVEN from the MATLAB path, it
+0005 %   does not delete the RAVEN folder itself. If RAVEN was installed as
+0006 %   MATLAB Add-On, the user is prompted to instead uninstall RAVEN via the
+0007 %   Add-On Manager.
+0008 %
+0009 % Usage: removeRavenFromPath()
+0010 
+0011 % Check for installation as Add-On
+0012 addList = matlab.addons.installedAddons;
+0013 if any(strcmp(addList.Name,'RAVEN Toolbox'))
+0014     error(['RAVEN is installed as MATLAB Add-On. You should uninstall RAVEN via '...
+0015         'the Add-On Manager instead. Once uninstalled, you may attempt to run '...
+0016         'removeRavenFromPath again to remove any potential remaining RAVEN installations.'])
+0017 end
+0018 
+0019 % Get current paths
+0020 currPath  = transpose(strsplit(path(),{';',':'}));
+0021 ravenPath = false(numel(currPath),1);
+0022 for i=1:numel(currPath)
+0023     dirCont = ls(currPath{i});
+0024     dirCont = cellstr(dirCont(3:end,:));
+0025     if any(contains(dirCont,{'ravenCobraWrapper.m','makeFakeBlastStructure.m','setRavenSolver.m'})) % A few (hopefully) unique RAVEN functions
+0026         ravenPath(i)=true;
+0027     end
+0028 end
+0029 
+0030 ravenPath = unique(regexprep(currPath(ravenPath),'(\\|\/)((external)|(struct_conversion)|(solver))',''));
+0031 addOnDir = contains(ravenPath,'MATLAB Add-Ons');
+0032 if any(addOnDir)
+0033     warning(['RAVEN is installed as MATLAB Add-On at the following directory, but MATLAB '...
+0034         'somehow does not recognize this installation. You are advised to manually delete '...
+0035         'the directory to remove any RAVEN remnants: ' ravenPath{addOnDir}]);
+0036 end
+0037 ravenSubDirs = currPath(startsWith(currPath,ravenPath));
+0038 % Remove from path
+0039 if ~isempty(ravenSubDirs)
+0040     rmpath(ravenSubDirs{:});
+0041     savepath;
+0042 end
+0043 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/io/SBMLFromExcel.html b/doc/io/SBMLFromExcel.html new file mode 100644 index 000000000..4565e9250 --- /dev/null +++ b/doc/io/SBMLFromExcel.html @@ -0,0 +1,94 @@ + + + + Description of SBMLFromExcel + + + + + + + + + +
Home > io > SBMLFromExcel.m
+ + + +

SBMLFromExcel +

+ +

PURPOSE ^

+
SBMLFromExcel
+ +

SYNOPSIS ^

+
function SBMLFromExcel(fileName, outputFileName,toCOBRA,printWarnings)
+ +

DESCRIPTION ^

+
 SBMLFromExcel
+   Converts a model in the Excel format to SBML
+
+   fileName        the Excel file
+   outputFileName  the SBML file
+   toCOBRA         true if the model should be saved in COBRA Toolbox
+                   format. Only limited support at the moment (optional,
+                   default false)
+   printWarnings   true if warnings about model issues should be reported
+                   (optional, default true)
+
+   For a detailed description of the file format, see the supplied manual.
+
+ Usage: SBMLFromExcel(fileName,outputFileName,toCOBRA,printWarnings)
+
+   NOTE: This is just a wrapper function for importExcelModel, printModelStats
+   and exportModel. Use those functions directly for greater control.
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function SBMLFromExcel(fileName, outputFileName,toCOBRA,printWarnings)
+0002 % SBMLFromExcel
+0003 %   Converts a model in the Excel format to SBML
+0004 %
+0005 %   fileName        the Excel file
+0006 %   outputFileName  the SBML file
+0007 %   toCOBRA         true if the model should be saved in COBRA Toolbox
+0008 %                   format. Only limited support at the moment (optional,
+0009 %                   default false)
+0010 %   printWarnings   true if warnings about model issues should be reported
+0011 %                   (optional, default true)
+0012 %
+0013 %   For a detailed description of the file format, see the supplied manual.
+0014 %
+0015 % Usage: SBMLFromExcel(fileName,outputFileName,toCOBRA,printWarnings)
+0016 %
+0017 %   NOTE: This is just a wrapper function for importExcelModel, printModelStats
+0018 %   and exportModel. Use those functions directly for greater control.
+0019 fileName=char(fileName);
+0020 outputFileName=char(outputFileName);
+0021 if nargin<3
+0022     toCOBRA=false;
+0023 end
+0024 if nargin<4
+0025     printWarnings=true;
+0026 end
+0027 
+0028 model=importExcelModel(fileName,false,printWarnings);
+0029 printModelStats(model,printWarnings,false);
+0030 exportModel(model,outputFileName,toCOBRA,true);
+0031 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/io/addJavaPaths.html b/doc/io/addJavaPaths.html new file mode 100644 index 000000000..1235fed1f --- /dev/null +++ b/doc/io/addJavaPaths.html @@ -0,0 +1,76 @@ + + + + Description of addJavaPaths + + + + + + + + + +
Home > io > addJavaPaths.m
+ + + +

addJavaPaths +

+ +

PURPOSE ^

+
addJavaPaths
+ +

SYNOPSIS ^

+
function addJavaPaths()
+ +

DESCRIPTION ^

+
 addJavaPaths
+   Adds the Apache POI classes to the static Java paths
+
+ Usage: addJavaPaths()
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + + + +

SOURCE CODE ^

+
0001 % addJavaPaths
+0002 %   Adds the Apache POI classes to the static Java paths
+0003 %
+0004 % Usage: addJavaPaths()
+0005 
+0006 function addJavaPaths()
+0007 %Get the path to Apache POI
+0008 ravenPath=findRAVENroot();
+0009 poiPATH=fullfile(ravenPath,'software','apache-poi');
+0010 
+0011 toAdd={fullfile(poiPATH,'dom4j-1.6.1.jar');
+0012     fullfile(poiPATH,'poi-3.8-20120326.jar');
+0013     fullfile(poiPATH,'poi-ooxml-3.8-20120326.jar');
+0014     fullfile(poiPATH,'poi-ooxml-schemas-3.8-20120326.jar');
+0015     fullfile(poiPATH,'xmlbeans-2.3.0.jar');
+0016     fullfile(poiPATH,'stax-api-1.0.1.jar')};
+0017 
+0018 existingPaths=javaclasspath();
+0019 
+0020 %Add the paths that are not already present
+0021 for i=1:numel(toAdd)
+0022     if ~any(ismember(existingPaths,toAdd{i}))
+0023         javaaddpath(toAdd{i});
+0024     end
+0025 end
+0026 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/io/checkFileExistence.html b/doc/io/checkFileExistence.html new file mode 100644 index 000000000..d17fbfcd7 --- /dev/null +++ b/doc/io/checkFileExistence.html @@ -0,0 +1,152 @@ + + + + Description of checkFileExistence + + + + + + + + + +
Home > io > checkFileExistence.m
+ + + +

checkFileExistence +

+ +

PURPOSE ^

+
checkFileExistence
+ +

SYNOPSIS ^

+
function files=checkFileExistence(files,fullOrTemp,allowSpace,checkExist)
+ +

DESCRIPTION ^

+
 checkFileExistence
+   Check whether files exist. If no full path is given a file should be
+   located in the current folder, which by default is appended to the
+   filename.
+
+   Input:
+   files           string or cell array of strings with path to file(s) or
+                   path or filename(s)
+   fullOrTemp      0: do not change path to file(s)
+                   1: return full path to file(s)
+                   2: copy file(s) to system default temporary folder and
+                      return full path
+                   (optional, default 0)
+   allowSpace      logical, whether 'space' character is allowed in the
+                   path (optional, default true)
+   checkExist      logical, whether file existence should really be
+                   checked, as this function can also be used to return
+                   the full path to a new file (optional, default true). Can
+                   only be set to false if fullOrTemp is set to 1.
+
+   Output:
+   files           string or cell array of strings with updated paths if
+                   fullOrTemp was set as 1 or 2, otherwise original paths
+                   are returned
+   
+ Usage: files=checkFileExistence(files,fullOrTemp,allowSpace,checkExist)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function files=checkFileExistence(files,fullOrTemp,allowSpace,checkExist)
+0002 % checkFileExistence
+0003 %   Check whether files exist. If no full path is given a file should be
+0004 %   located in the current folder, which by default is appended to the
+0005 %   filename.
+0006 %
+0007 %   Input:
+0008 %   files           string or cell array of strings with path to file(s) or
+0009 %                   path or filename(s)
+0010 %   fullOrTemp      0: do not change path to file(s)
+0011 %                   1: return full path to file(s)
+0012 %                   2: copy file(s) to system default temporary folder and
+0013 %                      return full path
+0014 %                   (optional, default 0)
+0015 %   allowSpace      logical, whether 'space' character is allowed in the
+0016 %                   path (optional, default true)
+0017 %   checkExist      logical, whether file existence should really be
+0018 %                   checked, as this function can also be used to return
+0019 %                   the full path to a new file (optional, default true). Can
+0020 %                   only be set to false if fullOrTemp is set to 1.
+0021 %
+0022 %   Output:
+0023 %   files           string or cell array of strings with updated paths if
+0024 %                   fullOrTemp was set as 1 or 2, otherwise original paths
+0025 %                   are returned
+0026 %
+0027 % Usage: files=checkFileExistence(files,fullOrTemp,allowSpace,checkExist)
+0028 
+0029 if nargin<2
+0030     fullOrTemp = 0;
+0031 end
+0032 if nargin<3
+0033     allowSpace = true;
+0034 end
+0035 if nargin<4
+0036     checkExist = true;
+0037 end
+0038 files=convertCharArray(files);
+0039 if numel(files)==1
+0040     oneFile=true;
+0041 else
+0042     oneFile=false;
+0043 end
+0044 filesOriginal = files;
+0045 
+0046 %Make all full paths before check of file existence
+0047 if ispc % full path starts like "C:\"
+0048     inCurrDir = cellfun(@isempty,regexpi(files,'^[a-z]\:\\'));
+0049 else %isunix full path starts like "/"
+0050     inCurrDir = cellfun(@isempty,regexpi(files,'^\/'));
+0051 end
+0052 files(inCurrDir) = fullfile(cd,files(inCurrDir));
+0053 
+0054 %Check existence
+0055 if checkExist
+0056     for i=1:numel(files)
+0057         if ~isfile(files{i})
+0058             error('File "%s" cannot be found\n',files{i});
+0059         elseif allowSpace == false & strfind(files{i},' ')
+0060             error('File "%s" has an invalid space in the filename or path, please remove this before running this function\n',files{i});
+0061         end
+0062     end
+0063 end
+0064 
+0065 switch fullOrTemp
+0066     case 0
+0067         files = filesOriginal;
+0068     case 1
+0069         % files already contains full path
+0070     case 2
+0071         for i=1:numel(files)
+0072             tmpFile=tempname;
+0073             copyfile(files{i},tmpFile);
+0074             files{i}=tmpFile;
+0075         end
+0076 end
+0077 
+0078 if oneFile == true
+0079     files = files{1};
+0080 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/io/cleanSheet.html b/doc/io/cleanSheet.html new file mode 100644 index 000000000..fd3918e9b --- /dev/null +++ b/doc/io/cleanSheet.html @@ -0,0 +1,170 @@ + + + + Description of cleanSheet + + + + + + + + + +
Home > io > cleanSheet.m
+ + + +

cleanSheet +

+ +

PURPOSE ^

+
cleanSheet
+ +

SYNOPSIS ^

+
function [raw,keptRows,keptCols]=cleanSheet(raw,removeComments,removeOnlyCap,removeNoCap,removeEmptyRows)
+ +

DESCRIPTION ^

+
 cleanSheet
+   Cleans up an Excel sheet by removing empty rows/colums (and some other
+   checks)
+
+   raw             cell array with the data in the sheet
+   removeComments  true if commented lines (non-empty first cell in each
+                   row) should be removed (optional, default true)
+   removeOnlyCap   remove columns with captions but no other values (optional,
+                   default false)
+   removeNoCap     remove columns without captions (optional, default true)
+   removeEmptyRows remove rows with no non-empty cells (optional, default true)
+   
+   raw             cleaned version
+   keptRows        indexes of the kept rows in the original structure
+   keptCols        indexes of the kept columns in the original structure
+
+ Usage: [raw,keptRows,keptCols]=cleanSheet(raw,removeComments,removeOnlyCap,...
+               removeNoCap,removeEmptyRows)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 % cleanSheet
+0002 %   Cleans up an Excel sheet by removing empty rows/colums (and some other
+0003 %   checks)
+0004 %
+0005 %   raw             cell array with the data in the sheet
+0006 %   removeComments  true if commented lines (non-empty first cell in each
+0007 %                   row) should be removed (optional, default true)
+0008 %   removeOnlyCap   remove columns with captions but no other values (optional,
+0009 %                   default false)
+0010 %   removeNoCap     remove columns without captions (optional, default true)
+0011 %   removeEmptyRows remove rows with no non-empty cells (optional, default true)
+0012 %
+0013 %   raw             cleaned version
+0014 %   keptRows        indexes of the kept rows in the original structure
+0015 %   keptCols        indexes of the kept columns in the original structure
+0016 %
+0017 % Usage: [raw,keptRows,keptCols]=cleanSheet(raw,removeComments,removeOnlyCap,...
+0018 %               removeNoCap,removeEmptyRows)
+0019 
+0020 function [raw,keptRows,keptCols]=cleanSheet(raw,removeComments,removeOnlyCap,removeNoCap,removeEmptyRows)
+0021 if nargin<2
+0022     removeComments=true;
+0023 end
+0024 if nargin<3
+0025     removeOnlyCap=false;
+0026 end
+0027 if nargin<4
+0028     removeNoCap=true;
+0029 end
+0030 if nargin<5
+0031     removeEmptyRows=true;
+0032 end
+0033 
+0034 keptRows=1:size(raw,1);
+0035 keptRows=keptRows(:);
+0036 keptCols=1:size(raw,2);
+0037 keptCols=keptCols(:);
+0038 
+0039 %First check that it's a cell array. If a sheet is completely empty, then
+0040 %raw=NaN
+0041 if iscell(raw)
+0042     %Clear cells which contain only white spaces or NaN. This could happen
+0043     %if you accidentally inserted a space for example. I don't know how NaN
+0044     %could occur after switching to Apache POI, but I clear it to be sure
+0045     whites=cellfun(@wrapperWS,raw);
+0046     raw(whites)={[]};
+0047     
+0048     %Find the rows that are not commented. This corresponds to the first
+0049     %row and the ones which are empty in the first column
+0050     if removeComments==true
+0051         keepers=cellfun(@isempty,raw(:,1));
+0052         keepers(1)=true;
+0053         raw=raw(keepers,:);
+0054         keptRows=keptRows(keepers);
+0055     end
+0056     
+0057     %Remove columns that don't have string headers. If you cut and paste a
+0058     %lot in the sheet there tends to be columns that are empty
+0059     if removeNoCap==true
+0060         I=cellfun(@isstr,raw(1,:));
+0061         raw=raw(:,I);
+0062         keptCols=keptCols(I);
+0063     end
+0064     
+0065     %Remove columns which are empty except for header
+0066     if removeOnlyCap==true
+0067         I=~all(cellfun(@isempty,raw(2:end,:)),1);
+0068         raw=raw(:,I);
+0069         keptCols=keptCols(I);
+0070     end
+0071     
+0072     %Check if there are any rows that are all empty. This could happen if
+0073     %it reads too far or if the user has inserted them for layout reasons.
+0074     %Remove any such rows
+0075     if removeEmptyRows==true
+0076         I=~all(cellfun(@isempty,raw),2);
+0077         raw=raw(I,:);
+0078         keptRows=keptRows(I);
+0079     end
+0080 else
+0081     raw={[]};
+0082 end
+0083 
+0084 %Checks if something is all white spaces or NaN
+0085     function I=wrapperWS(A)
+0086         if isnan(A)
+0087             I=true;
+0088         else
+0089             %isstrprop gives an error if boolean
+0090             if islogical(A)
+0091                 I=false;
+0092             else
+0093                 %I have to make this check, since otherwise it will pick up
+0094                 %on doubles for which the ASCII representation is a white
+0095                 %space character
+0096                 if isnumeric(A)
+0097                     I=false;
+0098                 else
+0099                     I=all(isstrprop(A,'wspace'));
+0100                 end
+0101             end
+0102         end
+0103     end
+0104 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/io/closeModel.html b/doc/io/closeModel.html new file mode 100644 index 000000000..a8db94c9b --- /dev/null +++ b/doc/io/closeModel.html @@ -0,0 +1,115 @@ + + + + Description of closeModel + + + + + + + + + +
Home > io > closeModel.m
+ + + +

closeModel +

+ +

PURPOSE ^

+
closeModel
+ +

SYNOPSIS ^

+
function closedModel=closeModel(model)
+ +

DESCRIPTION ^

+
 closeModel
+   Adds boundary metabolites and their participation in exchange
+   reactions.
+
+   model                 a model structure
+
+   closedModel           an updated closedModel structure
+
+ Usage: closedModel=closeModel(model)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function closedModel=closeModel(model)
+0002 % closeModel
+0003 %   Adds boundary metabolites and their participation in exchange
+0004 %   reactions.
+0005 %
+0006 %   model                 a model structure
+0007 %
+0008 %   closedModel           an updated closedModel structure
+0009 %
+0010 % Usage: closedModel=closeModel(model)
+0011 
+0012 closedModel=model;
+0013 
+0014 closedModel.comps{numel(closedModel.comps)+1,1}='b';
+0015 closedModel.compNames{numel(closedModel.compNames)+1,1}='boundary';
+0016 if isfield(closedModel,'compMiriams')
+0017     closedModel.compMiriams{numel(closedModel.compMiriams)+1,1}=[];
+0018 end
+0019 closedModel.unconstrained=zeros(numel(closedModel.mets),1);
+0020 
+0021 for i=1:numel(closedModel.rxns)
+0022     if sum(abs(closedModel.S(:,i)))==1
+0023         closedModel.mets{numel(closedModel.mets)+1}=strcat(closedModel.mets{find(closedModel.S(:,i))},'_b');
+0024         if isfield(closedModel,'metNames')
+0025             closedModel.metNames{numel(closedModel.metNames)+1}=closedModel.metNames{find(closedModel.S(:,i))};
+0026         end
+0027         closedModel.metComps(numel(closedModel.metComps)+1)=numel(closedModel.comps);
+0028         if isfield(closedModel,'inchis')
+0029             closedModel.inchis{numel(closedModel.inchis)+1}=closedModel.inchis{find(closedModel.S(:,i))};
+0030         end
+0031         if isfield(closedModel,'metSmiles')
+0032             closedModel.metSmiles{numel(closedModel.metSmiles)+1}=closedModel.metSmiles{find(closedModel.S(:,i))};
+0033         end
+0034         if isfield(closedModel,'metFormulas')
+0035             closedModel.metFormulas{numel(closedModel.metFormulas)+1}=closedModel.metFormulas{find(closedModel.S(:,i))};
+0036         end
+0037         if isfield(closedModel,'metMiriams')
+0038             closedModel.metMiriams{numel(closedModel.metMiriams)+1}=closedModel.metMiriams{find(closedModel.S(:,i))};
+0039         end
+0040         if isfield(closedModel,'metFrom')
+0041             closedModel.metFrom{numel(closedModel.metFrom)+1}='';
+0042         end
+0043         if isfield(closedModel,'metCharges')
+0044             closedModel.metCharges(numel(closedModel.metCharges)+1)=closedModel.metCharges(find(closedModel.S(:,i)));
+0045         end
+0046         if isfield(closedModel,'metDeltaG')
+0047             closedModel.metDeltaG(numel(closedModel.metDeltaG)+1)=closedModel.metDeltaG(find(closedModel.S(:,i)));
+0048         end
+0049         closedModel.unconstrained(numel(closedModel.unconstrained)+1)=1;
+0050         closedModel.b(numel(closedModel.b)+1)=0;
+0051         closedModel.S=[closedModel.S;sparse(1,size(closedModel.S,2))];
+0052         if sum(closedModel.S(:,i))==1
+0053             closedModel.S(numel(closedModel.mets),i)=-1;
+0054         else
+0055             closedModel.S(numel(closedModel.mets),i)=1;
+0056         end
+0057     end
+0058 end
+0059 
+0060 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/io/exportForGit.html b/doc/io/exportForGit.html new file mode 100644 index 000000000..1a60e1be9 --- /dev/null +++ b/doc/io/exportForGit.html @@ -0,0 +1,244 @@ + + + + Description of exportForGit + + + + + + + + + +
Home > io > exportForGit.m
+ + + +

exportForGit +

+ +

PURPOSE ^

+
exportForGit
+ +

SYNOPSIS ^

+
function out=exportForGit(model,prefix,path,formats,mainBranchFlag,subDirs,COBRAtext,neverPrefixIDs)
+ +

DESCRIPTION ^

+
 exportForGit
+   Generates a directory structure and populates this with model files, ready
+   to be commited to a Git(Hub) maintained model repository. Writes the model
+   as SBML L3V1 FBCv2 (both XML and YAML), COBRA text, Matlab MAT-file
+   orthologies in KEGG
+
+   model               model structure in RAVEN format that should be
+   exported
+   prefix              prefix for all filenames (optional, default 'model')
+   path                path where the directory structure should be
+                       generated and populated with all files (optional,
+                       default to current working directory)
+   formats             cell array of strings specifying in what file
+                       formats the model should be exported (optional,
+                       default to all formats as {'mat', 'txt', 'xlsx',
+                       'xml', 'yml'})
+   mainBranchFlag      logical, if true, function will error if RAVEN (and
+                       COBRA if detected) is/are not on the main branch.
+                       (optional, default false)
+   subDirs             logical, whether model files for each file format
+                       should be written in its own subdirectory, with
+                       'model' as parent directory, in accordance to the
+                       standard-GEM repository format. If false, all files
+                       are stored in the same folder. (optional, default
+                       true)
+   COBRAtext           logical, whether the txt file should be in COBRA
+                       Toolbox format using metabolite IDs, instead of
+                       metabolite names and compartments. (optional,
+                       default false)
+   neverPrefixIDs      true if prefixes are never added to identifiers,
+                       even if start with e.g. digits. This might result
+                       in invalid SBML files (optional, default false)
+
+ Usage: exportForGit(model,prefix,path,formats,mainBranchFlag,subDirs,COBRAtext,COBRAstyle)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function out=exportForGit(model,prefix,path,formats,mainBranchFlag,subDirs,COBRAtext,neverPrefixIDs)
+0002 % exportForGit
+0003 %   Generates a directory structure and populates this with model files, ready
+0004 %   to be commited to a Git(Hub) maintained model repository. Writes the model
+0005 %   as SBML L3V1 FBCv2 (both XML and YAML), COBRA text, Matlab MAT-file
+0006 %   orthologies in KEGG
+0007 %
+0008 %   model               model structure in RAVEN format that should be
+0009 %   exported
+0010 %   prefix              prefix for all filenames (optional, default 'model')
+0011 %   path                path where the directory structure should be
+0012 %                       generated and populated with all files (optional,
+0013 %                       default to current working directory)
+0014 %   formats             cell array of strings specifying in what file
+0015 %                       formats the model should be exported (optional,
+0016 %                       default to all formats as {'mat', 'txt', 'xlsx',
+0017 %                       'xml', 'yml'})
+0018 %   mainBranchFlag      logical, if true, function will error if RAVEN (and
+0019 %                       COBRA if detected) is/are not on the main branch.
+0020 %                       (optional, default false)
+0021 %   subDirs             logical, whether model files for each file format
+0022 %                       should be written in its own subdirectory, with
+0023 %                       'model' as parent directory, in accordance to the
+0024 %                       standard-GEM repository format. If false, all files
+0025 %                       are stored in the same folder. (optional, default
+0026 %                       true)
+0027 %   COBRAtext           logical, whether the txt file should be in COBRA
+0028 %                       Toolbox format using metabolite IDs, instead of
+0029 %                       metabolite names and compartments. (optional,
+0030 %                       default false)
+0031 %   neverPrefixIDs      true if prefixes are never added to identifiers,
+0032 %                       even if start with e.g. digits. This might result
+0033 %                       in invalid SBML files (optional, default false)
+0034 %
+0035 % Usage: exportForGit(model,prefix,path,formats,mainBranchFlag,subDirs,COBRAtext,COBRAstyle)
+0036 if nargin<8
+0037     neverPrefixIDs=false;
+0038 end
+0039 if nargin<7 || isempty(COBRAtext)
+0040     COBRAtext=false;
+0041 end
+0042 if nargin<6 || isempty(subDirs)
+0043     subDirs=true;
+0044 end
+0045 if nargin<5 || isempty(mainBranchFlag)
+0046     mainBranchFlag=false;
+0047 end
+0048 if nargin<4 || isempty(formats)
+0049     formats={'mat', 'txt', 'xlsx', 'xml', 'yml'};
+0050 else
+0051     formats=convertCharArray(formats);
+0052 end
+0053 if any(~ismember(formats, {'mat', 'txt', 'xlsx', 'xml', 'yml'}))
+0054     EM='Unknown file format defined. Only mat, txt, xlsx, xml and yml are allowed file formats.';
+0055     error(EM)
+0056 end
+0057 if nargin<3 || isempty(path)
+0058     path='.';
+0059 else
+0060     path=char(path);
+0061 end
+0062 if nargin<2 || isempty(prefix)
+0063     prefix='model';
+0064 else
+0065     prefix=char(prefix);
+0066 end
+0067 
+0068 %Sort reactions, metabolites and genes alphabetically
+0069 model=sortIdentifiers(model);
+0070 
+0071 %Get versions or commits of toolboxes:
+0072 RAVENver = getToolboxVersion('RAVEN','ravenCobraWrapper.m',mainBranchFlag);
+0073 if exist('initCobraToolbox.m','file')
+0074     COBRAver = getToolboxVersion('COBRA','initCobraToolbox.m',mainBranchFlag);
+0075 else
+0076     COBRAver = [];
+0077 end
+0078 %Retrieve libSBML version:
+0079 [ravenDir,prevDir]=findRAVENroot();
+0080 try % 5.17.0 and newer
+0081     libSBMLver=OutputSBML_RAVEN;
+0082     libSBMLver=libSBMLver.libSBML_version_string;
+0083 catch % before 5.17.0
+0084     fid = fopen('tempModelForLibSBMLversion.xml','w+');
+0085     fclose(fid);
+0086     evalc('[~,~,libSBMLver]=TranslateSBML_RAVEN(''tempModelForLibSBMLversion.xml'',0,0)');
+0087     libSBMLver=libSBMLver.libSBML_version_string;
+0088     delete('tempModelForLibSBMLversion.xml');
+0089 end
+0090 
+0091 % Make models folder, no warnings if folder already exists
+0092 if subDirs
+0093     path=fullfile(path,'model');
+0094     filePath=strcat(path,filesep,{'txt','yml','mat','xlsx','xml'});
+0095     [~,~,~]=mkdir(path);
+0096     for i = 1:length(formats)
+0097         [~,~,~]=mkdir(fullfile(path,formats{i}));
+0098     end
+0099 else
+0100     filePath=cell(1,5); filePath(:)={path};
+0101 end
+0102 
+0103 
+0104 % Write TXT format
+0105 if ismember('txt', formats)
+0106     fid=fopen(fullfile(filePath{1},strcat(prefix,'.txt')),'w');
+0107     if COBRAtext==true
+0108         eqns=constructEquations(model,model.rxns,false,false,false);
+0109         eqns=strrep(eqns,' => ','  -> ');
+0110         eqns=strrep(eqns,' <=> ','  <=> ');
+0111         eqns=regexprep(eqns,'> $','>');
+0112         grRules=regexprep(model.grRules,'\((?!\()','( ');
+0113         grRules=regexprep(grRules,'(?<!\))\)',' )');
+0114     else
+0115         eqns=constructEquations(model,model.rxns);
+0116         grRules=model.grRules;
+0117     end
+0118     fprintf(fid, 'Rxn name\tFormula\tGene-reaction association\tLB\tUB\tObjective\n');
+0119     for i = 1:numel(model.rxns)
+0120         fprintf(fid, '%s\t', model.rxns{i});
+0121         fprintf(fid, '%s \t', eqns{i});
+0122         fprintf(fid, '%s\t', grRules{i});
+0123         fprintf(fid, '%6.2f\t%6.2f\t%6.2f\n', model.lb(i), model.ub(i), model.c(i));
+0124     end
+0125     fclose(fid);
+0126 end
+0127 
+0128 % Write YML format
+0129 if ismember('yml', formats)
+0130     writeYAMLmodel(model,fullfile(filePath{2},strcat(prefix,'.yml')));
+0131 end
+0132 
+0133 % Write MAT format
+0134 if ismember('mat', formats)
+0135     save(fullfile(filePath{3},strcat(prefix,'.mat')),'model');
+0136 end
+0137 
+0138 % Write XLSX format
+0139 if ismember('xlsx', formats)
+0140     exportToExcelFormat(model,fullfile(filePath{4},strcat(prefix,'.xlsx')));
+0141 end
+0142 
+0143 % Write XML format
+0144 if ismember('xml', formats)
+0145         exportModel(model,fullfile(filePath{5},strcat(prefix,'.xml')),neverPrefixIDs);
+0146 end
+0147 
+0148 %Save file with versions:
+0149 fid = fopen(fullfile(path,'dependencies.txt'),'wt');
+0150 fprintf(fid,['MATLAB\t' version '\n']);
+0151 fprintf(fid,['libSBML\t' libSBMLver '\n']);
+0152 fprintf(fid,['RAVEN_toolbox\t' RAVENver '\n']);
+0153 if ~isempty(COBRAver)
+0154     fprintf(fid,['COBRA_toolbox\t' COBRAver '\n']);
+0155 end
+0156 if isfield(model,'modelVersion')
+0157     fields = fieldnames(model.modelVersion);
+0158     for i = 1:length(fields)
+0159         value = model.modelVersion.(fields{i});
+0160         fprintf(fid,[fields{i} '\t' num2str(value) '\n']);
+0161     end
+0162 end
+0163 fclose(fid);
+0164 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/io/exportModel.html b/doc/io/exportModel.html new file mode 100644 index 000000000..eacffe43b --- /dev/null +++ b/doc/io/exportModel.html @@ -0,0 +1,868 @@ + + + + Description of exportModel + + + + + + + + + +
Home > io > exportModel.m
+ + + +

exportModel +

+ +

PURPOSE ^

+
exportModel
+ +

SYNOPSIS ^

+
function exportModel(model,fileName,neverPrefix,supressWarnings,sortIds)
+ +

DESCRIPTION ^

+
 exportModel
+   Exports a constraint-based model to an SBML file (L3V1 FBCv2)
+
+ Input:
+   model               a model structure
+   fileName            filename to export the model to. A dialog window
+                       will open if no file name is specified.
+   neverPrefix         true if prefixes are never added to identifiers,
+                       even if start with e.g. digits. This might result
+                       in invalid SBML files (optional, default false)
+   supressWarnings     true if warnings should be supressed. This might
+                       results in invalid SBML files, as no checks are
+                       performed (optional, default false)
+   sortIds             logical whether metabolites, reactions and genes
+                       should be sorted alphabetically by their
+                       identifiers (optional, default false)
+
+ Usage: exportModel(model,fileName,neverPrefix,supressWarnings,sortIds)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 function exportModel(model,fileName,neverPrefix,supressWarnings,sortIds)
+0002 % exportModel
+0003 %   Exports a constraint-based model to an SBML file (L3V1 FBCv2)
+0004 %
+0005 % Input:
+0006 %   model               a model structure
+0007 %   fileName            filename to export the model to. A dialog window
+0008 %                       will open if no file name is specified.
+0009 %   neverPrefix         true if prefixes are never added to identifiers,
+0010 %                       even if start with e.g. digits. This might result
+0011 %                       in invalid SBML files (optional, default false)
+0012 %   supressWarnings     true if warnings should be supressed. This might
+0013 %                       results in invalid SBML files, as no checks are
+0014 %                       performed (optional, default false)
+0015 %   sortIds             logical whether metabolites, reactions and genes
+0016 %                       should be sorted alphabetically by their
+0017 %                       identifiers (optional, default false)
+0018 %
+0019 % Usage: exportModel(model,fileName,neverPrefix,supressWarnings,sortIds)
+0020 
+0021 if nargin<2 || isempty(fileName)
+0022     [fileName, pathName] = uiputfile({'*.xml;*.sbml'}, 'Select file for model export',[model.id '.xml']);
+0023     if fileName == 0
+0024         error('You should provide a file location')
+0025     else
+0026         fileName = fullfile(pathName,fileName);
+0027     end
+0028 end
+0029 fileName=char(fileName);
+0030 if nargin<3 || isempty(neverPrefix)
+0031     neverPrefix=false;
+0032 end
+0033 if nargin<4 || isempty(supressWarnings)
+0034     supressWarnings=false;
+0035 end
+0036 if nargin<5 || isempty(sortIds)
+0037     sortIds=false;
+0038 end
+0039 if sortIds==true
+0040     model=sortIdentifiers(model);
+0041 end
+0042 
+0043 if isfield(model,'ec')
+0044     warning("exportModel does not store information from the 'model.ec' structure. Use 'writeYAMLmodel(model)' to export all content from a GECKO model.")
+0045 end
+0046 
+0047 %If no subSystems are defined, then no need to use groups package
+0048 if isfield(model,'subSystems')
+0049     modelHasSubsystems=true;
+0050 else
+0051     modelHasSubsystems=false;
+0052 end
+0053 
+0054 %The default SBML format settings, which are used as input for appropriate
+0055 %libSBML functions to generate the blank SBML model structure before using
+0056 %exporting in with OutputSBML to xml file
+0057 sbmlLevel=3;
+0058 sbmlVersion=1;
+0059 sbmlPackages={'fbc'};
+0060 sbmlPackageVersions=2;
+0061 if modelHasSubsystems
+0062     sbmlPackages={sbmlPackages,'groups'};
+0063     sbmlPackageVersions=[sbmlPackageVersions,1];
+0064 end
+0065 
+0066 %Check if the "unconstrained" field is still present. This shows if
+0067 %exchange metabolites have been removed
+0068 if ~isfield(model,'unconstrained')
+0069     model.unconstrained=zeros(numel(model.mets),1);
+0070 end
+0071 
+0072 %If model id and name do not exist, make sure that default
+0073 %strings are included
+0074 if ~isfield(model,'id')
+0075     fprintf('WARNING: The model is missing the "id" field. Uses "blankID". \n');
+0076     model.id='blankID';
+0077 end
+0078 if ~isfield(model,'name')
+0079     fprintf('WARNING: The model is missing the "name" field. Uses "blankName". \n');
+0080     model.name='blankName';
+0081 end
+0082 
+0083 % Add prefixes if required
+0084 if ~neverPrefix
+0085     [model,hasChanged] = addIdentifierPrefix(model);
+0086     dispEM(['The following fields have one or more entries that do not start '...
+0087         'with a letter or _ (conflicting with SBML specifications). Prefixes '...
+0088         'are added to all entries in those fields:'],false,hasChanged)
+0089 end
+0090 
+0091 %Check the model structure
+0092 if supressWarnings==false
+0093     checkModelStruct(model);
+0094 end
+0095 
+0096 %Add several blank fields, if they do not exist already. This is to reduce
+0097 %the number of conditions below
+0098 if ~isfield(model,'compMiriams')
+0099     model.compMiriams=cell(numel(model.comps),1);
+0100 end
+0101 if ~isfield(model,'inchis')
+0102     model.inchis=cell(numel(model.mets),1);
+0103 end
+0104 if ~isfield(model,'metFormulas')
+0105     model.metFormulas=cell(numel(model.mets),1);
+0106 end
+0107 if ~isfield(model,'metMiriams')
+0108     model.metMiriams=cell(numel(model.mets),1);
+0109 end
+0110 if ~isfield(model,'geneMiriams') && isfield(model,'genes')
+0111     model.geneMiriams=cell(numel(model.genes),1);
+0112 end
+0113 if ~isfield(model,'geneShortNames') && isfield(model,'genes')
+0114     model.geneShortNames=cell(numel(model.genes),1);
+0115 end
+0116 if ~isfield(model,'proteins') && isfield(model,'genes')
+0117     model.proteins=cell(numel(model.genes),1);
+0118 end
+0119 if ~isfield(model,'subSystems')
+0120     model.subSystems=cell(numel(model.rxns),1);
+0121 end
+0122 if ~isfield(model,'eccodes')
+0123     model.eccodes=cell(numel(model.rxns),1);
+0124 end
+0125 if ~isfield(model,'rxnReferences')
+0126     model.rxnReferences=cell(numel(model.rxns),1);
+0127 end
+0128 if ~isfield(model,'rxnConfidenceScores')
+0129     model.rxnConfidenceScores=NaN(numel(model.rxns),1);
+0130 end
+0131 if ~isfield(model,'rxnNotes')
+0132     model.rxnNotes=cell(numel(model.rxns),1);
+0133 end
+0134 if ~isfield(model,'rxnMiriams')
+0135     model.rxnMiriams=cell(numel(model.rxns),1);
+0136 end
+0137 
+0138 if sbmlLevel<3
+0139     %Check if genes have associated compartments
+0140     if ~isfield(model,'geneComps') && isfield(model,'genes')
+0141         if supressWarnings==false
+0142             EM='There are no compartments specified for genes. All genes will be assigned to the first compartment. This is because the SBML structure requires all elements to be assigned to a compartment';
+0143             dispEM(EM,false);
+0144         end
+0145         model.geneComps=ones(numel(model.genes),1);
+0146     end
+0147 end
+0148 
+0149 %Convert ids to SBML-convenient format. This is to avoid the data loss when
+0150 %unsupported characters are included in ids. Here we are using part from
+0151 %convertSBMLID, originating from the COBRA Toolbox
+0152 model.rxns=regexprep(model.rxns,'([^0-9_a-zA-Z])','__${num2str($1+0)}__');
+0153 model.mets=regexprep(model.mets,'([^0-9_a-zA-Z])','__${num2str($1+0)}__');
+0154 model.comps=regexprep(model.comps,'([^0-9_a-zA-Z])','__${num2str($1+0)}__');
+0155 if isfield(model,'genes')
+0156     problemGenes=find(~cellfun('isempty',regexp(model.genes,'([^0-9_a-zA-Z])')));
+0157     originalGenes=model.genes(problemGenes);
+0158     replacedGenes=regexprep(model.genes(problemGenes),'([^0-9_a-zA-Z])','__${num2str($1+0)}__');
+0159     model.genes(problemGenes)=replacedGenes;
+0160     for i=1:numel(problemGenes)
+0161         model.grRules = regexprep(model.grRules, ['(^|\s|\()' originalGenes{i} '($|\s|\))'], ['$1' replacedGenes{i} '$2']);
+0162     end
+0163 end
+0164 
+0165 %Generate an empty SBML structure
+0166 modelSBML=getSBMLStructure(sbmlLevel,sbmlVersion,sbmlPackages,sbmlPackageVersions);
+0167 modelSBML.metaid=model.id;
+0168 modelSBML.id=regexprep(model.id,'([^0-9_a-zA-Z])','__${num2str($1+0)}__');
+0169 modelSBML.name=model.name;
+0170 
+0171 if isfield(model,'annotation')
+0172     if isfield(model.annotation,'note')
+0173         modelSBML.notes=['<notes><body xmlns="http://www.w3.org/1999/xhtml"><p>',regexprep(model.annotation.note,'<p>|</p>',''),'</p></body></notes>'];
+0174     end
+0175 else
+0176     modelSBML.notes='<notes><body xmlns="http://www.w3.org/1999/xhtml"><p>This file was generated using the exportModel function in RAVEN Toolbox 2 and OutputSBML in libSBML </p></body></notes>';
+0177 end
+0178 
+0179 if isfield(model,'annotation')
+0180     nameString='';
+0181     if isfield(model.annotation,'familyName')
+0182         if ~isempty(model.annotation.familyName)
+0183             nameString=['<vCard:Family>' model.annotation.familyName '</vCard:Family>'];
+0184         end
+0185     end
+0186     if isfield(model.annotation,'givenName')
+0187         if ~isempty(model.annotation.givenName)
+0188             nameString=[nameString '<vCard:Given>' model.annotation.givenName '</vCard:Given>'];
+0189         end
+0190     end
+0191     email='';
+0192     if isfield(model.annotation,'email')
+0193         if ~isempty(model.annotation.email)
+0194             email=['<vCard:EMAIL>' model.annotation.email '</vCard:EMAIL>'];
+0195         end
+0196     end
+0197     org='';
+0198     if isfield(model.annotation,'organization')
+0199         if ~isempty(model.annotation.organization)
+0200             org=['<vCard:ORG rdf:parseType="Resource"><vCard:Orgname>' model.annotation.organization '</vCard:Orgname></vCard:ORG>'];
+0201         end
+0202     end
+0203     if ~isempty(nameString) || ~isempty(email) || ~isempty(org) % Only fill .annotation if ownership data is provided
+0204         modelSBML.annotation=['<annotation><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#" xmlns:bqbiol="http://biomodels.net/biology-qualifiers/" xmlns:bqmodel="http://biomodels.net/model-qualifiers/"><rdf:Description rdf:about="#meta_' model.id '">'];
+0205         modelSBML.annotation=[modelSBML.annotation '<dc:creator><rdf:Bag><rdf:li rdf:parseType="Resource">'];
+0206         if ~isempty(nameString)
+0207             modelSBML.annotation=[modelSBML.annotation '<vCard:N rdf:parseType="Resource">' nameString '</vCard:N>'];
+0208         end
+0209         modelSBML.annotation=[modelSBML.annotation email org '</rdf:li></rdf:Bag></dc:creator>'];
+0210         modelSBML.annotation=[modelSBML.annotation '<dcterms:created rdf:parseType="Resource">'...
+0211             '<dcterms:W3CDTF>' datestr(now,'yyyy-mm-ddTHH:MM:SSZ') '</dcterms:W3CDTF></dcterms:created><dcterms:modified rdf:parseType="Resource">'...
+0212             '<dcterms:W3CDTF>' datestr(now,'yyyy-mm-ddTHH:MM:SSZ') '</dcterms:W3CDTF></dcterms:modified>'];
+0213         if isfield(model.annotation,'taxonomy')
+0214             modelSBML.annotation=[modelSBML.annotation '<bqbiol:is><rdf:Bag><rdf:li rdf:resource="https://identifiers.org/taxonomy/' regexprep(model.annotation.taxonomy,'taxonomy/','') '"/></rdf:Bag></bqbiol:is>'];
+0215         end
+0216         modelSBML.annotation=[modelSBML.annotation '</rdf:Description></rdf:RDF></annotation>'];
+0217     end
+0218 end
+0219 
+0220 %Prepare compartments
+0221 for i=1:numel(model.comps)
+0222     %Add the default values, as these will be the same in all entries
+0223     if i==1
+0224         if isfield(modelSBML.compartment, 'sboTerm')
+0225             modelSBML.compartment(i).sboTerm=290;
+0226         end
+0227         if isfield(modelSBML.compartment, 'spatialDimensions')
+0228             modelSBML.compartment(i).spatialDimensions=3;
+0229         end
+0230         if isfield(modelSBML.compartment, 'size')
+0231             modelSBML.compartment(i).size=1;
+0232         end
+0233         if isfield(modelSBML.compartment, 'constant')
+0234             modelSBML.compartment(i).constant=1;
+0235         end
+0236         if isfield(modelSBML.compartment, 'isSetSize')
+0237             modelSBML.compartment(i).isSetSize=1;
+0238         end
+0239         if isfield(modelSBML.compartment, 'isSetSpatialDimensions')
+0240             modelSBML.compartment(i).isSetSpatialDimensions=1;
+0241         end
+0242     end
+0243     %Copy the default values to the next entry as long as it is not the
+0244     %last one
+0245     if i<numel(model.comps)
+0246         modelSBML.compartment(i+1)=modelSBML.compartment(i);
+0247     end
+0248 
+0249     if isfield(modelSBML.compartment,'metaid')
+0250         modelSBML.compartment(i).metaid=model.comps{i};
+0251     end
+0252     %Prepare Miriam strings
+0253     if ~isempty(model.compMiriams{i})
+0254         [~,sbo_ind] = ismember('sbo',model.compMiriams{i}.name);
+0255         if sbo_ind > 0
+0256             modelSBML.compartment(i).sboTerm=str2double(regexprep(model.compMiriams{i}.value{sbo_ind},'SBO:','','ignorecase'));
+0257             % remove the SBO term from compMiriams so the information is
+0258             % not duplicated in the "annotation" field later on
+0259             model.compMiriams{i}.name(sbo_ind) = [];
+0260             model.compMiriams{i}.value(sbo_ind) = [];
+0261         end
+0262     end
+0263     if ~isempty(model.compMiriams{i}) && isfield(modelSBML.compartment(i),'annotation')
+0264         modelSBML.compartment(i).annotation=['<annotation><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#" xmlns:bqbiol="http://biomodels.net/biology-qualifiers/" xmlns:bqmodel="http://biomodels.net/model-qualifiers/"><rdf:Description rdf:about="#meta_' model.comps{i} '">'];
+0265         modelSBML.compartment(i).annotation=[modelSBML.compartment(i).annotation '<bqbiol:is><rdf:Bag>'];
+0266         modelSBML.compartment(i).annotation=[modelSBML.compartment(i).annotation getMiriam(model.compMiriams{i}) '</rdf:Bag></bqbiol:is></rdf:Description></rdf:RDF></annotation>'];
+0267     end
+0268     if isfield(modelSBML.compartment, 'name')
+0269         modelSBML.compartment(i).name=model.compNames{i};
+0270     end
+0271     if isfield(modelSBML.compartment, 'id')
+0272         modelSBML.compartment(i).id=model.comps{i};
+0273     end
+0274 
+0275 end
+0276 
+0277 %Begin writing species
+0278 for i=1:numel(model.mets)
+0279     %Add the default values, as these will be the same in all entries
+0280     if i==1
+0281         if isfield(modelSBML.species, 'sboTerm')
+0282             modelSBML.species(i).sboTerm=247;
+0283         end
+0284         if isfield(modelSBML.species, 'initialAmount')
+0285             modelSBML.species(i).initialAmount=1;
+0286         end
+0287         if isfield(modelSBML.species, 'initialConcentration')
+0288             modelSBML.species(i).initialConcentration=0;
+0289         end
+0290         if isfield(modelSBML.species, 'isSetInitialAmount')
+0291             modelSBML.species(i).isSetInitialAmount=1;
+0292         end
+0293         if isfield(modelSBML.species, 'isSetInitialConcentration')
+0294             modelSBML.species(i).isSetInitialConcentration=1;
+0295         end
+0296     end
+0297     %Copy the default values to the next entry as long as it is not the
+0298     %last one
+0299     if i<numel(model.mets)
+0300         modelSBML.species(i+1)=modelSBML.species(i);
+0301     end
+0302 
+0303     if isfield(modelSBML.species,'metaid')
+0304         modelSBML.species(i).metaid=model.mets{i};
+0305     end
+0306     if isfield(modelSBML.species, 'name')
+0307         modelSBML.species(i).name=model.metNames{i};
+0308     end
+0309     if isfield(modelSBML.species, 'id')
+0310         modelSBML.species(i).id=model.mets{i};
+0311     end
+0312     if isfield(modelSBML.species, 'compartment')
+0313         modelSBML.species(i).compartment=model.comps{model.metComps(i)};
+0314     end
+0315     if isfield(model,'unconstrained')
+0316         if model.unconstrained(i)
+0317             modelSBML.species(i).boundaryCondition=1;
+0318         end
+0319     end
+0320     if isfield(modelSBML.species, 'fbc_charge') && isfield(model,'metCharges')
+0321         if ~isnan(model.metCharges(i))
+0322             modelSBML.species(i).fbc_charge=model.metCharges(i);
+0323             modelSBML.species(i).isSetfbc_charge=1;
+0324         else
+0325             modelSBML.species(i).isSetfbc_charge=0;
+0326         end
+0327     end
+0328     if ~isempty(model.metMiriams{i})
+0329         [~,sbo_ind] = ismember('sbo',model.metMiriams{i}.name);
+0330         if sbo_ind > 0
+0331             modelSBML.species(i).sboTerm=str2double(regexprep(model.metMiriams{i}.value{sbo_ind},'SBO:','','ignorecase'));
+0332             % remove the SBO term from metMiriams so the information is
+0333             % not duplicated in the "annotation" field later on
+0334             model.metMiriams{i}.name(sbo_ind) = [];
+0335             model.metMiriams{i}.value(sbo_ind) = [];
+0336         end
+0337     end
+0338     if isfield(modelSBML.species,'annotation')
+0339         if ~isempty(model.metMiriams{i}) || ~isempty(model.metFormulas{i})
+0340             hasInchi=false;
+0341             if ~isempty(model.metFormulas{i})
+0342                 %Only export formula if there is no InChI. This is because
+0343                 %the metFormulas field is populated by InChIs if available
+0344                 if ~isempty(model.inchis{i})
+0345                     hasInchi=true;
+0346                 end
+0347                 if hasInchi==false
+0348                     modelSBML.species(i).fbc_chemicalFormula=model.metFormulas{i};
+0349                 end
+0350             end
+0351             if ~isempty(model.metMiriams{i}) || hasInchi==true
+0352                 modelSBML.species(i).annotation=['<annotation><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#" xmlns:bqbiol="http://biomodels.net/biology-qualifiers/" xmlns:bqmodel="http://biomodels.net/model-qualifiers/"><rdf:Description rdf:about="#meta_' model.mets{i} '">'];
+0353                 modelSBML.species(i).annotation=[modelSBML.species(i).annotation '<bqbiol:is><rdf:Bag>'];
+0354                 if ~isempty(model.metMiriams{i})
+0355                     modelSBML.species(i).annotation=[modelSBML.species(i).annotation getMiriam(model.metMiriams{i})];
+0356                 end
+0357                 if hasInchi==true
+0358                     modelSBML.species(i).annotation=[modelSBML.species(i).annotation '<rdf:li rdf:resource="https://identifiers.org/inchi/InChI=' regexprep(model.inchis{i},'^InChI=','') '"/>'];
+0359                     modelSBML.species(i).fbc_chemicalFormula=char(regexp(model.inchis{i}, '/(\w+)/', 'tokens', 'once'));
+0360                 end
+0361                 modelSBML.species(i).annotation=[modelSBML.species(i).annotation '</rdf:Bag></bqbiol:is></rdf:Description></rdf:RDF></annotation>'];
+0362             end
+0363         end
+0364     end
+0365 end
+0366 
+0367 if isfield(model,'genes')
+0368     for i=1:numel(model.genes)
+0369         %Add the default values, as these will be the same in all entries
+0370         if i==1
+0371             if isfield(modelSBML.fbc_geneProduct, 'sboTerm')
+0372                 modelSBML.fbc_geneProduct(i).sboTerm=243;
+0373             end
+0374         end
+0375         %Copy the default values to the next index as long as it is not the
+0376         %last one
+0377         if i<numel(model.genes)
+0378             modelSBML.fbc_geneProduct(i+1)=modelSBML.fbc_geneProduct(i);
+0379         end
+0380 
+0381         if isfield(modelSBML.fbc_geneProduct,'metaid')
+0382             modelSBML.fbc_geneProduct(i).metaid=model.genes{i};
+0383         end
+0384         if ~isempty(model.geneMiriams{i})
+0385             [~,sbo_ind] = ismember('sbo',model.geneMiriams{i}.name);
+0386             if sbo_ind > 0
+0387                 modelSBML.fbc_geneProduct(i).sboTerm=str2double(regexprep(model.geneMiriams{i}.value{sbo_ind},'SBO:','','ignorecase'));
+0388                 % remove the SBO term from compMiriams so the information is
+0389                 % not duplicated in the "annotation" field later on
+0390                 model.geneMiriams{i}.name(sbo_ind) = [];
+0391                 model.geneMiriams{i}.value(sbo_ind) = [];
+0392             end
+0393         end
+0394         if ~isempty(model.geneMiriams{i}) && isfield(modelSBML.fbc_geneProduct(i),'annotation')
+0395             modelSBML.fbc_geneProduct(i).annotation=['<annotation><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#" xmlns:bqbiol="http://biomodels.net/biology-qualifiers/" xmlns:bqmodel="http://biomodels.net/model-qualifiers/"><rdf:Description rdf:about="#meta_' model.genes{i} '">'];
+0396             modelSBML.fbc_geneProduct(i).annotation=[modelSBML.fbc_geneProduct(i).annotation '<bqbiol:is><rdf:Bag>'];
+0397             modelSBML.fbc_geneProduct(i).annotation=[modelSBML.fbc_geneProduct(i).annotation getMiriam(model.geneMiriams{i}) '</rdf:Bag></bqbiol:is></rdf:Description></rdf:RDF></annotation>'];
+0398         end
+0399         if isfield(modelSBML.fbc_geneProduct, 'fbc_id')
+0400             modelSBML.fbc_geneProduct(i).fbc_id=model.genes{i};
+0401         end
+0402         if isfield(modelSBML.fbc_geneProduct, 'fbc_label') && isfield(model,'geneShortNames')
+0403             if isempty(model.geneShortNames{i})
+0404                 modelSBML.fbc_geneProduct(i).fbc_label=model.genes{i};
+0405             else
+0406                 modelSBML.fbc_geneProduct(i).fbc_label=model.geneShortNames{i};
+0407             end
+0408         end
+0409         if isfield(modelSBML.fbc_geneProduct, 'fbc_name') && isfield(model,'proteins')
+0410             if ~isempty(model.proteins{i})
+0411                 modelSBML.fbc_geneProduct(i).fbc_name=model.proteins{i};
+0412             end
+0413         end
+0414     end
+0415 end
+0416 
+0417 %Generate a list of unique fbc_bound names
+0418 totalValues=[model.lb; model.ub];
+0419 totalNames=cell(size(totalValues,1),1);
+0420 
+0421 listUniqueValues=unique(totalValues);
+0422 
+0423 for i=1:length(listUniqueValues)
+0424     listUniqueNames{i,1}=['FB',num2str(i),'N',num2str(abs(round(listUniqueValues(i))))]; % create unique flux bound IDs.
+0425     ind=find(ismember(totalValues,listUniqueValues(i)));
+0426     totalNames(ind)=listUniqueNames(i,1);
+0427 end
+0428 
+0429 for i=1:length(listUniqueNames)
+0430     %Add the default values, as these will be the same in all entries
+0431     if i==1
+0432         if isfield(modelSBML.parameter, 'constant')
+0433             modelSBML.parameter(i).constant=1;
+0434         end
+0435         if isfield(modelSBML.parameter, 'isSetValue')
+0436             modelSBML.parameter(i).isSetValue=1;
+0437         end
+0438     end
+0439     %Copy the default values to the next index as long as it is not the
+0440     %last one
+0441     if i<numel(listUniqueNames)
+0442         modelSBML.parameter(i+1)=modelSBML.parameter(i);
+0443     end
+0444     modelSBML.parameter(i).id=listUniqueNames{i};
+0445     modelSBML.parameter(i).value=listUniqueValues(i);
+0446 end
+0447 
+0448 for i=1:numel(model.rxns)
+0449     %Add the default values, as these will be the same in all entries
+0450     if i==1
+0451         if isfield(modelSBML.reaction, 'sboTerm')
+0452             modelSBML.reaction(i).sboTerm=176;
+0453         end
+0454         if isfield(modelSBML.reaction, 'isSetFast')
+0455             modelSBML.reaction(i).isSetFast=1;
+0456         end
+0457     end
+0458     %Copy the default values to the next index as long as it is not the
+0459     %last one
+0460     if i<numel(model.rxns)
+0461         modelSBML.reaction(i+1)=modelSBML.reaction(i);
+0462     end
+0463 
+0464     if isfield(modelSBML.reaction,'metaid')
+0465         modelSBML.reaction(i).metaid=model.rxns{i};
+0466     end
+0467 
+0468     %Export notes information
+0469     if (~isnan(model.rxnConfidenceScores(i)) || ~isempty(model.rxnReferences{i}) || ~isempty(model.rxnNotes{i}))
+0470         modelSBML.reaction(i).notes='<notes><body xmlns="http://www.w3.org/1999/xhtml">';
+0471         if ~isnan(model.rxnConfidenceScores(i))
+0472             modelSBML.reaction(i).notes=[modelSBML.reaction(i).notes '<p>Confidence Level: ' num2str(model.rxnConfidenceScores(i)) '</p>'];
+0473         end
+0474         if ~isempty(model.rxnReferences{i})
+0475             modelSBML.reaction(i).notes=[modelSBML.reaction(i).notes '<p>AUTHORS: ' model.rxnReferences{i} '</p>'];
+0476         end
+0477         if ~isempty(model.rxnNotes{i})
+0478             modelSBML.reaction(i).notes=[modelSBML.reaction(i).notes '<p>NOTES: ' model.rxnNotes{i} '</p>'];
+0479         end
+0480         modelSBML.reaction(i).notes=[modelSBML.reaction(i).notes '</body></notes>'];
+0481     end
+0482 
+0483     % Export SBO terms from rxnMiriams
+0484     if ~isempty(model.rxnMiriams{i})
+0485         [~,sbo_ind] = ismember('sbo',model.rxnMiriams{i}.name);
+0486         if sbo_ind > 0
+0487             modelSBML.reaction(i).sboTerm=str2double(regexprep(model.rxnMiriams{i}.value{sbo_ind},'SBO:','','ignorecase'));
+0488             % remove the SBO term from rxnMiriams so the information is not
+0489             % duplicated in the "annotation" field later on
+0490             model.rxnMiriams{i}.name(sbo_ind) = [];
+0491             model.rxnMiriams{i}.value(sbo_ind) = [];
+0492         end
+0493     end
+0494 
+0495     %Export annotation information from rxnMiriams
+0496     if (~isempty(model.rxnMiriams{i}) && isfield(modelSBML.reaction(i),'annotation')) || ~isempty(model.eccodes{i})
+0497         modelSBML.reaction(i).annotation=['<annotation><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#" xmlns:bqbiol="http://biomodels.net/biology-qualifiers/" xmlns:bqmodel="http://biomodels.net/model-qualifiers/"><rdf:Description rdf:about="#meta_' model.rxns{i} '">'];
+0498         modelSBML.reaction(i).annotation=[modelSBML.reaction(i).annotation '<bqbiol:is><rdf:Bag>'];
+0499         if ~isempty(model.eccodes{i})
+0500             eccodes=regexp(model.eccodes{i},';','split');
+0501             for j=1:numel(eccodes)
+0502                 modelSBML.reaction(i).annotation=[modelSBML.reaction(i).annotation  '<rdf:li rdf:resource="https://identifiers.org/ec-code/' regexprep(eccodes{j},'ec-code/|EC','') '"/>'];
+0503             end
+0504         end
+0505         modelSBML.reaction(i).annotation=[modelSBML.reaction(i).annotation getMiriam(model.rxnMiriams{i}) '</rdf:Bag></bqbiol:is></rdf:Description></rdf:RDF></annotation>'];
+0506     end
+0507 
+0508     if isfield(modelSBML.reaction, 'name')
+0509         modelSBML.reaction(i).name=model.rxnNames{i};
+0510     end
+0511     if isfield(modelSBML.reaction, 'id')
+0512         modelSBML.reaction(i).id=model.rxns{i};
+0513     end
+0514 
+0515     %Add the information about reactants and products
+0516     involvedMets=addReactantsProducts(model,modelSBML,i);
+0517     for j=1:numel(involvedMets.reactant)
+0518         if j<numel(involvedMets.reactant)
+0519             modelSBML.reaction(i).reactant(j+1)=modelSBML.reaction(i).reactant(j);
+0520         end
+0521         modelSBML.reaction(i).reactant(j).species=involvedMets.reactant(j).species;
+0522         modelSBML.reaction(i).reactant(j).stoichiometry=involvedMets.reactant(j).stoichiometry;
+0523         modelSBML.reaction(i).reactant(j).isSetStoichiometry=involvedMets.reactant(j).isSetStoichiometry;
+0524         modelSBML.reaction(i).reactant(j).constant=involvedMets.reactant(j).constant;
+0525     end
+0526     if numel(involvedMets.reactant)==0
+0527         modelSBML.reaction(i).reactant='';
+0528     end
+0529     for j=1:numel(involvedMets.product)
+0530         if j<numel(involvedMets.product)
+0531             modelSBML.reaction(i).product(j+1)=modelSBML.reaction(i).product(j);
+0532         end
+0533         modelSBML.reaction(i).product(j).species=involvedMets.product(j).species;
+0534         modelSBML.reaction(i).product(j).stoichiometry=involvedMets.product(j).stoichiometry;
+0535         modelSBML.reaction(i).product(j).isSetStoichiometry=involvedMets.product(j).isSetStoichiometry;
+0536         modelSBML.reaction(i).product(j).constant=involvedMets.product(j).constant;
+0537     end
+0538     if numel(involvedMets.product)==0
+0539         modelSBML.reaction(i).product='';
+0540     end
+0541     %Export reversibility information. Reactions are irreversible by
+0542     %default
+0543     if model.rev(i)==1
+0544         modelSBML.reaction(i).reversible=1;
+0545     end
+0546     if isfield(model, 'rxnComps')
+0547         modelSBML.reaction(i).compartment=model.comps{model.rxnComps(i)};
+0548     end
+0549     if isfield(model, 'grRules')
+0550         modelSBML.reaction(i).fbc_geneProductAssociation.fbc_association.fbc_association=model.grRules{i};
+0551     end
+0552     modelSBML.reaction(i).fbc_lowerFluxBound=totalNames{i};
+0553     modelSBML.reaction(i).fbc_upperFluxBound=totalNames{length(model.lb)+i};
+0554 end
+0555 
+0556 %Prepare subSystems
+0557 if modelHasSubsystems
+0558     modelSBML.groups_group.groups_kind = 'partonomy';
+0559     modelSBML.groups_group.sboTerm     = 633;
+0560     grpTemplate = modelSBML.groups_group;
+0561 
+0562     % === 1) Normalize: make every entry a cell array of chars (vectorized) ===
+0563     isChar = cellfun(@ischar, model.subSystems);
+0564     model.subSystems(isChar)  = cellfun(@(s){s}, model.subSystems(isChar),  'UniformOutput', false);
+0565     model.subSystems(cellfun(@isempty, model.subSystems)) = {{}};
+0566 
+0567     % If some entries contain string scalars by mistake, coerce them. Also
+0568     % force each entry to a column cell array, so that reactions with
+0569     % different numbers of subsystems can be concatenated below (otherwise
+0570     % mixing e.g. 1x1 and 1x2 entries breaks vertcat):
+0571     model.subSystems = cellfun(@(c) reshape(cellfun(@char, c, 'UniformOutput', false), [], 1), model.subSystems, 'UniformOutput', false);
+0572 
+0573     % === 2) Flatten once: names and their reaction indices (vectorized) ===
+0574     flatNames = vertcat(model.subSystems{:});                    % Mx1 cellstr of all subsystem labels
+0575     if isempty(flatNames)
+0576         % Nothing to do: no subsystems present
+0577         return
+0578     end
+0579 
+0580     counts   = cellfun(@numel, model.subSystems);         % reactions -> how many subsystems
+0581     % For each reaction r, repeat r exactly counts(r) times
+0582     flatIdx  = arrayfun(@(r,c) repmat(r, c, 1), (1:numel(model.subSystems)).', counts, 'UniformOutput', false);
+0583     flatIdx  = vertcat(flatIdx{:});           % M×1 vector of reaction indices
+0584 
+0585     % === 3) Group in one shot: unique subsystems + members per subsystem ===
+0586     [subSystems, ~, g] = unique(flatNames, 'stable');          % stable preserves first appearance
+0587     membersIdx = accumarray(g, flatIdx, [], @(v){v});          % cell: one vector of r-idx per group
+0588     nSubs = numel(subSystems);
+0589 
+0590     % === 4) Preallocate and build SBML groups (single simple loop) ===
+0591     modelSBML.groups_group(1:nSubs) = grpTemplate;
+0592     groupIDs = "group" + (1:nSubs);
+0593 
+0594     if isfield(grpTemplate,'groups_member')
+0595         memTemplate = grpTemplate.groups_member;
+0596     else
+0597         memTemplate = struct('groups_idRef','');
+0598     end
+0599 
+0600     for i = 1:nSubs
+0601         rIdx       = membersIdx{i};
+0602         groupRXNs  = model.rxns(rIdx);
+0603         cgroup     = grpTemplate;
+0604 
+0605         % Preallocate and fill members
+0606         nM = numel(groupRXNs);
+0607         if nM > 0
+0608             cgroup.groups_member(1:nM) = memTemplate;
+0609             [cgroup.groups_member.groups_idRef] = deal(groupRXNs{:});
+0610         else
+0611             cgroup.groups_member = repmat(memTemplate, 0, 1);
+0612         end
+0613 
+0614         cgroup.groups_id   = char(groupIDs(i));     % keep as char for SBML compatibility
+0615         cgroup.groups_name = subSystems{i};
+0616         modelSBML.groups_group(i) = cgroup;
+0617     end
+0618 end
+0619 
+0620 
+0621 %Prepare fbc_objective subfield
+0622 
+0623 modelSBML.fbc_objective.fbc_type='maximize';
+0624 modelSBML.fbc_objective.fbc_id='obj';
+0625 
+0626 ind=find(model.c);
+0627 
+0628 if isempty(ind)
+0629     modelSBML.fbc_objective.fbc_fluxObjective.fbc_coefficient=0;
+0630 else
+0631     for i=1:length(ind)
+0632         %Copy the default values to the next index as long as it is not the
+0633         %last one
+0634         if i<numel(ind)
+0635             modelSBML.reaction(i+1)=modelSBML.reaction(i);
+0636         end
+0637         values=model.c(model.c~=0);
+0638         modelSBML.fbc_objective(i).fbc_fluxObjective.fbc_reaction=modelSBML.reaction(ind(i)).id;
+0639         modelSBML.fbc_objective(i).fbc_fluxObjective.fbc_coefficient=values(i);
+0640         modelSBML.fbc_objective(i).fbc_fluxObjective.isSetfbc_coefficient=1;
+0641     end
+0642 end
+0643 
+0644 modelSBML.fbc_activeObjective=modelSBML.fbc_objective.fbc_id;
+0645 
+0646 fbcStr=['http://www.sbml.org/sbml/level', num2str(sbmlLevel), '/version', num2str(sbmlVersion), '/fbc/version',num2str(sbmlPackageVersions(1))];
+0647 if modelHasSubsystems
+0648     groupStr=['http://www.sbml.org/sbml/level', num2str(sbmlLevel), '/version', num2str(sbmlVersion), '/groups/version',num2str(sbmlPackageVersions(2))];
+0649     modelSBML.namespaces=struct('prefix',{'','fbc','groups'},...
+0650         'uri',{['http://www.sbml.org/sbml/level', num2str(sbmlLevel), '/version', num2str(sbmlVersion), '/core'],...
+0651         fbcStr,groupStr});
+0652 else
+0653     modelSBML.namespaces=struct('prefix',{'','fbc'},...
+0654         'uri',{['http://www.sbml.org/sbml/level', num2str(sbmlLevel), '/version', num2str(sbmlVersion), '/core'],...
+0655         fbcStr});
+0656 end
+0657 
+0658 if sbmlPackageVersions(1) == 2
+0659     modelSBML.fbc_strict=1;
+0660     modelSBML.isSetfbc_strict = 1;
+0661 end
+0662 
+0663 modelSBML.rule=[];
+0664 modelSBML.constraint=[];
+0665 
+0666 [ravenDir,prevDir]=findRAVENroot();
+0667 fileName=checkFileExistence(fileName,1,true,false);
+0668 
+0669 OutputSBML_RAVEN(modelSBML,fileName,1,0,[1,0]);
+0670 end
+0671 
+0672 
+0673 function modelSBML=getSBMLStructure(sbmlLevel,sbmlVersion,sbmlPackages,sbmlPackageVersions)
+0674 %Returns the blank SBML model structure by using appropriate libSBML
+0675 %functions. This creates structure by considering three levels
+0676 
+0677 sbmlFieldNames=getStructureFieldnames('model',sbmlLevel,sbmlVersion,sbmlPackages,sbmlPackageVersions);
+0678 sbmlDefaultValues=getDefaultValues('model',sbmlLevel,sbmlVersion,sbmlPackages,sbmlPackageVersions);
+0679 
+0680 for i=1:numel(sbmlFieldNames)
+0681     modelSBML.(sbmlFieldNames{1,i})=sbmlDefaultValues{1,i};
+0682     sbmlSubfieldNames=getStructureFieldnames(sbmlFieldNames{1,i},sbmlLevel,sbmlVersion,sbmlPackages,sbmlPackageVersions);
+0683     sbmlSubfieldValues=getDefaultValues(sbmlFieldNames{1,i},sbmlLevel,sbmlVersion,sbmlPackages,sbmlPackageVersions);
+0684     if ~strcmp(sbmlFieldNames{1,i},'event') && ~strcmp(sbmlFieldNames{1,i},'functionDefinition') && ~strcmp(sbmlFieldNames{1,i},'initialAssignment')
+0685         for j=1:numel(sbmlSubfieldNames)
+0686             modelSBML.(sbmlFieldNames{1,i}).(sbmlSubfieldNames{1,j})=sbmlSubfieldValues{1,j};
+0687             sbmlSubsubfieldNames=getStructureFieldnames(sbmlSubfieldNames{1,j},sbmlLevel,sbmlVersion,sbmlPackages,sbmlPackageVersions);
+0688             sbmlSubsubfieldValues=getDefaultValues(sbmlSubfieldNames{1,j},sbmlLevel,sbmlVersion,sbmlPackages,sbmlPackageVersions);
+0689             if ~strcmp(sbmlSubfieldNames{1,j},'modifier') && ~strcmp(sbmlSubfieldNames{1,j},'kineticLaw')
+0690                 for k=1:numel(sbmlSubsubfieldNames)
+0691                     %'compartment' and 'species' fields are not supposed to
+0692                     %have their standalone structures if they are subfields
+0693                     %or subsubfields
+0694                     if ~strcmp(sbmlSubfieldNames{1,j},'compartment') && ~strcmp(sbmlSubfieldNames{1,j},'species')
+0695                         modelSBML.(sbmlFieldNames{1,i}).(sbmlSubfieldNames{1,j}).(sbmlSubsubfieldNames{1,k})=sbmlSubsubfieldValues{1,k};
+0696                     end
+0697                     %If it is fbc_association in the third level, we need
+0698                     %to establish the fourth level, since libSBML requires
+0699                     %it
+0700                     if strcmp(sbmlSubsubfieldNames{1,k},'fbc_association')
+0701                         fbc_associationFieldNames=getStructureFieldnames('fbc_association',sbmlLevel,sbmlVersion,sbmlPackages,sbmlPackageVersions);
+0702                         fbc_associationFieldValues=getDefaultValues('fbc_association',sbmlLevel,sbmlVersion,sbmlPackages,sbmlPackageVersions);
+0703                         for l=1:numel(fbc_associationFieldNames)
+0704                             modelSBML.(sbmlFieldNames{1,i}).(sbmlSubfieldNames{1,j}).(sbmlSubsubfieldNames{1,k}).(fbc_associationFieldNames{1,l})=fbc_associationFieldValues{1,l};
+0705                         end
+0706                     end
+0707                 end
+0708             end
+0709         end
+0710     end
+0711     if ~isstruct(modelSBML.(sbmlFieldNames{1,i}))
+0712         modelSBML.(sbmlFieldNames{1,i})=sbmlDefaultValues{1,i};
+0713     end
+0714 end
+0715 
+0716 modelSBML.unitDefinition.id='mmol_per_gDW_per_hr';
+0717 
+0718 unitFieldNames=getStructureFieldnames('unit',sbmlLevel,sbmlVersion,sbmlPackages,sbmlPackageVersions);
+0719 unitDefaultValues=getDefaultValues('unit',sbmlLevel,sbmlVersion,sbmlPackages,sbmlPackageVersions);
+0720 
+0721 kinds={'mole','gram','second'};
+0722 exponents=[1 -1 -1];
+0723 scales=[-3 0 0];
+0724 multipliers=[1 1 1*60*60];
+0725 
+0726 for i=1:numel(unitFieldNames)
+0727     modelSBML.unitDefinition.unit(1).(unitFieldNames{1,i})=unitDefaultValues{1,i};
+0728     for j=1:3
+0729         modelSBML.unitDefinition.unit(j).(unitFieldNames{1,i})=unitDefaultValues{1,i};
+0730         if strcmp(unitFieldNames{1,i},'kind')
+0731             modelSBML.unitDefinition.unit(j).(unitFieldNames{1,i})=kinds{j};
+0732         elseif strcmp(unitFieldNames{1,i},'exponent')
+0733             modelSBML.unitDefinition.unit(j).(unitFieldNames{1,i})=exponents(j);
+0734         elseif strcmp(unitFieldNames{1,i},'scale')
+0735             modelSBML.unitDefinition.unit(j).(unitFieldNames{1,i})=scales(j);
+0736         elseif strcmp(unitFieldNames{1,i},'multiplier')
+0737             modelSBML.unitDefinition.unit(j).(unitFieldNames{1,i})=multipliers(j);
+0738         end
+0739     end
+0740 end
+0741 end
+0742 
+0743 function miriamString=getMiriam(miriamStruct)
+0744 %Returns a string with list elements for a miriam structure ('<rdf:li
+0745 %rdf:resource="https://identifiers.org/go/GO:0005739"/>' for example). This
+0746 %is just to speed up things since this is done many times during the
+0747 %exporting
+0748 
+0749 miriamString='';
+0750 if isfield(miriamStruct,'name')
+0751     for i=1:numel(miriamStruct.name)
+0752         miriamString=[miriamString '<rdf:li rdf:resource="https://identifiers.org/' miriamStruct.name{i} '/' miriamStruct.value{i} '"/>'];
+0753     end
+0754 end
+0755 end
+0756 
+0757 function [tmp_Rxn]=addReactantsProducts(model,sbmlModel,i)
+0758 %This function provides reactants and products for particular reaction. The
+0759 %function was 'borrowed' from writeSBML in COBRA toolbox, lines 663-679
+0760 
+0761 met_idx = find(model.S(:, i));
+0762 tmp_Rxn.product=[];
+0763 tmp_Rxn.reactant=[];
+0764 for j_met=1:size(met_idx,1)
+0765     tmp_idx = met_idx(j_met,1);
+0766     sbml_tmp_species_ref.species = sbmlModel.species(tmp_idx).id;
+0767     met_stoich = model.S(tmp_idx, i);
+0768     sbml_tmp_species_ref.stoichiometry = abs(met_stoich);
+0769     sbml_tmp_species_ref.isSetStoichiometry=1;
+0770     sbml_tmp_species_ref.constant=1;
+0771     if (met_stoich > 0)
+0772         tmp_Rxn.product = [ tmp_Rxn.product, sbml_tmp_species_ref ];
+0773     else
+0774         tmp_Rxn.reactant = [ tmp_Rxn.reactant, sbml_tmp_species_ref];
+0775     end
+0776 end
+0777 end
+0778 
+0779 function vecT = columnVector(vec)
+0780 % Code below taken from COBRA Toolbox under GNU General Public License v3.0
+0781 % license file in readme/GPL.MD.
+0782 %
+0783 % Converts a vector to a column vector
+0784 %
+0785 % USAGE:
+0786 %
+0787 %   vecT = columnVector(vec)
+0788 %
+0789 % INPUT:
+0790 %   vec:     a vector
+0791 %
+0792 % OUTPUT:
+0793 %   vecT:    a column vector
+0794 
+0795 [n, m] = size(vec);
+0796 
+0797 if n < m
+0798     vecT = vec';
+0799 else
+0800     vecT = vec;
+0801 end
+0802 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/io/exportModelToSIF.html b/doc/io/exportModelToSIF.html new file mode 100644 index 000000000..191c50388 --- /dev/null +++ b/doc/io/exportModelToSIF.html @@ -0,0 +1,148 @@ + + + + Description of exportModelToSIF + + + + + + + + + +
Home > io > exportModelToSIF.m
+ + + +

exportModelToSIF +

+ +

PURPOSE ^

+
exportModelToSIF
+ +

SYNOPSIS ^

+
function exportModelToSIF(model,fileName,graphType,rxnLabels,metLabels)
+ +

DESCRIPTION ^

+
 exportModelToSIF
+   Exports a constraint-based model to a SIF file
+
+   model         a model structure
+   fileName      the filename  to export the model to
+   graphType     the type of graph to export to (optional, default 'rc')
+                 'rc'  reaction-compound
+                 'rr'  reaction-reaction
+                 'cc'  compound-compound
+   rxnLabels     cell array with labels for reactions (optional, default
+                 model.rxns)
+   metLabels     cell array with labels for metabolites (optional, default
+                 model.mets)
+
+ Usage: exportModelToSIF(model,fileName,graphType,rxnLabels,metLabels)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function exportModelToSIF(model,fileName,graphType,rxnLabels,metLabels)
+0002 % exportModelToSIF
+0003 %   Exports a constraint-based model to a SIF file
+0004 %
+0005 %   model         a model structure
+0006 %   fileName      the filename  to export the model to
+0007 %   graphType     the type of graph to export to (optional, default 'rc')
+0008 %                 'rc'  reaction-compound
+0009 %                 'rr'  reaction-reaction
+0010 %                 'cc'  compound-compound
+0011 %   rxnLabels     cell array with labels for reactions (optional, default
+0012 %                 model.rxns)
+0013 %   metLabels     cell array with labels for metabolites (optional, default
+0014 %                 model.mets)
+0015 %
+0016 % Usage: exportModelToSIF(model,fileName,graphType,rxnLabels,metLabels)
+0017 fileName=char(fileName);
+0018 if nargin<3
+0019     graphType='rc';
+0020 else
+0021     graphType=char(graphType);
+0022 end
+0023 
+0024 if nargin<4 || isempty(rxnLabels)
+0025     rxnLabels=model.rxns;
+0026 else
+0027     rxnLabels=convertCharArray(rxnLabels);
+0028 end
+0029 if nargin<5 || isempty(metLabels)
+0030     metLabels=model.mets;
+0031 else
+0032     metLabels=convertCharArray(metLabels);
+0033 end
+0034 
+0035 if ~strcmpi(graphType,'rc') && ~strcmpi(graphType,'rr') && ~strcmpi(graphType,'cc')
+0036     EM='The graph type is incorrect';
+0037     dispEM(EM);
+0038 end
+0039 
+0040 if numel(rxnLabels)~=numel(unique(rxnLabels))
+0041     EM='Not all reaction labels are unique';
+0042     dispEM(EM,false);
+0043 end
+0044 if numel(metLabels)~=numel(unique(metLabels))
+0045     EM='Not all metabolite labels are unique';
+0046     dispEM(EM,false);
+0047 end
+0048 
+0049 if strcmpi(graphType,'rc')
+0050     G=model.S;
+0051     A=rxnLabels;
+0052     B=metLabels;
+0053 end
+0054 if strcmpi(graphType,'rr')
+0055     G=model.S'*model.S;
+0056     A=rxnLabels;
+0057     B=rxnLabels;
+0058 end
+0059 if strcmpi(graphType,'cc')
+0060     %A metabolite is linked to all products of the reactions that it
+0061     %participates in If G=model.S*model.S' then all connections will be
+0062     %double, which looks weird
+0063     irrevModel=convertToIrrev(model);
+0064     G=sparse(numel(model.mets),numel(model.mets));
+0065     for i=1:numel(model.mets)
+0066         I=irrevModel.S(i,:)<0; %Get the reactions in which it is a substrate
+0067         [J, ~]=find(irrevModel.S(:,I)>0);
+0068         G(J,i)=1;
+0069     end
+0070     A=metLabels;
+0071     B=metLabels;
+0072 end
+0073 
+0074 fid=fopen(fileName,'w');
+0075 
+0076 for i=1:size(G,2)
+0077     I=G(:,i)~=0;
+0078     nodes=setdiff(B(I),A(i)); %Don't include connection to itself
+0079     if ~isempty(nodes)
+0080         nNodes=numel(nodes);
+0081         nodes(1:nNodes-1)=strcat(nodes(1:nNodes-1),{'\t'});
+0082         fullString=[nodes{:}];
+0083         fprintf(fid,[A{i} '\t' graphType '\t' fullString '\n']);
+0084     end
+0085 end
+0086 fclose(fid);
+0087 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/io/exportToExcelFormat.html b/doc/io/exportToExcelFormat.html new file mode 100644 index 000000000..72adbf32a --- /dev/null +++ b/doc/io/exportToExcelFormat.html @@ -0,0 +1,459 @@ + + + + Description of exportToExcelFormat + + + + + + + + + +
Home > io > exportToExcelFormat.m
+ + + +

exportToExcelFormat +

+ +

PURPOSE ^

+
exportToExcelFormat
+ +

SYNOPSIS ^

+
function exportToExcelFormat(model,fileName,sortIds)
+ +

DESCRIPTION ^

+
 exportToExcelFormat
+   Exports a model structure to the Microsoft Excel model format
+
+ Input:
+   model       a model structure
+   fileName    file name of the Excel file. Only xlsx format is supported.
+               In order to preserve backward compatibility this could also
+               be only a path, in which case the model is exported to a
+               set of tab-delimited text files via exportToTabDelimited.
+               A dialog window will open if fileName is empty.
+   sortIds     logical whether metabolites, reactions and genes should be
+               sorted alphabetically by their identifiers (optional,
+               default false)
+
+ Usage: exportToExcelFormat(model, fileName, sortIds)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function exportToExcelFormat(model,fileName,sortIds)
+0002 % exportToExcelFormat
+0003 %   Exports a model structure to the Microsoft Excel model format
+0004 %
+0005 % Input:
+0006 %   model       a model structure
+0007 %   fileName    file name of the Excel file. Only xlsx format is supported.
+0008 %               In order to preserve backward compatibility this could also
+0009 %               be only a path, in which case the model is exported to a
+0010 %               set of tab-delimited text files via exportToTabDelimited.
+0011 %               A dialog window will open if fileName is empty.
+0012 %   sortIds     logical whether metabolites, reactions and genes should be
+0013 %               sorted alphabetically by their identifiers (optional,
+0014 %               default false)
+0015 %
+0016 % Usage: exportToExcelFormat(model, fileName, sortIds)
+0017 
+0018 if nargin<2 || isempty(fileName)
+0019     [fileName, pathName] = uiputfile('*.xlsx', 'Select file for model export',[model.id '.xlsx']);
+0020     if fileName == 0
+0021         error('You should provide a file location')
+0022     else
+0023         fileName = fullfile(pathName,fileName);
+0024     end
+0025 end
+0026 fileName=char(fileName);
+0027 if nargin<3
+0028     sortIds=false;
+0029 end
+0030 if sortIds==true
+0031     model=sortIdentifiers(model);
+0032 end
+0033 
+0034 checkModelStruct(model);
+0035 
+0036 addList = matlab.addons.installedAddons;
+0037 if any(strcmpi(addList.Name,'Text Analytics Toolbox'))
+0038     error(['exportToExcelFormat is incompatible with MATLAB Text Analytics Toolbox. ' ...
+0039            'Further instructions => https://github.com/SysBioChalmers/RAVEN/issues/55#issuecomment-1514369299'])
+0040 end
+0041 
+0042 [~, A, B]=fileparts(fileName);
+0043 
+0044 %If a path was used call on exportToTabDelimited instead
+0045 if ~any(A) || ~any(B)
+0046     exportToTabDelimited(model,fileName);
+0047     return;
+0048 end
+0049 
+0050 if ~strcmpi(B,'.xlsx')
+0051     EM='As of RAVEN version 1.9, only export to xlsx format is supported';
+0052     dispEM(EM);
+0053 end
+0054 
+0055 import java.io.File;
+0056 import java.io.FileOutputStream;
+0057 import java.io.IOException;
+0058 
+0059 %Remove the output file if it already exists
+0060 if isfile(fileName)
+0061     delete(fileName);
+0062 end
+0063 
+0064 %Load an empty workbook
+0065 wb=loadWorkbook(fileName,true);
+0066 
+0067 %Construct equations
+0068 model.equations=constructEquations(model,model.rxns,true);
+0069 
+0070 %Check if it should print genes
+0071 if isfield(model,'grRules')
+0072     rules=model.grRules;
+0073 else
+0074     rules=[];
+0075 end
+0076 
+0077 %Check if the model has default upper/lower bounds. This determines if
+0078 %those values should be printed or not
+0079 hasDefaultLB=false;
+0080 hasDefaultUB=false;
+0081 if isfield(model,'annotation')
+0082     if isfield(model.annotation,'defaultLB')
+0083         hasDefaultLB=true;
+0084     end
+0085     if isfield(model.annotation,'defaultUB')
+0086         hasDefaultUB=true;
+0087     end
+0088 end
+0089 
+0090 %Add the RXNS sheet
+0091 
+0092 %Create the header row
+0093 headers={'#';'ID';'NAME';'EQUATION';'EC-NUMBER';'GENE ASSOCIATION';'LOWER BOUND';'UPPER BOUND';'OBJECTIVE';'COMPARTMENT';'MIRIAM';'SUBSYSTEM';'REPLACEMENT ID';'NOTE';'REFERENCE';'CONFIDENCE SCORE'};
+0094 
+0095 %Add empty comments
+0096 emptyColumn=cell(numel(model.rxns),1);
+0097 rxnSheet=emptyColumn;
+0098 
+0099 %Add the model fields
+0100 rxnSheet=[rxnSheet model.rxns];
+0101 
+0102 if isfield(model,'rxnNames')
+0103     rxnSheet=[rxnSheet model.rxnNames];
+0104 else
+0105     rxnSheet=[rxnSheet emptyColumn];
+0106 end
+0107 
+0108 rxnSheet=[rxnSheet model.equations];
+0109 
+0110 if isfield(model,'eccodes')
+0111     rxnSheet=[rxnSheet model.eccodes];
+0112 else
+0113     rxnSheet=[rxnSheet emptyColumn];
+0114 end
+0115 
+0116 if ~isempty(rules)
+0117     rxnSheet=[rxnSheet rules];
+0118 else
+0119     rxnSheet=[rxnSheet emptyColumn];
+0120 end
+0121 
+0122 lb=emptyColumn;
+0123 ub=emptyColumn;
+0124 objective=emptyColumn;
+0125 rxnMiriams=emptyColumn;
+0126 
+0127 for i=1:numel(model.rxns)
+0128     if isfield(model,'lb')
+0129         if hasDefaultLB==true
+0130             if model.rev(i)==1
+0131                 %If reversible, print only if different than defaultLB
+0132                 if model.lb(i) ~= model.annotation.defaultLB
+0133                     lb{i}=model.lb(i);
+0134                 end
+0135             else
+0136                 %If irreversible, print only for non-zero values
+0137                 if model.lb(i)~=0
+0138                     lb{i}=model.lb(i);
+0139                 end
+0140             end
+0141         else
+0142             lb{i}=model.lb(i);
+0143         end
+0144     end
+0145     
+0146     if isfield(model,'ub')
+0147         if hasDefaultUB==true
+0148             if model.ub(i) ~= model.annotation.defaultUB
+0149                 ub{i}=model.ub(i);
+0150             end
+0151         else
+0152             ub{i}=model.ub(i);
+0153         end
+0154     end
+0155     
+0156     if isfield(model,'c')
+0157         if model.c(i)~=0
+0158             objective{i}=model.c(i);
+0159         end
+0160     end
+0161     
+0162     if isfield(model,'rxnMiriams')
+0163         if ~isempty(model.rxnMiriams{i})
+0164             toPrint=[];
+0165             for j=1:numel(model.rxnMiriams{i}.name)
+0166                 toPrint=[toPrint strtrim(model.rxnMiriams{i}.name{j}) '/' strtrim(model.rxnMiriams{i}.value{j}) ';'];
+0167             end
+0168             rxnMiriams{i}=toPrint(1:end-1);
+0169         end
+0170     end
+0171 end
+0172 
+0173 rxnSheet=[rxnSheet lb];
+0174 rxnSheet=[rxnSheet ub];
+0175 rxnSheet=[rxnSheet objective];
+0176 
+0177 if isfield(model,'rxnComps')
+0178     rxnSheet=[rxnSheet model.comps(model.rxnComps)];
+0179 else
+0180     rxnSheet=[rxnSheet emptyColumn];
+0181 end
+0182 
+0183 rxnSheet=[rxnSheet rxnMiriams];
+0184 
+0185 subsystems='';
+0186 if isfield(model,'subSystems')
+0187     for i=1:numel(model.subSystems)
+0188         if ~iscell(model.subSystems{i})
+0189             model.subSystems{i} = {model.subSystems{i}};
+0190         end    
+0191         if ~isempty(model.subSystems{i,1})
+0192             subsystems{i,1}=strjoin(model.subSystems{i,1},';');
+0193         else
+0194             subsystems{i,1}='';
+0195         end
+0196     end
+0197     rxnSheet=[rxnSheet subsystems];
+0198 else
+0199     rxnSheet=[rxnSheet emptyColumn];
+0200 end
+0201 
+0202 %For REPLACEMENT ID which isn't in the model
+0203 rxnSheet=[rxnSheet emptyColumn];
+0204 
+0205 if isfield(model,'rxnNotes')
+0206     rxnSheet=[rxnSheet model.rxnNotes];
+0207 else
+0208     rxnSheet=[rxnSheet emptyColumn];
+0209 end
+0210 
+0211 if isfield(model,'rxnReferences')
+0212     rxnSheet=[rxnSheet model.rxnReferences];
+0213 else
+0214     rxnSheet=[rxnSheet emptyColumn];
+0215 end
+0216 
+0217 if isfield(model,'rxnConfidenceScores')
+0218     rxnSheet=[rxnSheet num2cell(model.rxnConfidenceScores)];
+0219 else
+0220     rxnSheet=[rxnSheet emptyColumn];
+0221 end
+0222 
+0223 wb=writeSheet(wb,'RXNS',0,headers,[],rxnSheet);
+0224 
+0225 headers={'#';'ID';'NAME';'UNCONSTRAINED';'MIRIAM';'COMPOSITION';'InChI';'COMPARTMENT';'REPLACEMENT ID';'CHARGE'};
+0226 
+0227 metSheet=cell(numel(model.mets),numel(headers));
+0228 
+0229 for i=1:numel(model.mets)
+0230     metSheet{i,2}=[model.metNames{i} '[' model.comps{model.metComps(i)} ']'];
+0231     
+0232     if isfield(model,'metNames')
+0233         metSheet(i,3)=model.metNames(i);
+0234     end
+0235     
+0236     if isfield(model,'unconstrained')
+0237         if model.unconstrained(i)~=0
+0238             metSheet{i,4}=true;
+0239         end
+0240     end
+0241     
+0242     if isfield(model,'metMiriams')
+0243         if ~isempty(model.metMiriams{i})
+0244             toPrint=[];
+0245             for j=1:numel(model.metMiriams{i}.name)
+0246                 toPrint=[toPrint strtrim(model.metMiriams{i}.name{j}) '/' strtrim(model.metMiriams{i}.value{j}) ';'];
+0247             end
+0248             metSheet{i,5}=toPrint(1:end-1);
+0249         end
+0250     end
+0251     
+0252     % Making sure that only these metFormulas are exported, which don't
+0253     % have InChI strings
+0254     if isfield(model,'metFormulas')
+0255         if isfield(model,'inchis')
+0256             if isempty(model.inchis{i})
+0257                 metSheet(i,6)=model.metFormulas(i);
+0258             end
+0259         else
+0260             metSheet(i,6)=model.metFormulas(i);
+0261         end
+0262     end
+0263     
+0264     if isfield(model,'inchis')
+0265         metSheet(i,7)=model.inchis(i);
+0266     end
+0267     
+0268     if isfield(model,'metComps')
+0269         metSheet(i,8)=model.comps(model.metComps(i));
+0270     end
+0271     
+0272     metSheet(i,9)=model.mets(i);
+0273     
+0274     if isfield(model,'metCharges')
+0275         metSheet{i,10}=model.metCharges(i);
+0276     end
+0277 end
+0278 
+0279 wb=writeSheet(wb,'METS',1,headers,[],metSheet);
+0280 
+0281 %Add the COMPS sheet
+0282 
+0283 %Create the header row
+0284 headers={'#';'ABBREVIATION';'NAME';'INSIDE';'MIRIAM'};
+0285 
+0286 compSheet=cell(numel(model.comps),numel(headers));
+0287 
+0288 for i=1:numel(model.comps)
+0289     compSheet(i,2)=model.comps(i);
+0290     
+0291     if isfield(model,'compNames')
+0292         compSheet(i,3)=model.compNames(i);
+0293     end
+0294     
+0295     if isfield(model,'compOutside')
+0296         compSheet(i,4)=model.compOutside(i);
+0297     end
+0298     
+0299     if isfield(model,'compMiriams')
+0300         if ~isempty(model.compMiriams{i})
+0301             toPrint=[];
+0302             for j=1:numel(model.compMiriams{i}.name)
+0303                 toPrint=[toPrint strtrim(model.compMiriams{i}.name{j}) '/' strtrim(model.compMiriams{i}.value{j}) ';'];
+0304             end
+0305             compSheet{i,5}=toPrint(1:end-1);
+0306         end
+0307     end
+0308 end
+0309 
+0310 wb=writeSheet(wb,'COMPS',2,headers,[],compSheet);
+0311 
+0312 %Add the GENES sheet
+0313 if isfield(model,'genes')
+0314     %Create the header row
+0315     headers={'#';'NAME';'MIRIAM';'SHORT NAME';'COMPARTMENT'};
+0316     
+0317     geneSheet=cell(numel(model.genes),numel(headers));
+0318     
+0319     for i=1:numel(model.genes)
+0320         geneSheet(i,2)=model.genes(i);
+0321         
+0322         if isfield(model,'geneMiriams')
+0323             if ~isempty(model.geneMiriams{i})
+0324                 toPrint=[];
+0325                 for j=1:numel(model.geneMiriams{i}.name)
+0326                     toPrint=[toPrint strtrim(model.geneMiriams{i}.name{j}) '/' strtrim(model.geneMiriams{i}.value{j}) ';'];
+0327                 end
+0328                 geneSheet{i,3}=toPrint(1:end-1);
+0329             end
+0330         end
+0331         if isfield(model,'geneShortNames')
+0332             geneSheet(i,4)=model.geneShortNames(i);
+0333         end
+0334         if isfield(model,'geneComps')
+0335             geneSheet(i,5)=model.comps(model.geneComps(i));
+0336         end
+0337     end
+0338     
+0339     wb=writeSheet(wb,'GENES',3,headers,[],geneSheet);
+0340 end
+0341 
+0342 %Add the MODEL sheet
+0343 
+0344 %Create the header row
+0345 headers={'#';'ID';'NAME';'TAXONOMY';'DEFAULT LOWER';'DEFAULT UPPER';'CONTACT GIVEN NAME';'CONTACT FAMILY NAME';'CONTACT EMAIL';'ORGANIZATION';'NOTES'};
+0346 
+0347 modelSheet=cell(1,numel(headers));
+0348 
+0349 if ~isfield(model,'annotation')
+0350     model.annotation = [];
+0351 end
+0352 
+0353 if isfield(model,'id')
+0354     modelSheet{1,2}=model.id;
+0355 else
+0356     modelSheet{1,2}='blankID';
+0357 end
+0358 if isfield(model,'name')
+0359     modelSheet{1,3}=model.name;
+0360 else
+0361     modelSheet{1,3}='blankName';
+0362 end
+0363 if isfield(model.annotation,'taxonomy')
+0364     modelSheet{1,4}=model.annotation.taxonomy;
+0365 end
+0366 if isfield(model.annotation,'defaultLB')
+0367     modelSheet{1,5}=model.annotation.defaultLB;
+0368 end
+0369 if isfield(model.annotation,'defaultUB')
+0370     modelSheet{1,6}=model.annotation.defaultUB;
+0371 end
+0372 if isfield(model.annotation,'givenName')
+0373     modelSheet{1,7}=model.annotation.givenName;
+0374 end
+0375 if isfield(model.annotation,'familyName')
+0376     modelSheet{1,8}=model.annotation.familyName;
+0377 end
+0378 if isfield(model.annotation,'email')
+0379     modelSheet{1,9}=model.annotation.email;
+0380 end
+0381 if isfield(model.annotation,'organization')
+0382     modelSheet{1,10}=model.annotation.organization;
+0383 end
+0384 if isfield(model.annotation,'note')
+0385     modelSheet{1,11}=model.annotation.note;
+0386 end
+0387 
+0388 if isfield(model,'genes')
+0389     wb=writeSheet(wb,'MODEL',4,headers,[],modelSheet);
+0390 else
+0391     wb=writeSheet(wb,'MODEL',3,headers,[],modelSheet);
+0392 end
+0393 
+0394 %Open the output stream
+0395 out = FileOutputStream(fileName);
+0396 wb.write(out);
+0397 out.close();
+0398 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/io/exportToTabDelimited.html b/doc/io/exportToTabDelimited.html new file mode 100644 index 000000000..11fe1e429 --- /dev/null +++ b/doc/io/exportToTabDelimited.html @@ -0,0 +1,407 @@ + + + + Description of exportToTabDelimited + + + + + + + + + +
Home > io > exportToTabDelimited.m
+ + + +

exportToTabDelimited +

+ +

PURPOSE ^

+
exportToTabDelimited
+ +

SYNOPSIS ^

+
function exportToTabDelimited(model,path,sortIds)
+ +

DESCRIPTION ^

+
 exportToTabDelimited
+   Exports a model structure to a set of tab-delimited text files
+
+   model    a model structure
+   path    the path to export to. The resulting text files will be saved
+           under the names excelRxns.txt, excelMets.txt, excelGenes.txt,
+           excelModel.txt, and excelComps.txt
+   sortIds logical whether metabolites, reactions and genes should be
+           sorted alphabetically by their identifiers (optional, default false)
+
+   NOTE: This functionality was previously a part of exportToExcelFormat.
+         The naming of the resulting text files is to preserve backward
+         compatibility
+
+   NOTE: No checks are made regarding the correctness of the model. Use
+         checkModelStruct to identify problems in the model structure
+
+ Usage: exportToTabDelimited(model,path,sortIds)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function exportToTabDelimited(model,path,sortIds)
+0002 % exportToTabDelimited
+0003 %   Exports a model structure to a set of tab-delimited text files
+0004 %
+0005 %   model    a model structure
+0006 %   path    the path to export to. The resulting text files will be saved
+0007 %           under the names excelRxns.txt, excelMets.txt, excelGenes.txt,
+0008 %           excelModel.txt, and excelComps.txt
+0009 %   sortIds logical whether metabolites, reactions and genes should be
+0010 %           sorted alphabetically by their identifiers (optional, default false)
+0011 %
+0012 %   NOTE: This functionality was previously a part of exportToExcelFormat.
+0013 %         The naming of the resulting text files is to preserve backward
+0014 %         compatibility
+0015 %
+0016 %   NOTE: No checks are made regarding the correctness of the model. Use
+0017 %         checkModelStruct to identify problems in the model structure
+0018 %
+0019 % Usage: exportToTabDelimited(model,path,sortIds)
+0020 
+0021 if nargin<2
+0022     path='./';
+0023 end
+0024 if nargin<3
+0025     sortIds=false;
+0026 end
+0027 if sortIds==true
+0028     model=sortIdentifiers(model);
+0029 end
+0030 
+0031 %If the folder doesn't exist then create it
+0032 if ~isfolder(path)
+0033     mkdir(path);
+0034 end
+0035 
+0036 %Remove the files if they already exist
+0037 if isfile(fullfile(path,'excelRxns.txt'))
+0038     delete(fullfile(path,'excelRxns.txt'));
+0039 end
+0040 if isfile(fullfile(path,'excelMets.txt'))
+0041     delete(fullfile(path,'excelMets.txt'));
+0042 end
+0043 if isfile(fullfile(path,'excelGenes.txt'))
+0044     delete(fullfile(path,'excelGenes.txt'));
+0045 end
+0046 if isfile(fullfile(path,'excelModel.txt'))
+0047     delete(fullfile(path,'excelModel.txt'));
+0048 end
+0049 if isfile(fullfile(path,'excelComps.txt'))
+0050     delete(fullfile(path,'excelComps.txt'));
+0051 end
+0052 
+0053 %Construct equations
+0054 model.equations=constructEquations(model,model.rxns,true);
+0055 
+0056 %Open for printing the rxn sheet
+0057 rxnFile=fopen(fullfile(path,'excelRxns.txt'),'wt');
+0058 
+0059 %Print header
+0060 fprintf(rxnFile,'#\tID\tNAME\tEQUATION\tEC-NUMBER\tGENE ASSOCIATION\tLOWER BOUND\tUPPER BOUND\tOBJECTIVE\tCOMPARTMENT\tMIRIAM\tSUBSYSTEM\tREPLACEMENT ID\tNOTE\tREFERENCE\tCONFIDENCE SCORE\n');
+0061 
+0062 %Loop through the reactions
+0063 for i=1:numel(model.rxns)
+0064     fprintf(rxnFile,['\t' model.rxns{i} '\t' model.rxnNames{i} '\t' model.equations{i} '\t']);
+0065     
+0066     if isfield(model,'eccodes')
+0067         fprintf(rxnFile,[model.eccodes{i} '\t']);
+0068     else
+0069         fprintf(rxnFile,'\t');
+0070     end
+0071     
+0072     if isfield(model,'grRules')
+0073         fprintf(rxnFile,[model.grRules{i} '\t']);
+0074     else
+0075         fprintf(rxnFile,'\t');
+0076     end
+0077     
+0078     %Print bounds and objectives
+0079     fprintf(rxnFile,[num2str(model.lb(i)) '\t' num2str(model.ub(i)) '\t']);
+0080     
+0081     if model.c(i)~=0
+0082         fprintf(rxnFile,[num2str(model.c(i)) '\t' ]);
+0083     else
+0084         fprintf(rxnFile,'\t');
+0085     end
+0086     
+0087     if isfield(model,'rxnComps')
+0088         fprintf(rxnFile,[model.comps{model.rxnComps(i)} '\t']);
+0089     else
+0090         fprintf(rxnFile,'\t');
+0091     end
+0092     
+0093     if isfield(model,'rxnMiriams')
+0094         if ~isempty(model.rxnMiriams{i})
+0095             toPrint=[];
+0096             for j=1:numel(model.rxnMiriams{i}.name)
+0097                 toPrint=[toPrint strtrim(model.rxnMiriams{i}.name{j}) '/' strtrim(model.rxnMiriams{i}.value{j}) ';'];
+0098             end
+0099             fprintf(rxnFile,[toPrint(1:end-1) '\t']);
+0100         else
+0101             fprintf(rxnFile,'\t');
+0102         end
+0103     else
+0104         fprintf(rxnFile,'\t');
+0105     end
+0106     
+0107     if isfield(model,'subSystems')
+0108         if ~isempty(model.subSystems{i})
+0109             if ~iscell(model.subSystems{i})
+0110                 model.subSystems{i} = {model.subSystems{i}};
+0111             end    
+0112             fprintf(rxnFile,[strjoin(model.subSystems{i,1},';') '\t']);
+0113         else
+0114             fprintf(rxnFile,'\t');
+0115         end
+0116     end
+0117     
+0118     %Print replacement IDs
+0119     fprintf(rxnFile,'\t');
+0120     
+0121     if isfield(model,'rxnNotes')
+0122         fprintf(rxnFile,[model.rxnNotes{i} '\t']);
+0123     else
+0124         fprintf(rxnFile,'\t');
+0125     end
+0126     
+0127     if isfield(model,'rxnReferences')
+0128         fprintf(rxnFile,[model.rxnReferences{i} '\t']);
+0129     else
+0130         fprintf(rxnFile,'\t');
+0131     end
+0132     
+0133     if isfield(model,'rxnConfidenceScores')
+0134         fprintf(rxnFile,[num2str(model.rxnConfidenceScores(i)) '\t' ]);
+0135     else
+0136         fprintf(rxnFile,'\t');
+0137     end
+0138     
+0139     fprintf(rxnFile,'\n');
+0140 end
+0141 
+0142 fclose(rxnFile);
+0143 
+0144 %Open for printing the metabolites sheet
+0145 metFile=fopen(fullfile(path,'excelMets.txt'),'wt');
+0146 
+0147 %Print header
+0148 fprintf(metFile,'#\tID\tNAME\tUNCONSTRAINED\tMIRIAM\tCOMPOSITION\tInChI\tCOMPARTMENT\tREPLACEMENT ID\tMETS FIELD\tCHARGE\n');
+0149 
+0150 %Loop through the metabolites
+0151 for i=1:numel(model.mets)
+0152     fprintf(metFile,['\t' model.metNames{i} '[' model.comps{model.metComps(i)} ']\t' model.metNames{i} '\t']);
+0153     
+0154     if isfield(model,'unconstrained')
+0155         if model.unconstrained(i)~=0
+0156             fprintf(metFile,'TRUE\t');
+0157         else
+0158             fprintf(metFile,'\t');
+0159         end
+0160     else
+0161         fprintf(metFile,'\t');
+0162     end
+0163     
+0164     if isfield(model,'metMiriams')
+0165         if ~isempty(model.metMiriams{i})
+0166             toPrint=[];
+0167             for j=1:numel(model.metMiriams{i}.name)
+0168                 toPrint=[toPrint strtrim(model.metMiriams{i}.name{j}) '/' strtrim(model.metMiriams{i}.value{j}) ';'];
+0169             end
+0170             fprintf(rxnFile,[toPrint(1:end-1) '\t']);
+0171         else
+0172             fprintf(metFile,'\t');
+0173         end
+0174     else
+0175         fprintf(metFile,'\t');
+0176     end
+0177     
+0178     if isfield(model,'metFormulas')
+0179         fprintf(metFile,[model.metFormulas{i} '\t']);
+0180     else
+0181         fprintf(metFile,'\t');
+0182     end
+0183     
+0184     if isfield(model,'inchis')
+0185         fprintf(metFile,[model.inchis{i} '\t']);
+0186     else
+0187         fprintf(metFile,'\t');
+0188     end
+0189     
+0190     fprintf(metFile,[model.comps{model.metComps(i)} '\t']);
+0191     
+0192     %There can be no replacement IDs in the structure, but it has to be
+0193     %something to give working met IDs.
+0194     fprintf(metFile,['m' int2str(i) '\t']);
+0195     
+0196     %Print the model.mets field. The reason for not putting this as
+0197     %replacement ID is that it's not guaranteed to be a valid SBML id.
+0198     fprintf(metFile,[model.mets{i} '\t']);
+0199     
+0200     if isfield(model,'metCharges')
+0201         fprintf(metFile,[num2str(model.metCharges(i)) '\t']);
+0202     else
+0203         fprintf(metFile,'\t');
+0204     end
+0205     
+0206     fprintf(metFile,'\n');
+0207 end
+0208 
+0209 fclose(metFile);
+0210 
+0211 if isfield(model,'genes')
+0212     %Open for printing the genes sheet
+0213     geneFile=fopen(fullfile(path,'excelGenes.txt'),'wt');
+0214     
+0215     %Print header
+0216     fprintf(geneFile,'#\tNAME\tMIRIAM\tSHORT NAME\tCOMPARTMENT\n');
+0217     
+0218     %Loop through the genes
+0219     for i=1:numel(model.genes)
+0220         fprintf(geneFile,['\t' model.genes{i} '\t']);
+0221         
+0222         if isfield(model,'geneMiriams')
+0223             if ~isempty(model.geneMiriams{i})
+0224                 toPrint=[];
+0225                 for j=1:numel(model.geneMiriams{i}.name)
+0226                     toPrint=[toPrint strtrim(model.geneMiriams{i}.name{j}) '/' strtrim(model.geneMiriams{i}.value{j}) ';'];
+0227                 end
+0228                 fprintf(geneFile,[toPrint(1:end-1) '\t']);
+0229             else
+0230                 fprintf(geneFile,'\t');
+0231             end
+0232         else
+0233             fprintf(geneFile,'\t');
+0234         end
+0235         
+0236         if isfield(model,'geneShortNames')
+0237             fprintf(geneFile,[model.geneShortNames{i} '\t']);
+0238         else
+0239             fprintf(geneFile,'\t');
+0240         end
+0241         
+0242         if isfield(model,'geneComps')
+0243             fprintf(geneFile,[model.comps{model.geneComps(i)} '\t']);
+0244         else
+0245             fprintf(geneFile,'\t');
+0246         end
+0247         
+0248         fprintf(geneFile,'\n');
+0249     end
+0250     fclose(geneFile);
+0251 end
+0252 
+0253 if isfield(model,'id')
+0254     %Open for printing the model sheet
+0255     modelFile=fopen(fullfile(path,'excelModel.txt'),'wt');
+0256     
+0257     %Print header
+0258     fprintf(geneFile,'#\tID\tNAME\tDEFAULT LOWER\tDEFAULT UPPER\tCONTACT GIVEN NAME\tCONTACT FAMILY NAME\tCONTACT EMAIL\tORGANIZATION\tTAXONOMY\tNOTES\n');
+0259     
+0260     %Print model ID and name. It is assumed that the default lower/upper
+0261     %bound correspond to min/max of the bounds
+0262     toPrint=['\t' model.id '\t' model.name '\t'];
+0263     if isfield(model,'annotation')
+0264         if isfield(model.annotation,'defaultLB')
+0265             toPrint=[toPrint num2str(model.annotation.defaultLB) '\t'];
+0266         else
+0267             toPrint=[toPrint num2str(min(model.lb)) '\t'];
+0268         end
+0269         if isfield(model.annotation,'defaultUB')
+0270             toPrint=[toPrint num2str(model.annotation.defaultUB) '\t'];
+0271         else
+0272             toPrint=[toPrint num2str(max(model.ub)) '\t'];
+0273         end
+0274         if isfield(model.annotation,'givenName')
+0275             toPrint=[toPrint model.annotation.givenName '\t'];
+0276         else
+0277             toPrint=[toPrint '\t'];
+0278         end
+0279         if isfield(model.annotation,'familyName')
+0280             toPrint=[toPrint model.annotation.familyName '\t'];
+0281         else
+0282             toPrint=[toPrint '\t'];
+0283         end
+0284         if isfield(model.annotation,'email')
+0285             toPrint=[toPrint model.annotation.email '\t'];
+0286         else
+0287             toPrint=[toPrint '\t'];
+0288         end
+0289         if isfield(model.annotation,'organization')
+0290             toPrint=[toPrint model.annotation.organization '\t'];
+0291         else
+0292             toPrint=[toPrint '\t'];
+0293         end
+0294         if isfield(model.annotation,'taxonomy')
+0295             toPrint=[toPrint model.annotation.taxonomy '\t'];
+0296         else
+0297             toPrint=[toPrint '\t'];
+0298         end
+0299         if isfield(model.annotation,'note')
+0300             toPrint=[toPrint model.annotation.note '\t'];
+0301         else
+0302             toPrint=[toPrint '\t'];
+0303         end
+0304     else
+0305         toPrint=[toPrint num2str(min(model.lb)) '\t' num2str(max(model.ub)) '\t\t\t\t\t\t\n'];
+0306     end
+0307     fprintf(modelFile,toPrint);
+0308     fclose(modelFile);
+0309 end
+0310 
+0311 if isfield(model,'comps')
+0312     %Open for printing the model sheet
+0313     compsFile=fopen(fullfile(path,'excelComps.txt'),'wt');
+0314     
+0315     %Print header
+0316     fprintf(compsFile,'#\tABBREVIATION\tNAME\tINSIDE\tMIRIAM\n');
+0317     
+0318     for i=1:numel(model.comps)
+0319         toPrint=['\t' model.comps{i} '\t' model.compNames{i} '\t'];
+0320         if isfield(model,'compOutside')
+0321             toPrint=[toPrint model.compOutside{i} '\t'];
+0322         else
+0323             toPrint=[toPrint '\t'];
+0324         end
+0325         if isfield(model,'compMiriams')
+0326             if ~isempty(model.compMiriams{i})
+0327                 for j=1:numel(model.compMiriams{i}.name)
+0328                     toPrint=[toPrint strtrim(model.compMiriams{i}.name{j}) '/' strtrim(model.compMiriams{i}.value{j}) ';'];
+0329                 end
+0330                 toPrint(end)=[];
+0331                 toPrint=[toPrint '\t'];
+0332             else
+0333                 toPrint=[toPrint '\t'];
+0334             end
+0335         else
+0336             toPrint=[toPrint '\t'];
+0337         end
+0338         toPrint=[toPrint '\n'];
+0339         fprintf(compsFile,toPrint);
+0340     end
+0341     fclose(compsFile);
+0342 end
+0343 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/io/getFullPath.html b/doc/io/getFullPath.html new file mode 100644 index 000000000..63e4a39b0 --- /dev/null +++ b/doc/io/getFullPath.html @@ -0,0 +1,439 @@ + + + + Description of getFullPath + + + + + + + + + +
Home > io > getFullPath.m
+ + + +

getFullPath +

+ +

PURPOSE ^

+
getFullPath - Get absolute canonical path of a file or folder
+ +

SYNOPSIS ^

+
function File = getFullPath(File, Style)
+ +

DESCRIPTION ^

+
 getFullPath - Get absolute canonical path of a file or folder
+ Absolute path names are safer than relative paths, when e.g. a GUI or TIMER
+ callback changes the current directory. Only canonical paths without "." and
+ ".." can be recognized uniquely.
+ Long path names (>259 characters) require a magic initial key "\\?\" to be
+ handled by Windows API functions, e.g. for Matlab's FOPEN, DIR and EXIST.
+
+ FullName = getFullPath(Name, Style)
+ INPUT:
+   Name:  String or cell string, absolute or relative name of a file or
+          folder. The path need not exist. Unicode strings, UNC paths and long
+          names are supported.
+   Style: Style of the output as string, optional, default: 'auto'.
+          'auto': Add '\\?\' or '\\?\UNC\' for long names on demand.
+          'lean': Magic string is not added.
+          'fat':  Magic string is added for short names also.
+          The Style is ignored when not running under Windows.
+
+ OUTPUT:
+   FullName: Absolute canonical path name as string or cell string.
+          For empty strings the current directory is replied.
+          '\\?\' or '\\?\UNC' is added on demand.
+
+ NOTE: The M- and the MEX-version create the same results, the faster MEX
+   function works under Windows only.
+   Some functions of the Windows-API still do not support long file names.
+   E.g. the Recycler and the Windows Explorer fail even with the magic '\\?\'
+   prefix. Some functions of Matlab accept 260 characters (value of MAX_PATH),
+   some at 259 already. Don't blame me.
+   The 'fat' style is useful e.g. when Matlab's DIR command is called for a
+   folder with les than 260 characters, but together with the file name this
+   limit is exceeded. Then "dir(getFullPath([folder, '\*.*], 'fat'))" helps.
+
+ EXAMPLES:
+   cd(tempdir);                    % Assumed as 'C:\Temp' here
+   getFullPath('File.Ext')         % 'C:\Temp\File.Ext'
+   getFullPath('..\File.Ext')      % 'C:\File.Ext'
+   getFullPath('..\..\File.Ext')   % 'C:\File.Ext'
+   getFullPath('.\File.Ext')       % 'C:\Temp\File.Ext'
+   getFullPath('*.txt')            % 'C:\Temp\*.txt'
+   getFullPath('..')               % 'C:\'
+   getFullPath('..\..\..')         % 'C:\'
+   getFullPath('Folder\')          % 'C:\Temp\Folder\'
+   getFullPath('D:\A\..\B')        % 'D:\B'
+   getFullPath('\\Server\Folder\Sub\..\File.ext')
+                                   % '\\Server\Folder\File.ext'
+   getFullPath({'..', 'new'})      % {'C:\', 'C:\Temp\new'}
+   getFullPath('.', 'fat')         % '\\?\C:\Temp\File.Ext'
+
+ COMPILE:
+   Automatic: InstallMex getFullPath.c uTest_getFullPath
+   Manual:    mex -O getFullPath.c
+   Download:  http://www.n-simon.de/mex
+ Run the unit-test uTest_getFullPath after compiling.
+
+ Tested: Matlab 6.5, 7.7, 7.8, 7.13, WinXP/32, Win7/64
+         Compiler: LCC2.4/3.8, BCC5.5, OWC1.8, MSVC2008/2010
+ Assumed Compatibility: higher Matlab versions
+ Author: Jan Simon, Heidelberg, (C) 2009-2013 matlab.THISYEAR(a)nMINUSsimon.de
+
+ See also: CD, FULLFILE, FILEPARTS.
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
  • getFullPath getFullPath - Get absolute canonical path of a file or folder
+This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function File = getFullPath(File, Style)
+0002 % getFullPath - Get absolute canonical path of a file or folder
+0003 % Absolute path names are safer than relative paths, when e.g. a GUI or TIMER
+0004 % callback changes the current directory. Only canonical paths without "." and
+0005 % ".." can be recognized uniquely.
+0006 % Long path names (>259 characters) require a magic initial key "\\?\" to be
+0007 % handled by Windows API functions, e.g. for Matlab's FOPEN, DIR and EXIST.
+0008 %
+0009 % FullName = getFullPath(Name, Style)
+0010 % INPUT:
+0011 %   Name:  String or cell string, absolute or relative name of a file or
+0012 %          folder. The path need not exist. Unicode strings, UNC paths and long
+0013 %          names are supported.
+0014 %   Style: Style of the output as string, optional, default: 'auto'.
+0015 %          'auto': Add '\\?\' or '\\?\UNC\' for long names on demand.
+0016 %          'lean': Magic string is not added.
+0017 %          'fat':  Magic string is added for short names also.
+0018 %          The Style is ignored when not running under Windows.
+0019 %
+0020 % OUTPUT:
+0021 %   FullName: Absolute canonical path name as string or cell string.
+0022 %          For empty strings the current directory is replied.
+0023 %          '\\?\' or '\\?\UNC' is added on demand.
+0024 %
+0025 % NOTE: The M- and the MEX-version create the same results, the faster MEX
+0026 %   function works under Windows only.
+0027 %   Some functions of the Windows-API still do not support long file names.
+0028 %   E.g. the Recycler and the Windows Explorer fail even with the magic '\\?\'
+0029 %   prefix. Some functions of Matlab accept 260 characters (value of MAX_PATH),
+0030 %   some at 259 already. Don't blame me.
+0031 %   The 'fat' style is useful e.g. when Matlab's DIR command is called for a
+0032 %   folder with les than 260 characters, but together with the file name this
+0033 %   limit is exceeded. Then "dir(getFullPath([folder, '\*.*], 'fat'))" helps.
+0034 %
+0035 % EXAMPLES:
+0036 %   cd(tempdir);                    % Assumed as 'C:\Temp' here
+0037 %   getFullPath('File.Ext')         % 'C:\Temp\File.Ext'
+0038 %   getFullPath('..\File.Ext')      % 'C:\File.Ext'
+0039 %   getFullPath('..\..\File.Ext')   % 'C:\File.Ext'
+0040 %   getFullPath('.\File.Ext')       % 'C:\Temp\File.Ext'
+0041 %   getFullPath('*.txt')            % 'C:\Temp\*.txt'
+0042 %   getFullPath('..')               % 'C:\'
+0043 %   getFullPath('..\..\..')         % 'C:\'
+0044 %   getFullPath('Folder\')          % 'C:\Temp\Folder\'
+0045 %   getFullPath('D:\A\..\B')        % 'D:\B'
+0046 %   getFullPath('\\Server\Folder\Sub\..\File.ext')
+0047 %                                   % '\\Server\Folder\File.ext'
+0048 %   getFullPath({'..', 'new'})      % {'C:\', 'C:\Temp\new'}
+0049 %   getFullPath('.', 'fat')         % '\\?\C:\Temp\File.Ext'
+0050 %
+0051 % COMPILE:
+0052 %   Automatic: InstallMex getFullPath.c uTest_getFullPath
+0053 %   Manual:    mex -O getFullPath.c
+0054 %   Download:  http://www.n-simon.de/mex
+0055 % Run the unit-test uTest_getFullPath after compiling.
+0056 %
+0057 % Tested: Matlab 6.5, 7.7, 7.8, 7.13, WinXP/32, Win7/64
+0058 %         Compiler: LCC2.4/3.8, BCC5.5, OWC1.8, MSVC2008/2010
+0059 % Assumed Compatibility: higher Matlab versions
+0060 % Author: Jan Simon, Heidelberg, (C) 2009-2013 matlab.THISYEAR(a)nMINUSsimon.de
+0061 %
+0062 % See also: CD, FULLFILE, FILEPARTS.
+0063 
+0064 % $JRev: R-G V:032 Sum:7Xd/JS0+yfax Date:15-Jan-2013 01:06:12 $
+0065 % $License: BSD (use/copy/change/redistribute on own risk, mention the author) $
+0066 % $UnitTest: uTest_getFullPath $
+0067 % $File: Tools\GLFile\getFullPath.m $
+0068 % History:
+0069 % 001: 20-Apr-2010 22:28, Successor of Rel2AbsPath.
+0070 % 010: 27-Jul-2008 21:59, Consider leading separator in M-version also.
+0071 % 011: 24-Jan-2011 12:11, Cell strings, '~File' under linux.
+0072 %      Check of input types in the M-version.
+0073 % 015: 31-Mar-2011 10:48, BUGFIX: Accept [] as input as in the Mex version.
+0074 %      Thanks to Jiro Doke, who found this bug by running the test function for
+0075 %      the M-version.
+0076 % 020: 18-Oct-2011 00:57, BUGFIX: Linux version created bad results.
+0077 %      Thanks to Daniel.
+0078 % 024: 10-Dec-2011 14:00, Care for long names under Windows in M-version.
+0079 %      Improved the unittest function for Linux. Thanks to Paul Sexton.
+0080 % 025: 09-Aug-2012 14:00, In MEX: Paths starting with "\\" can be non-UNC.
+0081 %      The former version treated "\\?\C:\<longpath>\file" as UNC path and
+0082 %      replied "\\?\UNC\?\C:\<longpath>\file".
+0083 % 032: 12-Jan-2013 21:16, 'auto', 'lean' and 'fat' style.
+0084 
+0085 % Initialize: ==================================================================
+0086 % Do the work: =================================================================
+0087 
+0088 % #############################################
+0089 % ### USE THE MUCH FASTER MEX ON WINDOWS!!! ###
+0090 % #############################################
+0091 
+0092 % Difference between M- and Mex-version:
+0093 % - Mex does not work under MacOS/Unix.
+0094 % - Mex calls Windows API function getFullPath.
+0095 % - Mex is much faster.
+0096 
+0097 % Magix prefix for long Windows names:
+0098 if nargin < 2
+0099     Style = 'auto';
+0100 end
+0101 
+0102 % Handle cell strings: NOTE: It is faster to create a function
+0103 % @cell\getFullPath.m under Linux, but under Windows this would shadow the
+0104 % fast C-Mex.
+0105 if isa(File, 'cell')
+0106     for iC = 1:numel(File)
+0107         File{iC} = getFullPath(File{iC}, Style);
+0108     end
+0109     return;
+0110 end
+0111 
+0112 % Check this once only:
+0113 isWIN    = strncmpi(computer, 'PC', 2);
+0114 MAX_PATH = 260;
+0115 
+0116 % Warn once per session (disable this under Linux/MacOS):
+0117 persistent hasDataRead
+0118 if isempty(hasDataRead)
+0119     % Test this once only - there is no relation to the existence of
+0120     % DATAREAD!
+0121     %if isWIN
+0122     %   Show a warning, if the slower Matlab version is used - commented,
+0123     %   because this is not a problem and it might be even useful when the
+0124     %   MEX-folder is not inlcuded in the path yet.
+0125     %   warning('JSimon:getFullPath:NoMex', ...
+0126     %      ['getFullPath: Using slow Matlab-version instead of fast Mex.',
+0127     %      ...
+0128     %       char(10), 'Compile: InstallMex getFullPath.c']);
+0129     %end
+0130     
+0131     % DATAREAD is deprecated in 2011b, but still available. In Matlab 6.5,
+0132     % REGEXP does not know the 'split' command, therefore DATAREAD is
+0133     % preferred:
+0134     hasDataRead = ~isempty(which('dataread'));
+0135 end
+0136 
+0137 if isempty(File)  % Accept empty matrix as input:
+0138     if ischar(File) || isnumeric(File)
+0139         File = cd;
+0140         return;
+0141     else
+0142         error(['JSimon:', mfilename, ':BadTypeInput1'], ...
+0143             ['*** ', mfilename, ': Input must be a string or cell string']);
+0144     end
+0145 end
+0146 
+0147 if ischar(File) == 0  % Non-empty inputs must be strings
+0148     error(['JSimon:', mfilename, ':BadTypeInput1'], ...
+0149         ['*** ', mfilename, ': Input must be a string or cell string']);
+0150 end
+0151 
+0152 if isWIN  % Windows: --------------------------------------------------------
+0153     FSep = '\';
+0154     File = strrep(File, '/', FSep);
+0155     
+0156     % Remove the magic key on demand, it is appended finally again:
+0157     if strncmp(File, '\\?\', 4)
+0158         if strncmpi(File, '\\?\UNC\', 8)
+0159             File = ['\', File(7:length(File))];  % Two leading backslashes!
+0160         else
+0161             File = File(5:length(File));
+0162         end
+0163     end
+0164     
+0165     isUNC   = strncmp(File, '\\', 2);
+0166     FileLen = length(File);
+0167     if isUNC == 0                        % File is not a UNC path
+0168         % Leading file separator means relative to current drive or base
+0169         % folder:
+0170         ThePath = cd;
+0171         if File(1) == FSep
+0172             if strncmp(ThePath, '\\', 2)   % Current directory is a UNC path
+0173                 sepInd  = strfind(ThePath, '\');
+0174                 ThePath = ThePath(1:sepInd(4));
+0175             else
+0176                 ThePath = ThePath(1:3);     % Drive letter only
+0177             end
+0178         end
+0179         
+0180         if FileLen < 2 || File(2) ~= ':'  % Does not start with drive letter
+0181             if ThePath(length(ThePath)) ~= FSep
+0182                 if File(1) ~= FSep
+0183                     File = [ThePath, FSep, File];
+0184                 else                        % File starts with separator:
+0185                     File = [ThePath, File];
+0186                 end
+0187             else                           % Current path ends with separator:
+0188                 if File(1) ~= FSep
+0189                     File = [ThePath, File];
+0190                 else                        % File starts with separator:
+0191                     ThePath(length(ThePath)) = [];
+0192                     File = [ThePath, File];
+0193                 end
+0194             end
+0195             
+0196         elseif FileLen == 2 && File(2) == ':'   % "C:" current directory on C!
+0197             % "C:" is the current directory on the C-disk, even if the
+0198             % current directory is on another disk! This was ignored in
+0199             % Matlab 6.5, but modern versions considers this strange
+0200             % behaviour.
+0201             if strncmpi(ThePath, File, 2)
+0202                 File = ThePath;
+0203             else
+0204                 try
+0205                     File = cd(cd(File));
+0206                 catch    % No MException to support Matlab6.5...
+0207                     if exist(File, 'dir')  % No idea what could cause an error then!
+0208                         rethrow(lasterror);
+0209                     else  % Reply "K:\" for not existing disk:
+0210                         File = [File, FSep];
+0211                     end
+0212                 end
+0213             end
+0214         end
+0215     end
+0216     
+0217 else         % Linux, MacOS: ---------------------------------------------------
+0218     FSep = '/';
+0219     File = strrep(File, '\', FSep);
+0220     
+0221     if strcmp(File, '~') || strncmp(File, '~/', 2)  % Home directory:
+0222         HomeDir = getenv('HOME');
+0223         if ~isempty(HomeDir)
+0224             File(1) = [];
+0225             File    = [HomeDir, File];
+0226         end
+0227         
+0228     elseif strncmpi(File, FSep, 1) == 0
+0229         % Append relative path to current folder:
+0230         ThePath = cd;
+0231         if ThePath(length(ThePath)) == FSep
+0232             File = [ThePath, File];
+0233         else
+0234             File = [ThePath, FSep, File];
+0235         end
+0236     end
+0237 end
+0238 
+0239 % Care for "\." and "\.." - no efficient algorithm, but the fast Mex is
+0240 % recommended at all!
+0241 if ~isempty(strfind(File, [FSep, '.']))
+0242     if isWIN
+0243         if strncmp(File, '\\', 2)  % UNC path
+0244             index = strfind(File, '\');
+0245             if length(index) < 4    % UNC path without separator after the folder:
+0246                 return;
+0247             end
+0248             Drive            = File(1:index(4));
+0249             File(1:index(4)) = [];
+0250         else
+0251             Drive     = File(1:3);
+0252             File(1:3) = [];
+0253         end
+0254     else  % Unix, MacOS:
+0255         isUNC   = false;
+0256         Drive   = FSep;
+0257         File(1) = [];
+0258     end
+0259     
+0260     hasTrailFSep = (File(length(File)) == FSep);
+0261     if hasTrailFSep
+0262         File(length(File)) = [];
+0263     end
+0264     
+0265     if hasDataRead
+0266         if isWIN  % Need "\\" as separator:
+0267             C = dataread('string', File, '%s', 'delimiter', '\\');  %#ok<REMFF1>
+0268         else
+0269             C = dataread('string', File, '%s', 'delimiter', FSep);  %#ok<REMFF1>
+0270         end
+0271     else  % Use the slower REGEXP, when DATAREAD is not available anymore:
+0272         C = regexp(File, FSep, 'split');
+0273     end
+0274     
+0275     % Remove '\.\' directly without side effects:
+0276     C(strcmp(C, '.')) = [];
+0277     
+0278     % Remove '\..' with the parent recursively:
+0279     R = 1:length(C);
+0280     for dd = reshape(find(strcmp(C, '..')), 1, [])
+0281         index    = find(R == dd);
+0282         R(index) = [];
+0283         if index > 1
+0284             R(index - 1) = [];
+0285         end
+0286     end
+0287     
+0288     if isempty(R)
+0289         File = Drive;
+0290         if isUNC && ~hasTrailFSep
+0291             File(length(File)) = [];
+0292         end
+0293         
+0294     elseif isWIN
+0295         % If you have CStr2String, use the faster:
+0296         %   File = CStr2String(C(R), FSep, hasTrailFSep);
+0297         File = sprintf('%s\\', C{R});
+0298         if hasTrailFSep
+0299             File = [Drive, File];
+0300         else
+0301             File = [Drive, File(1:length(File) - 1)];
+0302         end
+0303         
+0304     else  % Unix:
+0305         File = [Drive, sprintf('%s/', C{R})];
+0306         if ~hasTrailFSep
+0307             File(length(File)) = [];
+0308         end
+0309     end
+0310 end
+0311 
+0312 % "Very" long names under Windows:
+0313 if isWIN
+0314     if ~ischar(Style)
+0315         error(['JSimon:', mfilename, ':BadTypeInput2'], ...
+0316             ['*** ', mfilename, ': Input must be a string or cell string']);
+0317     end
+0318     
+0319     if (strncmpi(Style, 'a', 1) && length(File) >= MAX_PATH) || ...
+0320             strncmpi(Style, 'f', 1)
+0321         % Do not use [isUNC] here, because this concerns the input, which
+0322         % can '.\File', while the current directory is an UNC path.
+0323         if strncmp(File, '\\', 2)  % UNC path
+0324             File = ['\\?\UNC', File(2:end)];
+0325         else
+0326             File = ['\\?\', File];
+0327         end
+0328     end
+0329 end
+0330 
+0331 % return;
+0332 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/io/getMD5Hash.html b/doc/io/getMD5Hash.html new file mode 100644 index 000000000..ee3b856b2 --- /dev/null +++ b/doc/io/getMD5Hash.html @@ -0,0 +1,118 @@ + + + + Description of getMD5Hash + + + + + + + + + +
Home > io > getMD5Hash.m
+ + + +

getMD5Hash +

+ +

PURPOSE ^

+
getMD5Hash
+ +

SYNOPSIS ^

+
function md5Hash=getMD5Hash(inputFile,binEnd)
+ +

DESCRIPTION ^

+
 getMD5Hash
+   Calculates MD5 hash for a file
+
+   Input:
+   inputFile       string with the path to file for which MD5 hash should
+                   be calculated
+   binEnd          string that shows the operating system running in the
+                   client's computer. Use ".exe" for Windows, ".mac" for
+                   macOS or leave it blank for Linux (""). (optional, by
+                   default the function automatically detects the client's
+                   operating system)
+
+   Output:
+   md5Hash         string containing an MD5 hash for inputFile
+   
+ Usage: md5Hash=getMD5Hash(inputFile,binEnd)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function md5Hash=getMD5Hash(inputFile,binEnd)
+0002 % getMD5Hash
+0003 %   Calculates MD5 hash for a file
+0004 %
+0005 %   Input:
+0006 %   inputFile       string with the path to file for which MD5 hash should
+0007 %                   be calculated
+0008 %   binEnd          string that shows the operating system running in the
+0009 %                   client's computer. Use ".exe" for Windows, ".mac" for
+0010 %                   macOS or leave it blank for Linux (""). (optional, by
+0011 %                   default the function automatically detects the client's
+0012 %                   operating system)
+0013 %
+0014 %   Output:
+0015 %   md5Hash         string containing an MD5 hash for inputFile
+0016 %
+0017 % Usage: md5Hash=getMD5Hash(inputFile,binEnd)
+0018 inputFile=char(inputFile);
+0019 
+0020 if nargin<2
+0021     if isunix
+0022         if ismac
+0023             binEnd='.mac';
+0024         else
+0025             binEnd='';
+0026         end
+0027     elseif ispc
+0028         binEnd='.exe';
+0029     else
+0030         error('Unknown OS, exiting.')
+0031     end
+0032 else
+0033     binEnd=char(binEnd);
+0034 end
+0035 
+0036 %Check if binEnd is valid
+0037 if ~any(strcmp(binEnd,{'.mac','','.exe'}))
+0038    error('Unknown OS, exiting.')
+0039 end
+0040 
+0041 %Check file existence
+0042 inputFile=checkFileExistence(inputFile);
+0043 
+0044 %Get string containing an MD5 hash
+0045 switch binEnd
+0046     case '.mac'
+0047         [~, md5HashMessage]=system(['md5 "' inputFile '"']);
+0048     case ''
+0049         [~, md5HashMessage]=system(['md5sum "' inputFile '"']);
+0050     case '.exe'
+0051         [~, md5HashMessage]=system(['certutil -hashfile "' inputFile '" MD5"']);
+0052 end
+0053 
+0054 %Extract MD5 hash from a string
+0055 md5Hash = char(regexp(md5HashMessage,'[a-f0-9]{32}','match'));
+0056 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/io/getToolboxVersion.html b/doc/io/getToolboxVersion.html new file mode 100644 index 000000000..54e1744bc --- /dev/null +++ b/doc/io/getToolboxVersion.html @@ -0,0 +1,146 @@ + + + + Description of getToolboxVersion + + + + + + + + + +
Home > io > getToolboxVersion.m
+ + + +

getToolboxVersion +

+ +

PURPOSE ^

+
getToolboxVersion
+ +

SYNOPSIS ^

+
function version = getToolboxVersion(toolbox,fileID,mainBranchFlag)
+ +

DESCRIPTION ^

+
 getToolboxVersion
+   Returns the version of a given toolbox, or if not available the latest
+   commit hash (7 characters).
+
+   toolbox         string with the toolbox name (e.g. "RAVEN")
+   fileID          string with the name of a file that is only found in
+                   the corresponding toolbox (e.g. "ravenCobraWrapper.m").
+   mainBranchFlag  logical, if true, function will error if the toolbox is
+                   not on the main branch (optional, default false).
+
+   version         string containing either the toolbox version or latest
+                   commit hash (7 characters).
+
+ Usage: version = getToolboxVersion(toolbox,fileID,mainBranchFlag)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 function version = getToolboxVersion(toolbox,fileID,mainBranchFlag)
+0002 % getToolboxVersion
+0003 %   Returns the version of a given toolbox, or if not available the latest
+0004 %   commit hash (7 characters).
+0005 %
+0006 %   toolbox         string with the toolbox name (e.g. "RAVEN")
+0007 %   fileID          string with the name of a file that is only found in
+0008 %                   the corresponding toolbox (e.g. "ravenCobraWrapper.m").
+0009 %   mainBranchFlag  logical, if true, function will error if the toolbox is
+0010 %                   not on the main branch (optional, default false).
+0011 %
+0012 %   version         string containing either the toolbox version or latest
+0013 %                   commit hash (7 characters).
+0014 %
+0015 % Usage: version = getToolboxVersion(toolbox,fileID,mainBranchFlag)
+0016 toolbox=char(toolbox);
+0017 fileID=char(fileID);
+0018 
+0019 if nargin<3
+0020     mainBranchFlag = false;
+0021 end
+0022 
+0023 currentPath = pwd;
+0024 version     = '';
+0025 
+0026 %Try to find root of toolbox:
+0027 try
+0028     toolboxPath = which(fileID);                %full file path
+0029     slashPos    = getSlashPos(toolboxPath);
+0030     toolboxPath = toolboxPath(1:slashPos(end)); %folder path
+0031     %Go up until the root is found:
+0032     D = dir(toolboxPath);
+0033     while ~ismember({'.git'},{D.name})
+0034         slashPos    = getSlashPos(toolboxPath);
+0035         toolboxPath = toolboxPath(1:slashPos(end-1));
+0036         D           = dir(toolboxPath);
+0037     end
+0038     cd(toolboxPath);
+0039 catch
+0040     disp([toolbox ' toolbox cannot be found'])
+0041     version = 'unknown';
+0042 end
+0043 %Check if in main:
+0044 if mainBranchFlag
+0045     [~,currentBranch] = system('git rev-parse --abbrev-ref HEAD');
+0046     currentBranch = strtrim(currentBranch);
+0047     if any([strcmp(currentBranch, "main"), strcmp(currentBranch, "master")])
+0048         cd(currentPath);
+0049         error(['ERROR: ' toolbox ' not in main (or master) branch. Check-out this branch of ' toolbox ' before submitting model for Git.'])
+0050     end
+0051 end
+0052 %Try to find version file of the toolbox:
+0053 if isempty(version)
+0054     try
+0055         fid     = fopen([toolboxPath 'version.txt'],'r');
+0056         version = fscanf(fid,'%s');
+0057         fclose(fid);
+0058     catch
+0059         %If no file available, look up the tag:
+0060         try
+0061             [~,version] = system('git describe --tags');
+0062             version = strtrim(version);
+0063             [~,commit] = system('git log -n 1 --format=%H');
+0064             commit = commit(1:7);
+0065             %If no tag available or commit is part of tag, get commit instead:
+0066             if ~isempty(strfind(version,'fatal')) || ~isempty(strfind(version,commit))
+0067                 version = ['commit ' commit];
+0068             else
+0069                 version = strrep(version,'v','');
+0070             end
+0071         catch
+0072             version = 'unknown';
+0073         end
+0074     end
+0075 end
+0076 cd(currentPath);
+0077 end
+0078 
+0079 function slashPos = getSlashPos(path)
+0080 slashPos = strfind(path,'\');       %Windows
+0081 if isempty(slashPos)
+0082     slashPos = strfind(path,'/');   %MAC/Linux
+0083 end
+0084 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/io/importExcelModel.html b/doc/io/importExcelModel.html new file mode 100644 index 000000000..0366309c8 --- /dev/null +++ b/doc/io/importExcelModel.html @@ -0,0 +1,1051 @@ + + + + Description of importExcelModel + + + + + + + + + +
Home > io > importExcelModel.m
+ + + +

importExcelModel +

+ +

PURPOSE ^

+
importExcelModel
+ +

SYNOPSIS ^

+
function model=importExcelModel(fileName,removeExcMets,printWarnings,ignoreErrors)
+ +

DESCRIPTION ^

+
 importExcelModel
+   Imports a constraint-based model from a Excel file
+
+   fileName      a Microsoft Excel file to import
+   removeExcMets true if exchange metabolites should be removed. This is
+                 needed to be able to run simulations, but it could also
+                 be done using simplifyModel at a later stage (optional,
+                 default true)
+   printWarnings true if warnings should be printed (optional, default true)
+   ignoreErrors  true if errors should be ignored. See below for details
+                 (optional, default false)
+
+   model
+       annotation       
+           taxonomy     String with the NCBI Taxonomy ID, as valid
+                        identifiers.org annotation
+           defaultLB     Double    with the default lower bound values for reactions
+           defaultUB     Double    with the default upper bound values for reactions
+           givenName     String    with the name of the main model author
+           familyName     String    with the surname of the main model author
+           email        String    with the e-mail address of the main model author
+           organization String    with the organization of the main model author
+           note         String    with additional comments about the model
+       name      name of model
+       id               model ID
+       rxns             reaction ids
+       mets             metabolite ids
+       S                stoichiometric matrix
+       lb               lower bounds
+       ub               upper bounds
+       rev              reversibility vector
+       c                objective coefficients
+       b                equality constraints for the metabolite equations
+       comps            compartment ids
+       compNames        compartment names
+       compOutside      the id (as in comps) for the compartment
+                        surrounding each of the compartments
+       compMiriams      structure with MIRIAM information about the
+                        compartments
+       rxnNames         reaction name
+       rxnComps         compartments for reactions
+       grRules          reaction to gene rules in text form
+       rxnGeneMat       reaction-to-gene mapping in sparse matrix form
+       subSystems       subsystem name for each reaction
+       eccodes          EC-codes for the reactions
+       rxnMiriams       structure with MIRIAM information about the reactions
+       rxnNotes         reaction notes
+       rxnReferences    reaction references
+       rxnConfidenceScores reaction confidence scores
+       genes            list of all genes
+       geneComps        compartments for genes
+       geneMiriams      structure with MIRIAM information about the genes
+       geneShortNames   gene alternative names (e.g. ERG10)
+       metNames         metabolite name
+       metComps         compartments for metabolites
+       inchis           InChI-codes for metabolites
+       metFormulas      metabolite chemical formula
+       metMiriams       structure with MIRIAM information about the metabolites
+       metCharges       metabolite charge
+       unconstrained    true if the metabolite is an exchange metabolite
+
+   Loads models in the RAVEN Toolbox Excel format. A number of consistency
+   checks are performed in order to ensure that the model is valid. These
+   can be ignored by putting ignoreErrors to true. However, this is highly
+   advised against, as it can result in errors in simulations or other
+   functionalities. The RAVEN Toolbox is made to function only on consistent
+   models, and the only checks performed are when the model is imported.
+
+   NOTE: Most errors are checked for by checkModelStruct, but some
+   are checked for in this function as well. Those are ones which relate
+   to missing model elements and so on, and which would make it impossible
+   to construct the model structure. Those errors cannot be ignored by
+   setting ignoreErrors to true.
+
+ Usage: model=importExcelModel(fileName,removeExcMets,printWarnings,ignoreErrors)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 function model=importExcelModel(fileName,removeExcMets,printWarnings,ignoreErrors)
+0002 % importExcelModel
+0003 %   Imports a constraint-based model from a Excel file
+0004 %
+0005 %   fileName      a Microsoft Excel file to import
+0006 %   removeExcMets true if exchange metabolites should be removed. This is
+0007 %                 needed to be able to run simulations, but it could also
+0008 %                 be done using simplifyModel at a later stage (optional,
+0009 %                 default true)
+0010 %   printWarnings true if warnings should be printed (optional, default true)
+0011 %   ignoreErrors  true if errors should be ignored. See below for details
+0012 %                 (optional, default false)
+0013 %
+0014 %   model
+0015 %       annotation
+0016 %           taxonomy     String with the NCBI Taxonomy ID, as valid
+0017 %                        identifiers.org annotation
+0018 %           defaultLB     Double    with the default lower bound values for reactions
+0019 %           defaultUB     Double    with the default upper bound values for reactions
+0020 %           givenName     String    with the name of the main model author
+0021 %           familyName     String    with the surname of the main model author
+0022 %           email        String    with the e-mail address of the main model author
+0023 %           organization String    with the organization of the main model author
+0024 %           note         String    with additional comments about the model
+0025 %       name      name of model
+0026 %       id               model ID
+0027 %       rxns             reaction ids
+0028 %       mets             metabolite ids
+0029 %       S                stoichiometric matrix
+0030 %       lb               lower bounds
+0031 %       ub               upper bounds
+0032 %       rev              reversibility vector
+0033 %       c                objective coefficients
+0034 %       b                equality constraints for the metabolite equations
+0035 %       comps            compartment ids
+0036 %       compNames        compartment names
+0037 %       compOutside      the id (as in comps) for the compartment
+0038 %                        surrounding each of the compartments
+0039 %       compMiriams      structure with MIRIAM information about the
+0040 %                        compartments
+0041 %       rxnNames         reaction name
+0042 %       rxnComps         compartments for reactions
+0043 %       grRules          reaction to gene rules in text form
+0044 %       rxnGeneMat       reaction-to-gene mapping in sparse matrix form
+0045 %       subSystems       subsystem name for each reaction
+0046 %       eccodes          EC-codes for the reactions
+0047 %       rxnMiriams       structure with MIRIAM information about the reactions
+0048 %       rxnNotes         reaction notes
+0049 %       rxnReferences    reaction references
+0050 %       rxnConfidenceScores reaction confidence scores
+0051 %       genes            list of all genes
+0052 %       geneComps        compartments for genes
+0053 %       geneMiriams      structure with MIRIAM information about the genes
+0054 %       geneShortNames   gene alternative names (e.g. ERG10)
+0055 %       metNames         metabolite name
+0056 %       metComps         compartments for metabolites
+0057 %       inchis           InChI-codes for metabolites
+0058 %       metFormulas      metabolite chemical formula
+0059 %       metMiriams       structure with MIRIAM information about the metabolites
+0060 %       metCharges       metabolite charge
+0061 %       unconstrained    true if the metabolite is an exchange metabolite
+0062 %
+0063 %   Loads models in the RAVEN Toolbox Excel format. A number of consistency
+0064 %   checks are performed in order to ensure that the model is valid. These
+0065 %   can be ignored by putting ignoreErrors to true. However, this is highly
+0066 %   advised against, as it can result in errors in simulations or other
+0067 %   functionalities. The RAVEN Toolbox is made to function only on consistent
+0068 %   models, and the only checks performed are when the model is imported.
+0069 %
+0070 %   NOTE: Most errors are checked for by checkModelStruct, but some
+0071 %   are checked for in this function as well. Those are ones which relate
+0072 %   to missing model elements and so on, and which would make it impossible
+0073 %   to construct the model structure. Those errors cannot be ignored by
+0074 %   setting ignoreErrors to true.
+0075 %
+0076 % Usage: model=importExcelModel(fileName,removeExcMets,printWarnings,ignoreErrors)
+0077 fileName=char(fileName);
+0078 
+0079 if nargin<2
+0080     removeExcMets=true;
+0081 end
+0082 if nargin<3
+0083     printWarnings=true;
+0084 end
+0085 if nargin<4
+0086     ignoreErrors=false;
+0087 end
+0088 
+0089 if ~isfile(fileName)
+0090     error('Excel file %s cannot be found',string(fileName));
+0091 end
+0092 
+0093 %This is to match the order of the fields to those you get from importing
+0094 %from SBML
+0095 model=[];
+0096 model.id=[];
+0097 model.name=[];
+0098 model.annotation=[];
+0099 %Default bounds if not defined
+0100 model.annotation.defaultLB=-1000;
+0101 model.annotation.defaultUB=1000;
+0102 model.rxns={};
+0103 model.mets={};
+0104 model.S=[];
+0105 model.lb=[];
+0106 model.ub=[];
+0107 model.rev=[];
+0108 model.c=[];
+0109 model.b=[];
+0110 model.comps={};
+0111 model.compNames={};
+0112 model.compOutside={};
+0113 model.compMiriams={};
+0114 model.rxnNames={};
+0115 model.rxnComps={}; %Will be double later
+0116 model.grRules={};
+0117 model.rxnGeneMat=[];
+0118 model.subSystems={};
+0119 model.eccodes={};
+0120 model.rxnMiriams={};
+0121 model.rxnNotes={};
+0122 model.rxnReferences={};
+0123 model.rxnConfidenceScores={}; %Will be double later
+0124 model.genes={};
+0125 model.geneComps={}; %Will be double later
+0126 model.geneMiriams={};
+0127 model.geneShortNames={};
+0128 model.metNames={};
+0129 model.metComps=[];
+0130 model.inchis={};
+0131 model.metFormulas={};
+0132 model.metMiriams={};
+0133 model.metCharges={}; %Will be double later
+0134 model.unconstrained=[];
+0135 
+0136 workbook=loadWorkbook(fileName);
+0137 
+0138 [raw, flag]=loadSheet(workbook,'MODEL');
+0139 
+0140 if flag<0
+0141     if printWarnings==true
+0142         EM='Could not load the MODEL sheet';
+0143         dispEM(EM,false);
+0144     end
+0145     model.id='UNKNOWN';
+0146     model.name='No model details available';
+0147 else
+0148     raw=cleanSheet(raw);
+0149     
+0150     %It is assumed that the first line is labels and that the second one is
+0151     %info
+0152     raw(1,:)=upper(raw(1,:));
+0153     raw(1,:)=strrep(raw(1,:),'MODELID','ID');
+0154     raw(1,:)=strrep(raw(1,:),'MODELNAME','NAME');
+0155     raw(1,:)=strrep(raw(1,:),'DESCRIPTION','NAME');
+0156     
+0157     %Loop through the labels
+0158     for i=1:numel(raw(1,:))
+0159         switch raw{1,i}
+0160             case 'ID'
+0161                 if any(raw{2,i})
+0162                     model.id=toStr(raw{2,i}); %Should be string already
+0163                 else
+0164                     EM='No model ID supplied';
+0165                     dispEM(EM);
+0166                 end
+0167             case 'NAME'
+0168                 if any(raw{2,i})
+0169                     model.name=toStr(raw{2,i}); %Should be string already
+0170                 else
+0171                     EM='No model name supplied';
+0172                     dispEM(EM);
+0173                 end
+0174             case 'DEFAULT LOWER'
+0175                 if ~isempty(raw{2,i})
+0176                     try
+0177                         model.annotation.defaultLB=toDouble(raw{2,i},NaN);
+0178                     catch
+0179                         EM='DEFAULT LOWER must be numeric';
+0180                         dispEM(EM);
+0181                     end
+0182                 else
+0183                     if printWarnings==true
+0184                         fprintf('NOTE: DEFAULT LOWER not supplied. Uses -1000\n');
+0185                     end
+0186                     model.annotation.defaultLB=-1000;
+0187                 end
+0188             case 'DEFAULT UPPER'
+0189                 if ~isempty(raw{2,i})
+0190                     try
+0191                         model.annotation.defaultUB=toDouble(raw{2,i},NaN);
+0192                     catch
+0193                         EM='DEFAULT UPPER must be numeric';
+0194                         dispEM(EM);
+0195                     end
+0196                 else
+0197                     if printWarnings==true
+0198                         fprintf('NOTE: DEFAULT UPPER not supplied. Uses 1000\n');
+0199                     end
+0200                     model.annotation.defaultUB=1000;
+0201                 end
+0202             case 'TAXONOMY'
+0203                 if any(raw{2,i})
+0204                     model.annotation.taxonomy=toStr(raw{2,i}); %Should be string already
+0205                 end
+0206             case 'CONTACT GIVEN NAME'
+0207                 if any(raw{2,i})
+0208                     model.annotation.givenName=toStr(raw{2,i}); %Should be string already
+0209                 end
+0210             case 'CONTACT FAMILY NAME'
+0211                 if any(raw{2,i})
+0212                     model.annotation.familyName=toStr(raw{2,i}); %Should be string already
+0213                 end
+0214             case 'CONTACT EMAIL'
+0215                 if any(raw{2,i})
+0216                     model.annotation.email=toStr(raw{2,i}); %Should be string already
+0217                 end
+0218             case 'ORGANIZATION'
+0219                 if any(raw{2,i})
+0220                     model.annotation.organization=toStr(raw{2,i}); %Should be string already
+0221                 end
+0222             case 'NOTES'
+0223                 if any(raw{2,i})
+0224                     model.annotation.note=toStr(raw{2,i}); %Should be string already
+0225                 end
+0226         end
+0227     end
+0228 end
+0229 
+0230 %Get compartment information
+0231 [raw, flag]=loadSheet(workbook,'COMPS');
+0232 
+0233 if flag<0
+0234     if printWarnings==true
+0235         EM='Could not load the COMPS sheet. All elements will be assigned to a compartment "s" for "System"';
+0236         dispEM(EM,false);
+0237     end
+0238     model.comps={'s'};
+0239     model.compNames={'System'};
+0240 else
+0241     raw=cleanSheet(raw);
+0242     
+0243     %Map to new captions
+0244     raw(1,:)=upper(raw(1,:));
+0245     raw(1,:)=strrep(raw(1,:),'COMPABBREV','ABBREVIATION');
+0246     raw(1,:)=strrep(raw(1,:),'COMPNAME','NAME');
+0247         
+0248     %Loop through the labels
+0249     for i=1:numel(raw(1,:))
+0250         switch raw{1,i}
+0251             case 'ABBREVIATION'
+0252                 model.comps=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
+0253             case 'NAME'
+0254                 model.compNames=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
+0255             case 'INSIDE'
+0256                 model.compOutside=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
+0257             case 'MIRIAM'
+0258                 model.compMiriams=raw(2:end,i);
+0259         end
+0260     end
+0261     
+0262     %Check that necessary fields are loaded
+0263     if isempty(model.comps)
+0264         EM='There must be a column named ABBREVIATION in the COMPS sheet';
+0265         dispEM(EM);
+0266     end
+0267     if isempty(model.compNames)
+0268         model.compNames=model.comps;
+0269         if printWarnings==true
+0270             EM='There is no column named NAME in the COMPS sheet. ABBREVIATION will be used as name';
+0271             dispEM(EM,false);
+0272         end
+0273     end
+0274     model.compMiriams=parseMiriam(model.compMiriams);
+0275 end
+0276 
+0277 %Get all the genes and info about them
+0278 [raw, flag]=loadSheet(workbook,'GENES');
+0279 
+0280 if flag<0
+0281     if printWarnings==true
+0282         EM='There is no spreadsheet named GENES';
+0283         dispEM(EM,false)
+0284     end
+0285 else
+0286     raw=cleanSheet(raw);
+0287     
+0288     %Map to new captions
+0289     raw(1,:)=upper(raw(1,:));
+0290     raw(1,:)=strrep(raw(1,:),'GENE NAME','NAME');
+0291         
+0292     %Loop through the labels
+0293     foundGenes=false;
+0294     for i=1:numel(raw(1,:))
+0295         switch raw{1,i}
+0296             case 'NAME'
+0297                 model.genes=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
+0298                 foundGenes=true;
+0299             case 'MIRIAM'
+0300                 model.geneMiriams=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
+0301             case 'SHORT NAME'
+0302                 model.geneShortNames=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
+0303             case 'COMPARTMENT'
+0304                 model.geneComps=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
+0305         end
+0306     end
+0307     
+0308     if foundGenes==false
+0309         EM='There must be a column named NAME in the GENES sheet';
+0310         dispEM(EM);
+0311     end
+0312     
+0313     %Its ok if all of them are empty
+0314     if all(cellfun(@isempty,model.geneComps))
+0315         model.geneComps=[];
+0316     end
+0317     
+0318     %Check that geneName contain only strings and no empty strings
+0319     if ~iscellstr(model.genes)
+0320         EM='All gene names have to be strings';
+0321         dispEM(EM);
+0322     else
+0323         if any(strcmp('',model.genes))
+0324             EM='There can be no empty strings in gene names';
+0325             dispEM(EM);
+0326         end
+0327     end
+0328     
+0329     %Check that geneComp contains only strings and no empty string
+0330     if ~isempty(model.geneComps)
+0331         if ~iscellstr(model.geneComps)
+0332             EM='All gene compartments have to be strings';
+0333             dispEM(EM);
+0334         else
+0335             if any(strcmp('',model.geneComps))
+0336                 EM='There can be no empty strings in gene compartments';
+0337                 dispEM(EM);
+0338             end
+0339         end
+0340         [I, model.geneComps]=ismember(model.geneComps,model.comps);
+0341         EM='The following genes have compartment abbreviations which could not be found:';
+0342         dispEM(EM,true,model.genes(~I));
+0343     end
+0344 end
+0345 
+0346 model.geneMiriams=parseMiriam(model.geneMiriams);
+0347 
+0348 %Loads the reaction data
+0349 [raw, flag]=loadSheet(workbook,'RXNS');
+0350 
+0351 if flag<0
+0352     EM='Could not load the RXNS sheet';
+0353     dispEM(EM);
+0354 end
+0355 
+0356 raw=cleanSheet(raw);
+0357 
+0358 %Map to new captions
+0359 raw(1,:)=upper(raw(1,:));
+0360 raw(1,:)=strrep(raw(1,:),'RXNID','ID');
+0361 
+0362 %Loop through the labels
+0363 equations={};
+0364 reactionReplacement={};
+0365 for i=1:numel(raw(1,:))
+0366     switch raw{1,i}
+0367         case 'ID'
+0368             model.rxns=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
+0369         case 'NAME'
+0370             model.rxnNames=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
+0371         case 'EQUATION'
+0372             equations=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
+0373         case 'EC-NUMBER'
+0374             model.eccodes=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
+0375         case 'GENE ASSOCIATION'
+0376             model.grRules=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
+0377         case 'LOWER BOUND'
+0378             try
+0379                 model.lb=cellfun(@(x) toDouble(x,NaN),raw(2:end,i));
+0380             catch
+0381                 EM='The lower bounds must be numerical values';
+0382                 dispEM(EM);
+0383             end
+0384         case 'UPPER BOUND'
+0385             try
+0386                 model.ub=cellfun(@(x) toDouble(x,NaN),raw(2:end,i));
+0387             catch
+0388                 EM='The upper bounds must be numerical values';
+0389                 dispEM(EM);
+0390             end
+0391         case 'OBJECTIVE'
+0392             try
+0393                 model.c=cellfun(@(x) toDouble(x,0),raw(2:end,i));
+0394             catch
+0395                 EM='The objective coefficients must be numerical values';
+0396                 dispEM(EM);
+0397             end
+0398         case 'COMPARTMENT'
+0399             model.rxnComps=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
+0400         case 'SUBSYSTEM'
+0401             subsystems=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
+0402         case 'REPLACEMENT ID'
+0403             reactionReplacement=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
+0404         case 'MIRIAM'
+0405             model.rxnMiriams=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
+0406         case 'NOTE'
+0407             model.rxnNotes=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
+0408         case 'REFERENCE'
+0409             model.rxnReferences=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
+0410         case 'CONFIDENCE SCORE'
+0411             model.rxnConfidenceScores=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
+0412     end
+0413 end
+0414 
+0415 if ~isempty(model.rxnConfidenceScores)
+0416     model.rxnConfidenceScores=str2double(model.rxnConfidenceScores);
+0417 end
+0418 for i=1:numel(subsystems)
+0419     model.subSystems{i,1}=cellstr(strsplit(subsystems{i,1},';'));
+0420 end
+0421 
+0422 %Check that all necessary reaction info has been loaded
+0423 if isempty(equations)
+0424     EM='There must be a column named EQUATION in the RXNS sheet';
+0425     dispEM(EM);
+0426 end
+0427 if isempty(model.rxns)
+0428     if printWarnings==true
+0429         EM='There is no column named ID in the RXNS sheet. The reactions will be named as "r1", "r2"...';
+0430         dispEM(EM,false);
+0431     end
+0432     I=num2cell((1:numel(equations))');
+0433     model.rxns=strcat('r',cellfun(@num2str,I,'UniformOutput',false));
+0434 end
+0435 
+0436 %Check if some other stuff is loaded and populate with default values
+0437 %otherwise
+0438 if isempty(model.rxnNames)
+0439     model.rxnNames=cell(numel(model.rxns),1);
+0440     model.rxnNames(:)={''};
+0441     if printWarnings==true
+0442         EM='There is no column named NAME in the RXNS sheet. Empty strings will be used as reaction names';
+0443         dispEM(EM,false);
+0444     end
+0445 end
+0446 if isempty(model.lb)
+0447     %This is not set here since the reversibility isn't known yet
+0448     model.lb=nan(numel(model.rxns),1);
+0449     if printWarnings==true
+0450         EM='There is no column named LOWER BOUND in the RXNS sheet. Default bounds will be used';
+0451         dispEM(EM,false);
+0452     end
+0453 end
+0454 if isempty(model.ub)
+0455     model.ub=nan(numel(model.rxns),1);
+0456     if printWarnings==true
+0457         EM='There is no column named UPPER BOUND in the RXNS sheet. Default bounds will be used';
+0458         dispEM(EM,false);
+0459     end
+0460 end
+0461 if isempty(model.c)
+0462     model.c=zeros(numel(model.rxns),1);
+0463     if printWarnings==true
+0464         EM='There is no column named OBJECTIVE in the RXNS sheet';
+0465         dispEM(EM,false);
+0466     end
+0467 end
+0468 
+0469 %Either all reactions must have a compartment string or none of them. Check
+0470 %if it's only empty and if so return it to []
+0471 if ~isempty(model.rxnComps)
+0472     if all(cellfun(@isempty,model.rxnComps))
+0473         model.rxnComps=[];
+0474     end
+0475 end
+0476 
+0477 %Construct the rxnMiriams structure
+0478 model.rxnMiriams=parseMiriam(model.rxnMiriams);
+0479 
+0480 %Replace the reaction IDs for those IDs that have a corresponding
+0481 %replacement name.
+0482 I=cellfun(@any,reactionReplacement);
+0483 model.rxns(I)=reactionReplacement(I);
+0484 
+0485 %Check that there are no empty strings in reactionIDs or equations
+0486 if any(strcmp('',model.rxns))
+0487     EM='There are empty reaction IDs';
+0488     dispEM(EM);
+0489 end
+0490 
+0491 if any(strcmp('',equations))
+0492     EM='There are empty equations';
+0493     dispEM(EM);
+0494 end
+0495 
+0496 if ~isempty(model.rxnComps)
+0497     if any(strcmp('',model.rxnComps))
+0498         EM='Either all reactions must have an associated compartment string or none of them';
+0499         dispEM(EM);
+0500     end
+0501 end
+0502 
+0503 if ~isempty(model.grRules)
+0504     tempRules=model.grRules;
+0505     for i=1:length(model.rxns)
+0506         %Check that all gene associations have a match in the gene list
+0507         if ~isempty(model.grRules{i})
+0508             tempRules{i}=regexprep(tempRules{i},' and | or ','>'); %New format: Genes are separated 'and' and 'or' strings with parentheses
+0509             tempRules{i}=regexprep(tempRules{i},'(',''); %New format: Genes are separated 'and' and 'or' strings with parentheses
+0510             tempRules{i}=regexprep(tempRules{i},')',''); %New format: Genes are separated 'and' and 'or' strings with parentheses
+0511             indexesNew=strfind(tempRules{i},'>'); %Old format: Genes are separated by ":" for AND and ";" for OR
+0512             indexes=strfind(tempRules{i},':'); %Old format: Genes are separated by ":" for AND and ";" for OR
+0513             indexes=unique([indexesNew indexes strfind(tempRules{i},';')]);
+0514             if isempty(indexes)
+0515                 %See if you have a match
+0516                 I=find(strcmp(tempRules{i},model.genes));
+0517                 if isempty(I)
+0518                     EM=['The gene association in reaction ' model.rxns{i} ' (' tempRules{i} ') is not present in the gene list'];
+0519                     dispEM(EM);
+0520                 end
+0521             else
+0522                 temp=[0 indexes numel(tempRules{i})+1];
+0523                 for j=1:numel(indexes)+1
+0524                     %The reaction has several associated genes
+0525                     geneName=tempRules{i}(temp(j)+1:temp(j+1)-1);
+0526                     I=find(strcmp(geneName,model.genes));
+0527                     if isempty(I)
+0528                         EM=['The gene association in reaction ' model.rxns{i} ' (' geneName ') is not present in the gene list'];
+0529                         dispEM(EM);
+0530                     end
+0531                 end
+0532             end
+0533             %In order to adhere to the COBRA standards it should be like
+0534             %this: -If only one gene then no parentheses -If only "and" or
+0535             %only "or" there should only be one set of parentheses -If both
+0536             %"and" and "or", then split on "or". This is not complete, but
+0537             %it's the type of relationship supported by the Excel
+0538             %formulation
+0539             aSign=strfind(model.grRules{i},':');
+0540             oSign=strfind(model.grRules{i},';');
+0541             if isempty(aSign) && isempty(oSign)
+0542                 model.grRules{i}=model.grRules{i};
+0543             else
+0544                 if isempty(aSign)
+0545                     model.grRules{i}=['(' strrep(model.grRules{i},';',' or ') ')'];
+0546                 else
+0547                     if isempty(oSign)
+0548                         model.grRules{i}=['(' strrep(model.grRules{i},':',' and ') ')'];
+0549                     else
+0550                         model.grRules{i}=['((' strrep(model.grRules{i},';',') or (') '))'];
+0551                         model.grRules{i}=strrep(model.grRules{i},':',' and ');
+0552                     end
+0553                 end
+0554             end
+0555         end
+0556     end
+0557 end
+0558 
+0559 %Check that the compartment for each reaction can be found
+0560 if ~isempty(model.rxnComps)
+0561     [I, model.rxnComps]=ismember(model.rxnComps,model.comps);
+0562     EM='The following reactions have compartment abbreviations which could not be found:';
+0563     dispEM(EM,true,model.rxns(~I));
+0564 end
+0565 
+0566 %Get all the metabolites and info about them
+0567 [raw, flag]=loadSheet(workbook,'METS');
+0568 
+0569 if flag<0
+0570     if printWarnings==true
+0571         EM='There is no spreadsheet named METS. The metabolites will be named "m1", "m2"... and assigned to the first compartment';
+0572         dispEM(EM,false);
+0573     end
+0574     %Parse the equations to find out how many metabolites there are
+0575     metsForParsing=parseRxnEqu(equations);
+0576     I=num2cell((1:numel(metsForParsing))');
+0577     model.mets=strcat('m',cellfun(@num2str,I,'UniformOutput',false));
+0578     model.metComps=ones(numel(model.mets),1);
+0579     model.unconstrained=zeros(numel(model.mets),1);
+0580     model.metNames=metsForParsing;
+0581 else
+0582     raw=cleanSheet(raw);
+0583     
+0584     %Map to new captions
+0585     raw(1,:)=upper(raw(1,:));
+0586     raw(1,:)=strrep(raw(1,:),'METID','ID');
+0587     raw(1,:)=strrep(raw(1,:),'METNAME','NAME');
+0588     
+0589     %Loop through the labels
+0590     metReplacement={};
+0591     for i=1:numel(raw(1,:))
+0592         switch raw{1,i}
+0593             case 'ID'
+0594                 model.mets=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
+0595             case 'NAME'
+0596                 model.metNames=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
+0597             case 'UNCONSTRAINED'
+0598                 model.unconstrained=cellfun(@boolToDouble,raw(2:end,i));
+0599                 %NaN is returned if the values couldn't be parsed
+0600                 EM='The UNCONSTRAINED property for the following metabolites must be "true"/"false", 1/0, TRUE/FALSE or not set:';
+0601                 dispEM(EM,true,model.mets(isnan(model.unconstrained)));
+0602             case 'MIRIAM'
+0603                 model.metMiriams=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
+0604             case 'COMPOSITION'
+0605                 model.metFormulas=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
+0606             case 'INCHI'
+0607                 model.inchis=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
+0608             case 'COMPARTMENT'
+0609                 model.metComps=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
+0610                 
+0611                 %Check that all metabolites have compartments defined
+0612                 if any(strcmp('',model.metComps))
+0613                     EM='All metabolites must have an associated compartment string';
+0614                     dispEM(EM);
+0615                 end
+0616             case 'REPLACEMENT ID'
+0617                 metReplacement=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
+0618             case 'CHARGE'
+0619                 model.metCharges=cellfun(@toStr,raw(2:end,i),'UniformOutput',false);
+0620         end
+0621     end
+0622     
+0623     %Check that necessary fields are loaded (METID)
+0624     if isempty(model.mets)
+0625         EM='There must be a column named ID in the METS sheet';
+0626         dispEM(EM);
+0627     end
+0628     
+0629     %Check that some other stuff is loaded and use default values otherwise
+0630     if isempty(model.metNames)
+0631         model.metNames=cell(numel(model.mets),1);
+0632         if printWarnings==true
+0633             EM='There is no column named NAME in the METS sheet. ID will be used as name';
+0634             dispEM(EM,false);
+0635         end
+0636     end
+0637     if isempty(model.unconstrained)
+0638         model.unconstrained=zeros(numel(model.mets),1);
+0639         if printWarnings==true
+0640             EM='There is no column named UNCONSTRAINED in the METS sheet. All metabolites will be constrained';
+0641             dispEM(EM,false);
+0642         end
+0643     end
+0644     
+0645     if isempty(model.metComps)
+0646         model.metComps=cell(numel(model.mets),1);
+0647         model.metComps(:)=model.comps(1);
+0648         if printWarnings==true
+0649             EM='There is no column named COMPARTMENT in the METS sheet. All metabolites will be assigned to the first compartment in COMPS. Note that RAVEN makes extensive use of metabolite names and compartments. Some features will therefore not function correctly if metabolite compartments are not correctly assigned';
+0650             dispEM(EM,false);
+0651         end
+0652     end
+0653     
+0654     %The composition should be loaded from InChIs when available
+0655     I=find(~cellfun(@isempty,model.inchis));
+0656     for i=1:numel(I)
+0657         S=regexp(model.inchis(I(i)),'/','split');
+0658         S=S{1};
+0659         if numel(S)>=2
+0660             %Don't copy if it doesn't look good
+0661             model.metFormulas(I(i))=S(2);
+0662         end
+0663     end
+0664     
+0665     %Check that the compartment for each metabolite can be found. Also
+0666     %convert from id to index
+0667     [I, model.metComps]=ismember(model.metComps,model.comps);
+0668     EM='The following metabolites have compartment abbreviations which could not be found:';
+0669     dispEM(EM,true,model.mets(~I));
+0670     
+0671     %Check that the model.mets vector is unique. The problem is that the
+0672     %checkModelStruct cannot check for that since only the metReplacements
+0673     %(if used) end up in the model structure
+0674     I=false(numel(model.mets),1);
+0675     [J, K]=unique(model.mets);
+0676     if numel(J)~=numel(model.mets)
+0677         L=1:numel(model.mets);
+0678         L(K)=[];
+0679         I(L)=true;
+0680     end
+0681     EM='The following metabolites are duplicates:';
+0682     dispEM(EM,~ignoreErrors,model.mets(I));
+0683     
+0684     %Check that there are no metabolite IDs which are numbers. This would
+0685     %give errors when parsing the equations
+0686     I=cellfun(@str2double,model.mets);
+0687     EM='The following metabolites have names which cannot be distinguished from numbers:';
+0688     dispEM(EM,~ignoreErrors,model.mets(~isnan(I)));
+0689     I=cellfun(@str2double,metReplacement);
+0690     EM='The following metabolites have names which cannot be distinguished from numbers:';
+0691     dispEM(EM,~ignoreErrors,metReplacement(~isnan(I)));
+0692     
+0693     %Replace the metabolite IDs for those IDs that have a corresponding
+0694     %replacement metabolite. This is not used for matching, but will be
+0695     %checked for consistency with SBML naming conventions
+0696     metsForParsing=model.mets; %This is because the equations are written with this
+0697     I=cellfun(@any,metReplacement);
+0698     model.mets(I)=metReplacement(I);
+0699     
+0700     %If the metabolite name isn't set, replace it with the metabolite id
+0701     I=~cellfun(@any,model.metNames);
+0702     model.metNames(I)=model.mets(I);
+0703     
+0704     %Construct the metMiriams structure
+0705     model.metMiriams=parseMiriam(model.metMiriams);
+0706     
+0707     %Either all metabolites have charge or none of them. Check if it's only
+0708     %empty and if so return it to []
+0709     if ~isempty(model.metCharges)
+0710         if all(cellfun(@isempty,model.metCharges))
+0711             model.metCharges=[];
+0712         end
+0713     end
+0714     if ~isempty(model.metCharges)
+0715         model.metCharges=str2double(model.metCharges);
+0716     end
+0717 end
+0718 
+0719 %Everything seems fine with the metabolite IDs, compartments, genes, and
+0720 %reactions
+0721 
+0722 %Parse the equations
+0723 [model.S, mets, badRxns, model.rev]=constructS(equations,metsForParsing,model.rxns);
+0724 model.rev=model.rev*1; %Typecast to double
+0725 
+0726 %Add default constraints
+0727 model.lb(isnan(model.lb))=model.annotation.defaultLB.*model.rev(isnan(model.lb));
+0728 model.ub(isnan(model.ub))=model.annotation.defaultUB;
+0729 
+0730 %Reorder the S matrix so that it fits with the metabolite list in the
+0731 %structure
+0732 [~, I]=ismember(mets,metsForParsing);
+0733 model.S=model.S(I,:);
+0734 
+0735 %Print warnings about the reactions which contain the same metabolite as
+0736 %both reactants and products
+0737 EM='The following reactions have metabolites which are present more than once. Only the net reactions will be exported:';
+0738 dispEM(EM,false,model.rxns(badRxns));
+0739 
+0740 model.b=zeros(numel(model.mets),1);
+0741 
+0742 %Fix grRules and reconstruct rxnGeneMat
+0743 [grRules,rxnGeneMat] = standardizeGrRules(model,true);
+0744 model.grRules = grRules;
+0745 model.rxnGeneMat = rxnGeneMat;
+0746 
+0747 %Remove unused fields
+0748 if all(cellfun(@isempty,model.compOutside))
+0749     model=rmfield(model,'compOutside');
+0750 end
+0751 if all(cellfun(@isempty,model.compMiriams))
+0752     model=rmfield(model,'compMiriams');
+0753 end
+0754 if all(cellfun(@isempty,model.rxnNames))
+0755     model=rmfield(model,'rxnNames');
+0756 end
+0757 if isempty(model.rxnComps)
+0758     model=rmfield(model,'rxnComps');
+0759 end
+0760 if all(cellfun(@isempty,model.grRules))
+0761     model=rmfield(model,'grRules');
+0762 end
+0763 if isfield(model,'rxnGeneMat') && isempty(model.rxnGeneMat)
+0764     model=rmfield(model,'rxnGeneMat');
+0765 end
+0766 if all(cellfun(@isempty,model.subSystems))
+0767     model=rmfield(model,'subSystems');
+0768 end
+0769 if all(cellfun(@isempty,model.eccodes))
+0770     model=rmfield(model,'eccodes');
+0771 end
+0772 if all(cellfun(@isempty,model.rxnMiriams))
+0773     model=rmfield(model,'rxnMiriams');
+0774 end
+0775 if all(cellfun(@isempty,model.rxnNotes))
+0776     model=rmfield(model,'rxnNotes');
+0777 end
+0778 if all(cellfun(@isempty,model.rxnReferences))
+0779     model=rmfield(model,'rxnReferences');
+0780 end
+0781 if isempty(model.rxnConfidenceScores)
+0782     model=rmfield(model,'rxnConfidenceScores');
+0783 end
+0784 if isempty(model.genes)
+0785     model=rmfield(model,'genes');
+0786 end
+0787 if isempty(model.geneComps)
+0788     model=rmfield(model,'geneComps');
+0789 end
+0790 if isempty(model.geneMiriams)
+0791     model=rmfield(model,'geneMiriams');
+0792 end
+0793 if all(cellfun(@isempty,model.geneShortNames))
+0794     model=rmfield(model,'geneShortNames');
+0795 end
+0796 if all(cellfun(@isempty,model.inchis))
+0797     model=rmfield(model,'inchis');
+0798 end
+0799 if all(cellfun(@isempty,model.metFormulas))
+0800     model=rmfield(model,'metFormulas');
+0801 end
+0802 if all(cellfun(@isempty,model.metMiriams))
+0803     model=rmfield(model,'metMiriams');
+0804 end
+0805 if isempty(model.metCharges)
+0806     model=rmfield(model,'metCharges');
+0807 end
+0808 
+0809 %The model structure has now been reconstructed but it can still contain
+0810 %many types of errors. The checkModelConsistency function is used to make
+0811 %sure that naming and mapping of stuff looks good
+0812 checkModelStruct(model,~ignoreErrors);
+0813 
+0814 if removeExcMets==true
+0815     model=simplifyModel(model);
+0816 end
+0817 end
+0818 
+0819 function miriamStruct=parseMiriam(strings,miriamStruct)
+0820 %Gets the names and values of Miriam-string. Nothing fancy at all, just to
+0821 %prevent using the same code for metabolites, genes, and reactions. The
+0822 %function also allows for supplying a miriamStruct and the info will then
+0823 %be added
+0824 
+0825 if nargin<2
+0826     miriamStruct=cell(numel(strings),1);
+0827 end
+0828 for i=1:numel(strings)
+0829     if any(strings{i})
+0830         %A Miriam string can be several ids separated by ";". Each id is
+0831         %"name(..:..)/value"; an old format when value is separated by
+0832         %colon is also supported
+0833         I=regexp(strings{i},';','split');
+0834         if isfield(miriamStruct{i},'name')
+0835             startIndex=numel(miriamStruct{i}.name);
+0836             miriamStruct{i}.name=[miriamStruct{i}.name;cell(numel(I),1)];
+0837             miriamStruct{i}.value=[miriamStruct{i}.value;cell(numel(I),1)];
+0838         else
+0839             startIndex=0;
+0840             miriamStruct{i}.name=cell(numel(I),1);
+0841             miriamStruct{i}.value=cell(numel(I),1);
+0842         end
+0843         
+0844         for j=1:numel(I)
+0845             if any(strfind(I{j},'/'))
+0846                 index=max(strfind(I{j},'/'));
+0847             elseif any(strfind(I{j},':'))
+0848                 index=max(strfind(I{j},':'));
+0849             end
+0850             if exist('index','var') & any(index)
+0851                 miriamStruct{i}.name{startIndex+j}=I{j}(1:index-1);
+0852                 miriamStruct{i}.value{startIndex+j}=I{j}(index+1:end);
+0853             else
+0854                 EM=['"' I{j} '" is not a valid MIRIAM string. The format must be "identifier/value" or identifier:value'];
+0855                 dispEM(EM);
+0856             end
+0857         end
+0858     end
+0859 end
+0860 end
+0861 
+0862 %For converting a value to string. This is used instead of num2str because
+0863 %I want to convert empty cells to {''}.
+0864 function y=toStr(x)
+0865 %x can be empty, numerical, string or boolean. It cannot be NaN. Boolean
+0866 %values will be converted to '1'/'0'
+0867 if isempty(x)
+0868     y='';
+0869 else
+0870     y=num2str(x);
+0871 end
+0872 end
+0873 
+0874 %For converting to numeric. This is used instead of str2num because I want
+0875 %to be able to choose what empty values should be mapped to.
+0876 %
+0877 % default the value to use for empty input
+0878 function y=toDouble(x,default)
+0879 if isempty(x) %Note that this catches '' as well
+0880     y=default;
+0881 else
+0882     if isnumeric(x)
+0883         y=x;
+0884     else
+0885         y=str2double(x);
+0886         
+0887         %This happens if the input couldn't be converted. Note that the
+0888         %input itself cannot be NaN since it was fixed in clean imported
+0889         if isnan(y)
+0890             EM=['Cannot convert the string "' x '" to double'];
+0891             dispEM(EM);
+0892         end
+0893     end
+0894 end
+0895 end
+0896 
+0897 %For converting boolean (the UNCONSTRAINED field) to double (the
+0898 %model.unconstrained field)
+0899 function y=boolToDouble(x)
+0900 if isempty(x)
+0901     y=0;
+0902     return;
+0903 end
+0904 if islogical(x)
+0905     y=x*1; %Typecast to double
+0906     return;
+0907 end
+0908 if isnumeric(x)
+0909     if x~=0
+0910         y=1;
+0911         return;
+0912     else
+0913         y=0;
+0914         return;
+0915     end
+0916 end
+0917 if ischar(x)
+0918     if strcmpi(x,'TRUE')
+0919         y=1;
+0920         return;
+0921     end
+0922     if strcmpi(x,'FALSE')
+0923         y=0;
+0924         return;
+0925     end
+0926 end
+0927 y=NaN; %This means that the input couldn't be parsed
+0928 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/io/importModel.html b/doc/io/importModel.html new file mode 100644 index 000000000..dff37de8c --- /dev/null +++ b/doc/io/importModel.html @@ -0,0 +1,1263 @@ + + + + Description of importModel + + + + + + + + + +
Home > io > importModel.m
+ + + +

importModel +

+ +

PURPOSE ^

+
importModel
+ +

SYNOPSIS ^

+
function model=importModel(fileName,removeExcMets,removePrefix,supressWarnings)
+ +

DESCRIPTION ^

+
 importModel
+   Import a constraint-based model from an SBML file.
+
+ Input:
+   fileName        a SBML file to import. A dialog window will open if
+                   no file name is specified.
+   removeExcMets   true if exchange metabolites should be removed. This is
+                   needed to be able to run simulations, but it could also
+                   be done using simplifyModel at a later stage (optional,
+                   default true)
+   removePrefix    true if identifier prefixes should be removed when
+                   loading the model: G_ for genes, R_ for reactions,
+                   M_ for metabolites, and C_ for compartments. These are
+                   only removed if all identifiers of a certain type
+                   contain the prefix. (optional, default true)
+   supressWarnings true if warnings regarding the model structure should
+                   be supressed (optional, default false)
+
+ Output:
+   model
+       id               model ID
+       name             name of model contents
+       annotation       additional information about model
+       rxns             reaction ids
+       mets             metabolite ids
+       S                stoichiometric matrix
+       lb               lower bounds
+       ub               upper bounds
+       rev              reversibility vector
+       c                objective coefficients
+       b                equality constraints for the metabolite equations
+       comps            compartment ids
+       compNames        compartment names
+       compOutside      the id (as in comps) for the compartment
+                        surrounding each of the compartments
+       compMiriams      structure with MIRIAM information about the
+                        compartments
+       rxnNames         reaction description
+       rxnComps         compartments for reactions
+       grRules          reaction to gene rules in text form
+       rxnGeneMat       reaction-to-gene mapping in sparse matrix form
+       subSystems       subsystem name for each reaction
+       eccodes          EC-codes for the reactions
+       rxnMiriams       structure with MIRIAM information about the reactions
+       rxnNotes         reaction notes
+       rxnReferences    reaction references
+       rxnConfidenceScores reaction confidence scores
+       genes            list of all genes
+       geneComps        compartments for genes
+       geneMiriams      structure with MIRIAM information about the genes
+       geneShortNames   gene alternative names (e.g. ERG10)
+       proteins         protein associated to each gene
+       metNames         metabolite description
+       metComps         compartments for metabolites
+       inchis           InChI-codes for metabolites
+       metFormulas      metabolite chemical formula
+       metMiriams       structure with MIRIAM information about the metabolites
+       metCharges       metabolite charge
+       unconstrained    true if the metabolite is an exchange metabolite
+
+ Note: A number of consistency checks are performed in order to ensure that the
+ model is valid. Take these warnings seriously and modify the model
+ structure to solve them.
+
+ Usage: model = importModel(fileName, removeExcMets, removePrefix, supressWarnings)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 function model=importModel(fileName,removeExcMets,removePrefix,supressWarnings)
+0002 % importModel
+0003 %   Import a constraint-based model from an SBML file.
+0004 %
+0005 % Input:
+0006 %   fileName        a SBML file to import. A dialog window will open if
+0007 %                   no file name is specified.
+0008 %   removeExcMets   true if exchange metabolites should be removed. This is
+0009 %                   needed to be able to run simulations, but it could also
+0010 %                   be done using simplifyModel at a later stage (optional,
+0011 %                   default true)
+0012 %   removePrefix    true if identifier prefixes should be removed when
+0013 %                   loading the model: G_ for genes, R_ for reactions,
+0014 %                   M_ for metabolites, and C_ for compartments. These are
+0015 %                   only removed if all identifiers of a certain type
+0016 %                   contain the prefix. (optional, default true)
+0017 %   supressWarnings true if warnings regarding the model structure should
+0018 %                   be supressed (optional, default false)
+0019 %
+0020 % Output:
+0021 %   model
+0022 %       id               model ID
+0023 %       name             name of model contents
+0024 %       annotation       additional information about model
+0025 %       rxns             reaction ids
+0026 %       mets             metabolite ids
+0027 %       S                stoichiometric matrix
+0028 %       lb               lower bounds
+0029 %       ub               upper bounds
+0030 %       rev              reversibility vector
+0031 %       c                objective coefficients
+0032 %       b                equality constraints for the metabolite equations
+0033 %       comps            compartment ids
+0034 %       compNames        compartment names
+0035 %       compOutside      the id (as in comps) for the compartment
+0036 %                        surrounding each of the compartments
+0037 %       compMiriams      structure with MIRIAM information about the
+0038 %                        compartments
+0039 %       rxnNames         reaction description
+0040 %       rxnComps         compartments for reactions
+0041 %       grRules          reaction to gene rules in text form
+0042 %       rxnGeneMat       reaction-to-gene mapping in sparse matrix form
+0043 %       subSystems       subsystem name for each reaction
+0044 %       eccodes          EC-codes for the reactions
+0045 %       rxnMiriams       structure with MIRIAM information about the reactions
+0046 %       rxnNotes         reaction notes
+0047 %       rxnReferences    reaction references
+0048 %       rxnConfidenceScores reaction confidence scores
+0049 %       genes            list of all genes
+0050 %       geneComps        compartments for genes
+0051 %       geneMiriams      structure with MIRIAM information about the genes
+0052 %       geneShortNames   gene alternative names (e.g. ERG10)
+0053 %       proteins         protein associated to each gene
+0054 %       metNames         metabolite description
+0055 %       metComps         compartments for metabolites
+0056 %       inchis           InChI-codes for metabolites
+0057 %       metFormulas      metabolite chemical formula
+0058 %       metMiriams       structure with MIRIAM information about the metabolites
+0059 %       metCharges       metabolite charge
+0060 %       unconstrained    true if the metabolite is an exchange metabolite
+0061 %
+0062 % Note: A number of consistency checks are performed in order to ensure that the
+0063 % model is valid. Take these warnings seriously and modify the model
+0064 % structure to solve them.
+0065 %
+0066 % Usage: model = importModel(fileName, removeExcMets, removePrefix, supressWarnings)
+0067 
+0068 if nargin<1 || isempty(fileName)
+0069     [fileName, pathName] = uigetfile({'*.xml;*.sbml'}, 'Please select the model file');
+0070     if fileName == 0
+0071         error('You should select a model file')
+0072     else
+0073         fileName = fullfile(pathName,fileName);
+0074     end
+0075 end
+0076 fileName=char(fileName);
+0077 if nargin<2 || isempty(removeExcMets)
+0078     removeExcMets=true;
+0079 end
+0080 
+0081 if nargin<3 || isempty(removePrefix)
+0082     removePrefix=true;
+0083 end
+0084 
+0085 if nargin<4
+0086     supressWarnings=false;
+0087 end
+0088 
+0089 fileName=checkFileExistence(fileName,1);
+0090 % If path contains non-ASCII characters, copy file to tempdir first, as
+0091 % libSBML is known to have problems with this on Windows:
+0092 % https://sbml.org/software/libsbml/libsbml-docs/known-pitfalls/#matlab-on-windows-has-issues-with-unicode-filenames
+0093 if ispc && any(double(fileName)>128)
+0094     [~,originalFile,ext] = fileparts(fileName);
+0095     tempFile = fullfile(tempdir,[originalFile ext]);
+0096     copyfile(fileName,tempFile);
+0097     fileName = tempFile;
+0098 end
+0099 
+0100 %This is to match the order of the fields to those you get from importing
+0101 %from Excel
+0102 model=[];
+0103 model.id=[];
+0104 model.name=[];
+0105 model.annotation=[];
+0106 model.rxns={};
+0107 model.mets={};
+0108 model.S=[];
+0109 model.lb=[];
+0110 model.ub=[];
+0111 model.rev=[];
+0112 model.c=[];
+0113 model.b=[];
+0114 model.comps={};
+0115 model.compNames={};
+0116 model.compOutside={};
+0117 model.compMiriams={};
+0118 model.rxnNames={};
+0119 model.rxnComps=[];
+0120 model.grRules={};
+0121 model.rxnGeneMat=[];
+0122 model.subSystems={};
+0123 model.eccodes={};
+0124 model.rxnMiriams={};
+0125 model.rxnNotes={};
+0126 model.rxnReferences={};
+0127 model.rxnConfidenceScores=[];
+0128 model.genes={};
+0129 model.geneComps=[];
+0130 model.geneMiriams={};
+0131 model.geneShortNames={};
+0132 model.proteins={};
+0133 model.metNames={};
+0134 model.metComps=[];
+0135 model.inchis={};
+0136 model.metFormulas={};
+0137 model.metMiriams={};
+0138 model.metCharges=[];
+0139 model.unconstrained=[];
+0140 
+0141 %Load the model using libSBML
+0142 [modelSBML,errorMsg] = TranslateSBML_RAVEN(fileName,0,0,[1 1]);
+0143 if exist('tempFile','var')
+0144     delete(tempFile)
+0145 end
+0146 
+0147 if isempty(modelSBML)
+0148     EM=['There is a problem with the SBML file. Try using the SBML Validator at http://sbml.org/Facilities/Validator.\nlibSBML reports: ', errorMsg.message];
+0149     dispEM(EM);
+0150 end
+0151 
+0152 %Retrieve compartment names and IDs
+0153 compartmentNames=cell(numel(modelSBML.compartment),1);
+0154 compartmentIDs=cell(numel(modelSBML.compartment),1);
+0155 compartmentOutside=cell(numel(modelSBML.compartment),1);
+0156 compartmentMiriams=cell(numel(modelSBML.compartment),1);
+0157 
+0158 if isfield(modelSBML.compartment,'sboTerm') && isscalar(unique([modelSBML.compartment.sboTerm]))
+0159     %If all the SBO terms are identical, don't add them to compMiriams
+0160     modelSBML.compartment = rmfield(modelSBML.compartment,'sboTerm');
+0161 end
+0162 
+0163 for i=1:numel(modelSBML.compartment)
+0164     compartmentNames{i}=modelSBML.compartment(i).name;
+0165     compartmentIDs{i}=modelSBML.compartment(i).id;
+0166     if isfield(modelSBML.compartment(i),'outside')
+0167         if ~isempty(modelSBML.compartment(i).outside)
+0168             compartmentOutside{i}=modelSBML.compartment(i).outside;
+0169         else
+0170             compartmentOutside{i}='';
+0171         end
+0172     else
+0173         compartmentOutside{i}=[];
+0174     end
+0175 
+0176     if isfield(modelSBML.compartment(i),'annotation')
+0177         compartmentMiriams{i}=parseMiriam(modelSBML.compartment(i).annotation);
+0178     else
+0179         compartmentMiriams{i}=[];
+0180     end
+0181 
+0182     if isfield(modelSBML.compartment(i),'sboTerm') && ~(modelSBML.compartment(i).sboTerm==-1)
+0183         compartmentMiriams{i} = addSBOtoMiriam(compartmentMiriams{i},modelSBML.compartment(i).sboTerm);
+0184     end
+0185 end
+0186 
+0187 %If there are no compartment names then use compartment id as name
+0188 if all(cellfun(@isempty,compartmentNames))
+0189     compartmentNames=compartmentIDs;
+0190 end
+0191 
+0192 %Retrieve info on metabolites, genes, complexes
+0193 metaboliteNames={};
+0194 metaboliteIDs={};
+0195 metaboliteCompartments={};
+0196 metaboliteUnconstrained=[];
+0197 metaboliteFormula={};
+0198 metaboliteInChI={};
+0199 metaboliteMiriams={};
+0200 metaboliteCharges=[];
+0201 
+0202 geneNames={};
+0203 geneIDs={};
+0204 geneMiriams={};
+0205 geneShortNames={};
+0206 proteins={};
+0207 geneCompartments={};
+0208 complexIDs={};
+0209 complexNames={};
+0210 
+0211 %If the file is not a COBRA Toolbox model. According to the format
+0212 %specified in the yeast consensus model both metabolites and genes are a
+0213 %type of 'species'. The metabolites have names starting with 'M_' and genes
+0214 %with 'E_'
+0215 geneSBOs = [];
+0216 metSBOs = [];
+0217 %Regex of compartment names, later to be used to remove from metabolite
+0218 %names if present as suffix.
+0219 regexCompNames = ['\s?\[((' strjoin({modelSBML.compartment.name},')|(') '))\]$'];
+0220 for i=1:numel(modelSBML.species)
+0221     if length(modelSBML.species(i).id)>=2 && strcmpi(modelSBML.species(i).id(1:2),'E_')
+0222         geneNames{numel(geneNames)+1,1}=modelSBML.species(i).name;
+0223 
+0224         %The "E_" is included in the ID. This is because it's only used
+0225         %internally in this file and it makes the matching a little
+0226         %smoother
+0227         geneIDs{numel(geneIDs)+1,1}=modelSBML.species(i).id;
+0228         geneCompartments{numel(geneCompartments)+1,1}=modelSBML.species(i).compartment;
+0229 
+0230         %Get Miriam structure
+0231         if isfield(modelSBML.species(i),'annotation')
+0232             %Get Miriam info
+0233             geneMiriam=parseMiriam(modelSBML.species(i).annotation);
+0234             geneMiriams{numel(geneMiriams)+1,1}=geneMiriam;
+0235         else
+0236             geneMiriams{numel(geneMiriams)+1,1}=[];
+0237         end
+0238 
+0239         %Protein short names (for example ERG10) are saved as SHORT
+0240         %NAME: NAME in the notes-section of metabolites for SBML Level
+0241         %2 and as PROTEIN_ASSOCIATION for each reaction in SBML Level 2
+0242         %COBRA Toolbox format. For now only the SHORT NAME is loaded
+0243         %and no mapping takes place
+0244         if isfield(modelSBML.species(i),'notes')
+0245             geneShortNames{numel(geneShortNames)+1,1}=parseNote(modelSBML.species(i).notes,'SHORT NAME');
+0246         else
+0247             geneShortNames{numel(geneShortNames)+1,1}='';
+0248         end
+0249 
+0250         %Get SBO term
+0251         if isfield(modelSBML.species(i),'sboTerm') && ~(modelSBML.species(i).sboTerm==-1)
+0252             geneSBOs(end+1,1) = modelSBML.species(i).sboTerm;
+0253         end
+0254     elseif length(modelSBML.species(i).id)>=2 && strcmpi(modelSBML.species(i).id(1:3),'Cx_')
+0255         %If it's a complex keep the ID and name
+0256         complexIDs=[complexIDs;modelSBML.species(i).id];
+0257         complexNames=[complexNames;modelSBML.species(i).name];
+0258     else
+0259         %If it is not gene or complex, then it must be a metabolite
+0260         metaboliteNames{numel(metaboliteNames)+1,1}=modelSBML.species(i).name;
+0261         metaboliteIDs{numel(metaboliteIDs)+1,1}=modelSBML.species(i).id;
+0262         metaboliteCompartments{numel(metaboliteCompartments)+1,1}=modelSBML.species(i).compartment;
+0263         metaboliteUnconstrained(numel(metaboliteUnconstrained)+1,1)=modelSBML.species(i).boundaryCondition;
+0264 
+0265         %For each metabolite retrieve the formula and the InChI code if
+0266         %available First add the InChI code and the formula from the
+0267         %InChI. This allows for overwriting the formula by setting the
+0268         %actual formula field
+0269         if ~isempty(modelSBML.species(i).annotation)
+0270             %Get the formula if available
+0271             startString='>InChI=';
+0272             endString='</in:inchi>';
+0273             formStart=strfind(modelSBML.species(i).annotation,startString);
+0274             if isempty(formStart)
+0275                 startString='InChI=';
+0276                 endString='"/>';
+0277             end
+0278             formStart=strfind(modelSBML.species(i).annotation,startString);
+0279             if ~isempty(formStart)
+0280                 formEnd=strfind(modelSBML.species(i).annotation,endString);
+0281                 formEndIndex=find(formEnd>formStart, 1 );
+0282                 formula=modelSBML.species(i).annotation(formStart+numel(startString):formEnd(formEndIndex)-1);
+0283                 metaboliteInChI{numel(metaboliteInChI)+1,1}=formula;
+0284 
+0285                 %The composition is most often present between the
+0286                 %first and second "/" in the model. In some simple
+0287                 %molecules, such as salts, there is no second "/". The
+0288                 %formula is then assumed to be to the end of the string
+0289                 compositionIndexes=strfind(formula,'/');
+0290                 if numel(compositionIndexes)>1
+0291                     metaboliteFormula{numel(metaboliteFormula)+1,1}=...
+0292                         formula(compositionIndexes(1)+1:compositionIndexes(2)-1);
+0293                 else
+0294                     if isscalar(compositionIndexes)
+0295                         %Probably a simple molecule which can have only
+0296                         %one conformation
+0297                         metaboliteFormula{numel(metaboliteFormula)+1,1}=...
+0298                             formula(compositionIndexes(1)+1:numel(formula));
+0299                     else
+0300                         metaboliteFormula{numel(metaboliteFormula)+1,1}='';
+0301                     end
+0302                 end
+0303             elseif isfield(modelSBML.species(i),'fbc_chemicalFormula')
+0304                 metaboliteInChI{numel(metaboliteInChI)+1,1}='';
+0305                 if ~isempty(modelSBML.species(i).fbc_chemicalFormula)
+0306                     %Cannot extract InChi from formula, so remains
+0307                     %empty
+0308                     metaboliteFormula{numel(metaboliteFormula)+1,1}=modelSBML.species(i).fbc_chemicalFormula;
+0309                 else
+0310                     metaboliteFormula{numel(metaboliteFormula)+1,1}='';
+0311                 end
+0312             else
+0313                 metaboliteInChI{numel(metaboliteInChI)+1,1}='';
+0314                 metaboliteFormula{numel(metaboliteFormula)+1,1}='';
+0315             end
+0316 
+0317             %Get Miriam info
+0318             metMiriam=parseMiriam(modelSBML.species(i).annotation);
+0319             metaboliteMiriams{numel(metaboliteMiriams)+1,1}=metMiriam;
+0320         else
+0321             metaboliteInChI{numel(metaboliteInChI)+1,1}='';
+0322             if isfield(modelSBML.species(i),'notes')
+0323                 metaboliteFormula{numel(metaboliteFormula)+1,1}=parseNote(modelSBML.species(i).notes,'FORMULA');
+0324             else
+0325                 metaboliteFormula{numel(metaboliteFormula)+1,1}='';
+0326             end
+0327             metaboliteMiriams{numel(metaboliteMiriams)+1,1}=[];
+0328         end
+0329         if ~isempty(modelSBML.species(i).notes)
+0330             if ~isfield(modelSBML.species(i),'annotation')
+0331                 metaboliteFormula{numel(metaboliteFormula)+1,1}=parseNote(modelSBML.species(i).notes,'FORMULA');
+0332             end
+0333         elseif ~isfield(modelSBML.species(i),'annotation')
+0334             metaboliteFormula{numel(metaboliteFormula)+1,1}='';
+0335         end
+0336         %Get SBO term
+0337         if isfield(modelSBML.species(i),'sboTerm') && ~(modelSBML.species(i).sboTerm==-1)
+0338             metSBOs(end+1,1) = modelSBML.species(i).sboTerm;
+0339         end
+0340     end
+0341 
+0342     %The following lines are executed regardless isSBML2COBRA setting
+0343     if isempty(modelSBML.species(i).id) || ~strcmpi(modelSBML.species(i).id(1:2),'E_')
+0344         if isempty(modelSBML.species(i).id) || ~strcmpi(modelSBML.species(i).id(1:3),'Cx_')
+0345             %Remove trailing [compartment] from metabolite name if present
+0346             metaboliteNames{end,1}=regexprep(metaboliteNames{end,1},regexCompNames,'');
+0347             metaboliteNames{end,1}=metaboliteNames{end,1};
+0348             if isfield(modelSBML.species(i),'fbc_charge')
+0349                 if ~isempty(modelSBML.species(i).fbc_charge) && modelSBML.species(i).isSetfbc_charge
+0350                     metaboliteCharges(numel(metaboliteCharges)+1,1)=double(modelSBML.species(i).fbc_charge);
+0351                 else
+0352                     if isfield(modelSBML.species(i),'notes')
+0353                         if strfind(modelSBML.species(i).notes,'CHARGE')
+0354                             metaboliteCharges(numel(metaboliteCharges)+1,1)=str2double(parseNote(modelSBML.species(i).notes,'CHARGE'));
+0355                         else
+0356                             metaboliteCharges(numel(metaboliteCharges)+1,1)=NaN;
+0357                         end
+0358                     else
+0359                         metaboliteCharges(numel(metaboliteCharges)+1,1)=NaN;
+0360                     end
+0361                 end
+0362             elseif isfield(modelSBML.species(i),'notes')
+0363                 if strfind(modelSBML.species(i).notes,'CHARGE')
+0364                     metaboliteCharges(numel(metaboliteCharges)+1,1)=str2double(parseNote(modelSBML.species(i).notes,'CHARGE'));
+0365                 else
+0366                     metaboliteCharges(numel(metaboliteCharges)+1,1)=NaN;
+0367                 end
+0368             else
+0369                 metaboliteCharges(numel(metaboliteCharges)+1,1)=NaN;
+0370             end
+0371             %Additional information from FBC format Chemical formula
+0372             if isfield(modelSBML.species(i),'fbc_chemicalFormula')
+0373                 if ~isempty(modelSBML.species(i).fbc_chemicalFormula)
+0374                     metaboliteFormula{numel(metaboliteFormula),1}=modelSBML.species(i).fbc_chemicalFormula;
+0375                 end
+0376             end
+0377         end
+0378     end
+0379 end
+0380 
+0381 %Add SBO terms to gene and metabolite miriam fields
+0382 if numel(unique(geneSBOs)) > 1  % don't add if they're all identical
+0383     for i = 1:numel(geneNames)
+0384         geneMiriams{i} = addSBOtoMiriam(geneMiriams{i},geneSBOs(i));
+0385     end
+0386 end
+0387 if numel(unique(metSBOs)) > 1
+0388     for i = 1:numel(metaboliteNames)
+0389         metaboliteMiriams{i} = addSBOtoMiriam(metaboliteMiriams{i},metSBOs(i));
+0390     end
+0391 end
+0392 
+0393 %Retrieve info on reactions
+0394 reactionNames=cell(numel(modelSBML.reaction),1);
+0395 reactionIDs=cell(numel(modelSBML.reaction),1);
+0396 subsystems=cell(numel(modelSBML.reaction),1);
+0397 eccodes=cell(numel(modelSBML.reaction),1);
+0398 eccodes(:,:)=cellstr('');
+0399 rxnconfidencescores=NaN(numel(modelSBML.reaction),1);
+0400 rxnreferences=cell(numel(modelSBML.reaction),1);
+0401 rxnreferences(:,:)=cellstr('');
+0402 rxnnotes=cell(numel(modelSBML.reaction),1);
+0403 rxnnotes(:,:)=cellstr('');
+0404 grRules=cell(numel(modelSBML.reaction),1);
+0405 grRules(:,:)=cellstr('');
+0406 grRulesFromModifier=grRules;
+0407 rxnComps=zeros(numel(modelSBML.reaction),1);
+0408 rxnMiriams=cell(numel(modelSBML.reaction),1);
+0409 reactionReversibility=zeros(numel(modelSBML.reaction),1);
+0410 reactionUB=zeros(numel(modelSBML.reaction),1);
+0411 reactionLB=zeros(numel(modelSBML.reaction),1);
+0412 reactionObjective=zeros(numel(modelSBML.reaction),1);
+0413 
+0414 %Construct the stoichiometric matrix while the reaction info is read
+0415 S=zeros(numel(metaboliteIDs),numel(modelSBML.reaction));
+0416 
+0417 counter=0;
+0418 %If FBC, then bounds have parameter ids defined for the whole model
+0419 if isfield(modelSBML,'parameter')
+0420     parameter.name=cell(numel(modelSBML.parameter),1);
+0421     parameter.name={modelSBML.parameter(:).id}';
+0422     parameter.value={modelSBML.parameter(:).value}';
+0423 end
+0424 
+0425 if isfield(modelSBML.reaction,'sboTerm') && isscalar(unique([modelSBML.reaction.sboTerm]))
+0426     %If all the SBO terms are identical, don't add them to rxnMiriams
+0427     modelSBML.reaction = rmfield(modelSBML.reaction,'sboTerm');
+0428 end
+0429 
+0430 for i=1:numel(modelSBML.reaction)
+0431 
+0432     %Check that the reaction doesn't produce a complex and nothing else. If
+0433     %so, then jump to the next reaction. This is because I get the genes
+0434     %for complexes from the names and not from the reactions that create
+0435     %them. This only applies to the non-COBRA format
+0436     if isscalar(modelSBML.reaction(i).product)
+0437         if length(modelSBML.reaction(i).product(1).species)>=3
+0438             if strcmp(modelSBML.reaction(i).product(1).species(1:3),'Cx_')==true
+0439                 continue;
+0440             end
+0441         end
+0442     end
+0443 
+0444     %It didn't look like a gene complex-forming reaction
+0445     counter=counter+1;
+0446 
+0447     reactionNames{counter}=modelSBML.reaction(i).name;
+0448 
+0449     reactionIDs{counter}=modelSBML.reaction(i).id;
+0450     reactionReversibility(counter)=modelSBML.reaction(i).reversible;
+0451 
+0452     %If model is FBC, first get parameter of bound and then replace it with
+0453     %the correct value. Probably faster with replace(), but this was only
+0454     %introduced in Matlab R2016b
+0455     if isfield(modelSBML.reaction(i),'fbc_lowerFluxBound')
+0456         lb=modelSBML.reaction(i).fbc_lowerFluxBound;
+0457         ub=modelSBML.reaction(i).fbc_upperFluxBound;
+0458         [~,fluxBoundIdx] = ismember({lb,ub},parameter.name);
+0459         reactionLB(counter) = parameter.value{fluxBoundIdx(1)};
+0460         reactionUB(counter) = parameter.value{fluxBoundIdx(2)};
+0461     elseif isfield(modelSBML.reaction(i).kineticLaw,'parameter')
+0462         reactionLB(counter)=modelSBML.reaction(i).kineticLaw.parameter(1).value;
+0463         reactionUB(counter)=modelSBML.reaction(i).kineticLaw.parameter(2).value;
+0464         reactionObjective(counter)=modelSBML.reaction(i).kineticLaw.parameter(3).value;
+0465     else
+0466         if reactionReversibility(counter)==true
+0467             reactionLB(counter)=-inf;
+0468         else
+0469             reactionLB(counter)=0;
+0470         end
+0471         reactionUB(counter)=inf;
+0472         reactionObjective(counter)=0;
+0473     end
+0474 
+0475     %Find the associated gene if available
+0476     %If FBC, get gene association data from corresponding fields
+0477     if isfield(modelSBML.reaction(i),'fbc_geneProductAssociation')
+0478         if ~isempty(modelSBML.reaction(i).fbc_geneProductAssociation) && ~isempty(modelSBML.reaction(i).fbc_geneProductAssociation.fbc_association)
+0479             grRules{counter}=modelSBML.reaction(i).fbc_geneProductAssociation.fbc_association.fbc_association;
+0480         end
+0481     elseif isfield(modelSBML.reaction(i),'notes')
+0482         %This section was previously executed only if isSBML2COBRA is true. Now
+0483         %it will be executed, if 'GENE_ASSOCIATION' is found in
+0484         %modelSBML.reaction(i).notes
+0485         if strfind(modelSBML.reaction(i).notes,'GENE_ASSOCIATION')
+0486             geneAssociation=parseNote(modelSBML.reaction(i).notes,'GENE_ASSOCIATION');
+0487         elseif strfind(modelSBML.reaction(i).notes,'GENE ASSOCIATION')
+0488             geneAssociation=parseNote(modelSBML.reaction(i).notes,'GENE ASSOCIATION');
+0489         else
+0490             geneAssociation='';
+0491         end
+0492         if ~isempty(geneAssociation)
+0493             %This adds the grRules. The gene list and rxnGeneMat are created
+0494             %later
+0495             grRules{counter}=geneAssociation;
+0496         end
+0497     end
+0498     if isempty(grRules{counter}) && ~isempty(modelSBML.reaction(i).modifier)
+0499         rules='';
+0500         for j=1:numel(modelSBML.reaction(i).modifier)
+0501             modifier=modelSBML.reaction(i).modifier(j).species;
+0502             if ~isempty(modifier)
+0503                 if strcmpi(modifier(1:2),'E_')
+0504                     index=find(strcmp(modifier,geneIDs));
+0505                     %This should be unique and in the geneIDs list,
+0506                     %otherwise something is wrong
+0507                     if numel(index)~=1
+0508                         EM=['Could not get the gene association data from reaction ' reactionIDs{i}];
+0509                         dispEM(EM);
+0510                     end
+0511                     if ~isempty(rules)
+0512                         rules=[rules ' or (' geneNames{index} ')'];
+0513                     else
+0514                         rules=['(' geneNames{index} ')'];
+0515                     end
+0516                 elseif strcmp(modifier(1:2),'s_')
+0517                     index=find(strcmp(modifier,metaboliteIDs));
+0518                     %This should be unique and in the geneIDs list,
+0519                     %otherwise something is wrong
+0520                     if numel(index)~=1
+0521                         EM=['Could not get the gene association data from reaction ' reactionIDs{i}];
+0522                         dispEM(EM);
+0523                     end
+0524                     if ~isempty(rules)
+0525                         rules=[rules ' or (' metaboliteIDs{index} ')'];
+0526                     else
+0527                         rules=['(' metaboliteIDs{index} ')'];
+0528                     end
+0529                 else
+0530                     %It seems to be a complex. Add the corresponding
+0531                     %genes from the name of the complex (not the
+0532                     %reaction that creates it)
+0533                     index=find(strcmp(modifier,complexIDs));
+0534                     if isscalar(index)
+0535                         if ~isempty(rules)
+0536                             rules=[rules ' or (' strrep(complexNames{index},':',' and ') ')'];
+0537                         else
+0538                             rules=['(' strrep(complexNames{index},':',' and ') ')'];
+0539                         end
+0540                     else
+0541                         %Could not find a complex
+0542                         EM=['Could not get the gene association data from reaction ' reactionIDs{i}];
+0543                         dispEM(EM);
+0544                     end
+0545                 end
+0546             end
+0547         end
+0548         grRules{counter}=rules;
+0549         grRulesFromModifier{counter}=rules;%Backup copy for grRules, useful to parse Yeast 7.6
+0550     end
+0551 
+0552     %Add reaction compartment
+0553     if isfield(modelSBML.reaction(i),'compartment')
+0554         if ~isempty(modelSBML.reaction(i).compartment)
+0555             rxnComp=modelSBML.reaction(i).compartment;
+0556         else
+0557             rxnComp='';
+0558         end
+0559     elseif isfield(modelSBML.reaction(i),'notes')
+0560         rxnComp=parseNote(modelSBML.reaction(i).notes,'COMPARTMENT');
+0561     end
+0562     if ~isempty(rxnComp)
+0563         %Find it in the compartment list
+0564         [~, J]=ismember(rxnComp,compartmentIDs);
+0565         rxnComps(counter)=J;
+0566     end
+0567 
+0568 
+0569     miriamStruct=parseMiriam(modelSBML.reaction(i).annotation);
+0570     rxnMiriams{counter}=miriamStruct;
+0571     if isfield(modelSBML.reaction(i),'notes')
+0572         subsystems{counter,1}=cellstr(parseNote(modelSBML.reaction(i).notes,'SUBSYSTEM'));
+0573         subsystems{counter,1}(cellfun('isempty',subsystems{counter,1})) = [];
+0574         if strfind(modelSBML.reaction(i).notes,'Confidence Level')
+0575             confScore = parseNote(modelSBML.reaction(i).notes,'Confidence Level');
+0576             if isempty(confScore)
+0577                 confScore = 0;
+0578             end
+0579             rxnconfidencescores(counter)=str2double(confScore);
+0580         end
+0581         rxnreferences{counter,1}=parseNote(modelSBML.reaction(i).notes,'AUTHORS');
+0582         rxnnotes{counter,1}=parseNote(modelSBML.reaction(i).notes,'NOTES');
+0583     end
+0584 
+0585     %Get SBO terms
+0586     if isfield(modelSBML.reaction(i),'sboTerm') && ~(modelSBML.reaction(i).sboTerm==-1)
+0587         rxnMiriams{counter} = addSBOtoMiriam(rxnMiriams{counter}, modelSBML.reaction(i).sboTerm);
+0588     end
+0589 
+0590     %Get ec-codes
+0591     eccode='';
+0592     if ~isempty(modelSBML.reaction(i).annotation)
+0593         if strfind(modelSBML.reaction(i).annotation,'urn:miriam:ec-code')
+0594             eccode=parseAnnotation(modelSBML.reaction(i).annotation,'urn:miriam:',':','ec-code');
+0595         elseif strfind(modelSBML.reaction(i).annotation,'http://identifiers.org/ec-code')
+0596             eccode=parseAnnotation(modelSBML.reaction(i).annotation,'http://identifiers.org/','/','ec-code');
+0597         elseif strfind(modelSBML.reaction(i).annotation,'https://identifiers.org/ec-code')
+0598             eccode=parseAnnotation(modelSBML.reaction(i).annotation,'https://identifiers.org/','/','ec-code');
+0599         end
+0600     elseif isfield(modelSBML.reaction(i),'notes')
+0601         if strfind(modelSBML.reaction(i).notes,'EC Number')
+0602             eccode=[eccode parseNote(modelSBML.reaction(i).notes,'EC Number')];
+0603         elseif strfind(modelSBML.reaction(i).notes,'PROTEIN_CLASS')
+0604             eccode=[eccode parseNote(modelSBML.reaction(i).notes,'PROTEIN_CLASS')];
+0605         end
+0606     end
+0607     eccodes{counter}=eccode;
+0608 
+0609     %Add all reactants
+0610     for j=1:numel(modelSBML.reaction(i).reactant)
+0611         %Get the index of the metabolite in metaboliteIDs. External
+0612         %metabolites will be removed at a later stage
+0613         metIndex=find(strcmp(modelSBML.reaction(i).reactant(j).species,metaboliteIDs),1);
+0614         if isempty(metIndex)
+0615             EM=['Could not find metabolite ' modelSBML.reaction(i).reactant(j).species ' in reaction ' reactionIDs{counter}];
+0616             dispEM(EM);
+0617         end
+0618         S(metIndex,counter)=S(metIndex,counter)+modelSBML.reaction(i).reactant(j).stoichiometry*-1;
+0619     end
+0620 
+0621     %Add all products
+0622     for j=1:numel(modelSBML.reaction(i).product)
+0623         %Get the index of the metabolite in metaboliteIDs.
+0624         metIndex=find(strcmp(modelSBML.reaction(i).product(j).species,metaboliteIDs),1);
+0625         if isempty(metIndex)
+0626             EM=['Could not find metabolite ' modelSBML.reaction(i).product(j).species ' in reaction ' reactionIDs{counter}];
+0627             dispEM(EM);
+0628         end
+0629         S(metIndex,counter)=S(metIndex,counter)+modelSBML.reaction(i).product(j).stoichiometry;
+0630     end
+0631 end
+0632 
+0633 %if FBC, objective function is separately defined. Multiple objective
+0634 %functions can be defined, one is set as active
+0635 if isfield(modelSBML, 'fbc_activeObjective')
+0636     obj=modelSBML.fbc_activeObjective;
+0637     for i=1:numel(modelSBML.fbc_objective)
+0638         if strcmp(obj,modelSBML.fbc_objective(i).fbc_id)
+0639             if ~isempty(modelSBML.fbc_objective(i).fbc_fluxObjective)
+0640                 rxn=modelSBML.fbc_objective(i).fbc_fluxObjective.fbc_reaction;
+0641                 idx=ismember(reactionIDs,rxn);
+0642                 reactionObjective(idx)=modelSBML.fbc_objective(i).fbc_fluxObjective.fbc_coefficient;
+0643             end
+0644         end
+0645     end
+0646 end
+0647 
+0648 %subSystems can be stored as groups instead of in annotations
+0649 if isfield(modelSBML,'groups_group')
+0650     for i=1:numel(modelSBML.groups_group)
+0651         groupreactions={modelSBML.groups_group(i).groups_member(:).groups_idRef};
+0652         [~, idx] = ismember(groupreactions, reactionIDs);
+0653         if any(idx)
+0654             for j=1:numel(idx)
+0655                 if isempty(subsystems{idx(j)}) % First subsystem
+0656                     subsystems{idx(j)} = {modelSBML.groups_group(i).groups_name};
+0657                 else % Consecutive subsystems: concatenate
+0658                     subsystems{idx(j)} = horzcat(subsystems{idx(j)}, modelSBML.groups_group(i).groups_name);
+0659                 end
+0660             end
+0661         end
+0662     end
+0663 end
+0664 
+0665 %Shrink the structures if complex-forming reactions had to be skipped
+0666 reactionNames=reactionNames(1:counter);
+0667 reactionIDs=reactionIDs(1:counter);
+0668 subsystems=subsystems(1:counter);
+0669 eccodes=eccodes(1:counter);
+0670 rxnconfidencescores=rxnconfidencescores(1:counter);
+0671 rxnreferences=rxnreferences(1:counter);
+0672 rxnnotes=rxnnotes(1:counter);
+0673 grRules=grRules(1:counter);
+0674 rxnMiriams=rxnMiriams(1:counter);
+0675 reactionReversibility=reactionReversibility(1:counter);
+0676 reactionUB=reactionUB(1:counter);
+0677 reactionLB=reactionLB(1:counter);
+0678 reactionObjective=reactionObjective(1:counter);
+0679 S=S(:,1:counter);
+0680 
+0681 model.name=modelSBML.name;
+0682 model.id=modelSBML.id;
+0683 model.rxns=reactionIDs;
+0684 model.mets=metaboliteIDs;
+0685 model.S=sparse(S);
+0686 model.lb=reactionLB;
+0687 model.ub=reactionUB;
+0688 model.rev=reactionReversibility;
+0689 model.c=reactionObjective;
+0690 model.b=zeros(numel(metaboliteIDs),1);
+0691 model.comps=compartmentIDs;
+0692 model.compNames=compartmentNames;
+0693 model.rxnConfidenceScores=rxnconfidencescores;
+0694 model.rxnReferences=rxnreferences;
+0695 model.rxnNotes=rxnnotes;
+0696 
+0697 %Load annotation if available. If there are several authors, only the first
+0698 %author credentials are imported
+0699 if isfield(modelSBML,'annotation')
+0700     endString='</';
+0701     I=strfind(modelSBML.annotation,endString);
+0702     J=strfind(modelSBML.annotation,'<vCard:Family>');
+0703     if any(J)
+0704         model.annotation.familyName=modelSBML.annotation(J(1)+14:I(find(I>J(1),1))-1);
+0705     end
+0706     J=strfind(modelSBML.annotation,'<vCard:Given>');
+0707     if any(J)
+0708         model.annotation.givenName=modelSBML.annotation(J(1)+13:I(find(I>J(1),1))-1);
+0709     end
+0710     J=strfind(modelSBML.annotation,'<vCard:EMAIL>');
+0711     if any(J)
+0712         model.annotation.email=modelSBML.annotation(J(1)+13:I(find(I>J(1),1))-1);
+0713     end
+0714     J=strfind(modelSBML.annotation,'<vCard:Orgname>');
+0715     if any(J)
+0716         model.annotation.organization=modelSBML.annotation(J(1)+15:I(find(I>J(1),1))-1);
+0717     end
+0718     endString='"/>';
+0719     I=strfind(modelSBML.annotation,endString);
+0720     if strfind(modelSBML.annotation,'"urn:miriam:')
+0721         J=strfind(modelSBML.annotation,'"urn:miriam:');
+0722         if any(J)
+0723             model.annotation.taxonomy=modelSBML.annotation(J+12:I(find(I>J,1))-1);
+0724         end
+0725     else
+0726         J=strfind(modelSBML.annotation,'"http://identifiers.org/');
+0727         if any(J)
+0728             I = I(find(I>J,1))-1;
+0729             J = J(find(J<I,1))+24;
+0730             model.annotation.taxonomy=modelSBML.annotation(J:I);
+0731         else
+0732             J=strfind(modelSBML.annotation,'"https://identifiers.org/');
+0733             if any(J)
+0734                 I = I(find(I>J,1))-1;
+0735                 J = J(find(J<I,1))+25;
+0736                 model.annotation.taxonomy=modelSBML.annotation(J:I);
+0737             end
+0738         end
+0739     end
+0740 end
+0741 if isfield(modelSBML,'notes')
+0742     startString=strfind(modelSBML.notes,'xhtml">');
+0743     endString=strfind(modelSBML.notes,'</body>');
+0744     if any(startString) && any(endString)
+0745         model.annotation.note=modelSBML.notes(startString(1)+7:endString-1);
+0746         model.annotation.note=regexprep(model.annotation.note,'<p.*?>|</p.*?>','');
+0747         model.annotation.note=strtrim(model.annotation.note);
+0748         if regexp(model.annotation.note,'This file was generated using the exportModel function in RAVEN Toolbox \d\.\d and OutputSBML in libSBML')
+0749             model.annotation=rmfield(model.annotation,'note'); % Default note added when running exportModel
+0750         end
+0751     end
+0752 end
+0753 
+0754 if any(~cellfun(@isempty,compartmentOutside))
+0755     model.compOutside=compartmentOutside;
+0756 end
+0757 
+0758 model.rxnNames=reactionNames;
+0759 model.metNames=metaboliteNames;
+0760 
+0761 %Match the compartments for metabolites
+0762 [~, J]=ismember(metaboliteCompartments,model.comps);
+0763 model.metComps=J;
+0764 
+0765 %If any genes have been loaded (only for the new format)
+0766 if ~isempty(geneNames)
+0767     %In some rare cases geneNames may not necessarily be used in grRules.
+0768     %That is true for Yeast 7.6. It's therefore important to change gene
+0769     %systematic names to geneIDs in sophisticated way. Gene systematic
+0770     %names are not unique, since exactly the same name may be in different
+0771     %compartments
+0772     if all(cellfun(@isempty,strfind(grRules,geneNames{1})))
+0773         geneShortNames=geneNames;
+0774         %geneShortNames contain compartments as well, so these are removed
+0775         geneShortNames=regexprep(geneShortNames,' \[.+$','');
+0776         %grRules obtained from modifier fields contain geneNames. These are
+0777         %changed into geneIDs. grRulesFromModifier is a good way to have
+0778         %geneIDs and rxns association when it's important to resolve
+0779         %systematic name ambiguities
+0780         grRulesFromModifier=regexprep(regexprep(grRulesFromModifier,'\[|\]','_'),regexprep(geneNames,'\[|\]','_'),geneIDs);
+0781         grRules=regexprep(regexprep(grRules,'\[|\]','_'),regexprep(geneNames,'\[|\]','_'),geneIDs);
+0782 
+0783         %Yeast 7.6 contains several metabolites, which were used in gene
+0784         %associations. For that reason, the list of species ID is created
+0785         %and we then check whether any of them have kegg.genes annotation
+0786         %thereby obtaining systematic gene names
+0787         geneShortNames=vertcat(geneShortNames,metaboliteNames);
+0788         geneIDs=vertcat(geneIDs,metaboliteIDs);
+0789         geneSystNames=extractMiriam(vertcat(geneMiriams,metaboliteMiriams),'kegg.genes');
+0790         geneCompartments=vertcat(geneCompartments,metaboliteCompartments);
+0791         geneMiriams=vertcat(geneMiriams,metaboliteMiriams);
+0792 
+0793         %Now we retain information for only these entries, which have
+0794         %kegg.genes annotation
+0795         geneShortNames=geneShortNames(~cellfun('isempty',geneSystNames));
+0796         geneIDs=geneIDs(~cellfun('isempty',geneSystNames));
+0797         geneSystNames=geneSystNames(~cellfun('isempty',geneSystNames));
+0798         geneCompartments=geneCompartments(~cellfun('isempty',geneSystNames));
+0799         geneMiriams=geneMiriams(~cellfun('isempty',geneSystNames));
+0800         %Now we reorder geneIDs and geneSystNames by geneSystNames string
+0801         %length
+0802         geneNames=geneIDs;%Backuping geneIDs, since we need unsorted order for later
+0803         [~, Indx] = sort(cellfun('size', geneSystNames, 2), 'descend');
+0804         geneIDs = geneIDs(Indx);
+0805         geneSystNames = geneSystNames(Indx);
+0806         for i=1:numel(geneSystNames)
+0807             for j=1:numel(grRules)
+0808                 if strfind(grRules{j},geneSystNames{i})
+0809                     if ~isempty(grRules{j})
+0810                         if sum(ismember(geneSystNames,geneSystNames{i}))==1
+0811                             grRules{j}=regexprep(grRules{j},geneSystNames{i},geneIDs{i});
+0812                         elseif sum(ismember(geneSystNames,geneSystNames{i}))>1
+0813                             counter=0;
+0814                             ovrlpIDs=geneIDs(ismember(geneSystNames,geneSystNames{i}));
+0815                             for k=1:numel(ovrlpIDs)
+0816                                 if strfind(grRulesFromModifier{j},ovrlpIDs{k})
+0817                                     counter=counter+1;
+0818                                     grRules{j}=regexprep(grRules{j},geneSystNames{i},ovrlpIDs{k});
+0819                                 end
+0820                                 if counter>1
+0821                                     EM=['Gene association is ambiguous for reaction ' modelSBML.reaction(j).id];
+0822                                     dispEM(EM);
+0823                                 end
+0824                             end
+0825                         end
+0826                     end
+0827                 end
+0828             end
+0829         end
+0830     end
+0831     model.genes=geneNames;
+0832     model.grRules=grRules;
+0833     [grRules,rxnGeneMat] = standardizeGrRules(model,true);
+0834     model.grRules = grRules;
+0835     model.rxnGeneMat = rxnGeneMat;
+0836 
+0837     %Match the compartments for genes
+0838     [~, J]=ismember(geneCompartments,model.comps);
+0839     model.geneComps=J;
+0840 else
+0841     if ~all(cellfun(@isempty,grRules))
+0842         %If fbc_geneProduct exists, follow the specified gene order, such
+0843         %that matching geneShortNames in function below will work
+0844         if isfield(modelSBML,'fbc_geneProduct')
+0845             genes={modelSBML.fbc_geneProduct.fbc_id};
+0846 
+0847             %Get gene Miriams if they were not retrieved above (this occurs
+0848             %when genes are stored as fbc_geneProduct instead of species)
+0849             if isempty(geneMiriams)
+0850                 geneMiriams = cell(numel(genes),1);
+0851                 if isfield(modelSBML.fbc_geneProduct,'sboTerm') && isscalar(unique([modelSBML.fbc_geneProduct.sboTerm]))
+0852                     %If all the SBO terms are identical, don't add them to geneMiriams
+0853                     modelSBML.fbc_geneProduct = rmfield(modelSBML.fbc_geneProduct,'sboTerm');
+0854                 end
+0855                 for i = 1:numel(genes)
+0856                     geneMiriams{i}=parseMiriam(modelSBML.fbc_geneProduct(i).annotation);
+0857                     if isfield(modelSBML.fbc_geneProduct(i),'sboTerm') && ~(modelSBML.fbc_geneProduct(i).sboTerm==-1)
+0858                         geneMiriams{i} = addSBOtoMiriam(geneMiriams{i},modelSBML.fbc_geneProduct(i).sboTerm);
+0859                     end
+0860                 end
+0861             end
+0862             proteins={modelSBML.fbc_geneProduct.fbc_name};
+0863         else
+0864             genes=getGenesFromGrRules(grRules);
+0865         end
+0866         model.genes=genes;
+0867         model.grRules=grRules;
+0868         [grRules,rxnGeneMat] = standardizeGrRules(model,true);
+0869         model.grRules = grRules;
+0870         model.rxnGeneMat = rxnGeneMat;
+0871     end
+0872 end
+0873 
+0874 if all(cellfun(@isempty,geneShortNames))
+0875     if isfield(modelSBML,'fbc_geneProduct')
+0876         for i=1:numel(genes)
+0877             if ~isempty(modelSBML.fbc_geneProduct(i).fbc_label)
+0878                 geneShortNames{i,1}=modelSBML.fbc_geneProduct(i).fbc_label;
+0879             elseif ~isempty(modelSBML.fbc_geneProduct(i).fbc_name)
+0880                 geneShortNames{i,1}=modelSBML.fbc_geneProduct(i).fbc_name;
+0881             else
+0882                 geneShortNames{i,1}='';
+0883             end
+0884         end
+0885     end
+0886 end
+0887 
+0888 %If any InChIs have been loaded
+0889 if any(~cellfun(@isempty,metaboliteInChI))
+0890     model.inchis=metaboliteInChI;
+0891 end
+0892 
+0893 %If any formulas have been loaded
+0894 if any(~cellfun(@isempty,metaboliteFormula))
+0895     model.metFormulas=metaboliteFormula;
+0896 end
+0897 
+0898 %If any charges have been loaded
+0899 if ~isempty(metaboliteCharges)
+0900     model.metCharges=metaboliteCharges;
+0901 end
+0902 
+0903 %If any gene short names have been loaded
+0904 if any(~cellfun(@isempty,geneShortNames))
+0905     model.geneShortNames=geneShortNames;
+0906 end
+0907 
+0908 %If any Miriam strings for compartments have been loaded
+0909 if any(~cellfun(@isempty,compartmentMiriams))
+0910     model.compMiriams=compartmentMiriams;
+0911 end
+0912 
+0913 %If any Miriam strings for metabolites have been loaded
+0914 if any(~cellfun(@isempty,metaboliteMiriams))
+0915     model.metMiriams=metaboliteMiriams;
+0916 end
+0917 
+0918 %If any subsystems have been loaded
+0919 if any(~cellfun(@isempty,subsystems))
+0920     model.subSystems=subsystems;
+0921 end
+0922 if any(rxnComps)
+0923     if all(rxnComps)
+0924         model.rxnComps=rxnComps;
+0925     else
+0926         if supressWarnings==false
+0927             EM='The compartments for the following reactions could not be matched. Ignoring reaction compartment information';
+0928             dispEM(EM,false,model.rxns(rxnComps==0));
+0929         end
+0930     end
+0931 end
+0932 
+0933 %If any ec-codes have been loaded
+0934 if any(~cellfun(@isempty,eccodes))
+0935     model.eccodes=eccodes;
+0936 end
+0937 
+0938 %If any Miriam strings for reactions have been loaded
+0939 if any(~cellfun(@isempty,rxnMiriams))
+0940     model.rxnMiriams=rxnMiriams;
+0941 end
+0942 
+0943 %If any Miriam strings for genes have been loaded
+0944 if any(~cellfun(@isempty,geneMiriams))
+0945     model.geneMiriams=geneMiriams;
+0946 end
+0947 
+0948 %If any protein strings have been loaded
+0949 if any(~cellfun(@isempty,proteins))
+0950     proteins = reshape(proteins,[],1);
+0951     model.proteins=proteins;
+0952 end
+0953 
+0954 model.unconstrained=metaboliteUnconstrained;
+0955 
+0956 %Convert SBML IDs back into their original strings. Here we are using part
+0957 %from convertSBMLID, originating from the COBRA Toolbox
+0958 model.rxns=regexprep(model.rxns,'__([0-9]+)__','${char(str2num($1))}');
+0959 model.mets=regexprep(model.mets,'__([0-9]+)__','${char(str2num($1))}');
+0960 model.comps=regexprep(model.comps,'__([0-9]+)__','${char(str2num($1))}');
+0961 model.grRules=regexprep(model.grRules,'__([0-9]+)__','${char(str2num($1))}');
+0962 model.genes=regexprep(model.genes,'__([0-9]+)__','${char(str2num($1))}');
+0963 model.id=regexprep(model.id,'__([0-9]+)__','${char(str2num($1))}');
+0964 
+0965 if removePrefix
+0966     [model, hasChanged]=removeIdentifierPrefix(model);
+0967     dispEM(['The following fields have prefixes removed from all entries. '...
+0968     'If this is undesired, run importModel with removePrefix as false. Example: '...
+0969     'importModel(''filename.xml'',[],false);'],false,hasChanged)
+0970 end
+0971 
+0972 %Remove unused fields
+0973 if isempty(model.annotation)
+0974     model=rmfield(model,'annotation');
+0975 end
+0976 if isempty(model.compOutside)
+0977     model=rmfield(model,'compOutside');
+0978 end
+0979 if isempty(model.compMiriams)
+0980     model=rmfield(model,'compMiriams');
+0981 end
+0982 if isempty(model.rxnComps)
+0983     model=rmfield(model,'rxnComps');
+0984 end
+0985 if isempty(model.grRules)
+0986     model=rmfield(model,'grRules');
+0987 end
+0988 if isempty(model.rxnGeneMat)
+0989     model=rmfield(model,'rxnGeneMat');
+0990 end
+0991 if isempty(model.subSystems)
+0992     model=rmfield(model,'subSystems');
+0993 else
+0994     model.subSystems(cellfun(@isempty,subsystems))={{''}};
+0995     % If all subSystems have single entries, then unnest them
+0996     if all(cellfun(@(x) iscell(x) && isscalar(x), model.subSystems))
+0997         model.subSystems = transpose([model.subSystems{:}]);
+0998     end
+0999 end
+1000 if isempty(model.eccodes)
+1001     model=rmfield(model,'eccodes');
+1002 end
+1003 if isempty(model.rxnMiriams)
+1004     model=rmfield(model,'rxnMiriams');
+1005 end
+1006 if cellfun(@isempty,model.rxnNotes)
+1007     model=rmfield(model,'rxnNotes');
+1008 end
+1009 if cellfun(@isempty,model.rxnReferences)
+1010     model=rmfield(model,'rxnReferences');
+1011 end
+1012 if isempty(model.rxnConfidenceScores) || all(isnan(model.rxnConfidenceScores))
+1013     model=rmfield(model,'rxnConfidenceScores');
+1014 end
+1015 if isempty(model.genes)
+1016     model=rmfield(model,'genes');
+1017 elseif isrow(model.genes)
+1018     model.genes=transpose(model.genes);
+1019 end
+1020 if isempty(model.geneComps)
+1021     model=rmfield(model,'geneComps');
+1022 end
+1023 if isempty(model.geneMiriams)
+1024     model=rmfield(model,'geneMiriams');
+1025 end
+1026 if isempty(model.geneShortNames)
+1027     model=rmfield(model,'geneShortNames');
+1028 end
+1029 if isempty(model.proteins)
+1030     model=rmfield(model,'proteins');
+1031 end
+1032 if isempty(model.inchis)
+1033     model=rmfield(model,'inchis');
+1034 end
+1035 if isempty(model.metFormulas)
+1036     model=rmfield(model,'metFormulas');
+1037 end
+1038 if isempty(model.metMiriams)
+1039     model=rmfield(model,'metMiriams');
+1040 end
+1041 if ~any(model.metCharges)
+1042     model=rmfield(model,'metCharges');
+1043 end
+1044 
+1045 %This just removes the grRules if no genes have been loaded
+1046 if ~isfield(model,'genes') && isfield(model,'grRules')
+1047     model=rmfield(model,'grRules');
+1048 end
+1049 
+1050 %Print warnings about bad structure
+1051 if supressWarnings==false
+1052     checkModelStruct(model,false);
+1053 end
+1054 
+1055 if removeExcMets==true
+1056     model=simplifyModel(model);
+1057 end
+1058 end
+1059 
+1060 function fieldContent=parseNote(searchString,fieldName)
+1061 %The function obtains the particular information from 'notes' field, using
+1062 %fieldName as the dummy string
+1063 
+1064 fieldContent='';
+1065 
+1066 if strfind(searchString,fieldName)
+1067     [~,targetString] = regexp(searchString,['<p>' fieldName '.*?</p>'],'tokens','match');
+1068     targetString=regexprep(targetString,'<p>|</p>','');
+1069     targetString=regexprep(targetString,[fieldName, ':'],'');
+1070     for i=1:numel(targetString)
+1071         fieldContent=[fieldContent ';' strtrim(targetString{1,i})];
+1072     end
+1073     fieldContent=regexprep(fieldContent,'^;|;$','');
+1074 else
+1075     fieldContent='';
+1076 end
+1077 end
+1078 
+1079 function fieldContent=parseAnnotation(searchString,startString,midString,fieldName)
+1080 
+1081 fieldContent='';
+1082 
+1083 %Removing whitespace characters from the ending strings, which may occur in
+1084 %several cases
+1085 searchString=regexprep(searchString,'" />','"/>');
+1086 [~,targetString] = regexp(searchString,['<rdf:li rdf:resource="' startString fieldName midString '.*?"/>'],'tokens','match');
+1087 targetString=regexprep(targetString,'<rdf:li rdf:resource="|"/>','');
+1088 targetString=regexprep(targetString,startString,'');
+1089 targetString=regexprep(targetString,[fieldName midString],'');
+1090 
+1091 for i=1:numel(targetString)
+1092     fieldContent=[fieldContent ';' strtrim(targetString{1,i})];
+1093 end
+1094 
+1095 fieldContent=regexprep(fieldContent,'^;|;$','');
+1096 end
+1097 
+1098 function miriamStruct=parseMiriam(searchString)
+1099 %Generates miriam structure from annotation field
+1100 
+1101 %Finding whether miriams are written in the old or the new way
+1102 if strfind(searchString,'urn:miriam:')
+1103     startString='urn:miriam:';
+1104 elseif strfind(searchString,'http://identifiers.org/')
+1105     startString='http://identifiers.org/';
+1106 elseif strfind(searchString,'https://identifiers.org/')
+1107     startString='https://identifiers.org/';
+1108 else
+1109     miriamStruct=[];
+1110     return;
+1111 end
+1112 
+1113 miriamStruct=[];
+1114 
+1115 searchString=regexprep(searchString,'" />','"/>');
+1116 [~,targetString] = regexp(searchString,'<rdf:li rdf:resource=".*?"/>','tokens','match');
+1117 targetString=regexprep(targetString,'<rdf:li rdf:resource="|"/>','');
+1118 targetString=regexprep(targetString,startString,'');
+1119 
+1120 fwdslash  = contains(targetString,'/');
+1121 midString = cell(numel(targetString),1);
+1122 midString(fwdslash) = {'/'};
+1123 midString(~fwdslash) = {':'};
+1124 
+1125 counter=0;
+1126 for i=1:numel(targetString)
+1127     if isempty(regexp(targetString{1,i},'inchi|ec-code', 'once'))
+1128         counter=counter+1;
+1129         miriamStruct.name{counter,1} = regexprep(targetString{1,i},[midString{i} '.+'],'','once');
+1130         miriamStruct.value{counter,1} = regexprep(targetString{1,i},[miriamStruct.name{counter,1} midString{i}],'','once');
+1131         miriamStruct.name{counter,1} = regexprep(miriamStruct.name{counter,1},'^obo\.','');
+1132     end
+1133 end
+1134 end
+1135 
+1136 function miriam = addSBOtoMiriam(miriam,sboTerm)
+1137 %Appends SBO term to miriam structure
+1138 
+1139 sboTerm = {['SBO:' sprintf('%07u',sboTerm)]};  % convert to proper format
+1140 if isempty(miriam)
+1141     miriam.name = {'sbo'};
+1142     miriam.value = sboTerm;
+1143 elseif any(strcmp('sbo',miriam.name))
+1144     currSbo = strcmp('sbo',miriam.name);
+1145     miriam.value(currSbo) = sboTerm;
+1146 else
+1147     miriam.name(end+1) = {'sbo'};
+1148     miriam.value(end+1) = sboTerm;
+1149 end
+1150 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/io/index.html b/doc/io/index.html new file mode 100644 index 000000000..894f6b1fc --- /dev/null +++ b/doc/io/index.html @@ -0,0 +1,29 @@ + + + + Index for Directory io + + + + + + + + + + +
< Master indexIndex for io >
+ +

Index for io

+ +

Matlab files in this directory:

+ +
 SBMLFromExcelSBMLFromExcel
 addJavaPathsaddJavaPaths
 checkFileExistencecheckFileExistence
 cleanSheetcleanSheet
 closeModelcloseModel
 exportForGitexportForGit
 exportModelexportModel
 exportModelToSIFexportModelToSIF
 exportToExcelFormatexportToExcelFormat
 exportToTabDelimitedexportToTabDelimited
 getFullPathgetFullPath - Get absolute canonical path of a file or folder
 getMD5HashgetMD5Hash
 getToolboxVersiongetToolboxVersion
 importExcelModelimportExcelModel
 importModelimportModel
 loadSheetloadSheet
 loadWorkbookloadWorkbook
 readYAMLmodelreadYAMLmodel
 sortIdentifiersexportModel
 startupAdd the Java Paths at startup in order to be ready for use if the Toolbox is on the path
 writeSheetwriteSheet
 writeYAMLmodelwriteYAMLmodel
+ + + + +
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/io/loadSheet.html b/doc/io/loadSheet.html new file mode 100644 index 000000000..0504929b9 --- /dev/null +++ b/doc/io/loadSheet.html @@ -0,0 +1,130 @@ + + + + Description of loadSheet + + + + + + + + + +
Home > io > loadSheet.m
+ + + +

loadSheet +

+ +

PURPOSE ^

+
loadSheet
+ +

SYNOPSIS ^

+
function [raw, flag]=loadSheet(workbook, sheet)
+ +

DESCRIPTION ^

+
 loadSheet
+   Loads an Excel sheet into a cell matrix using the Java library Apache POI
+
+   workbook    Workbook object representing the Excel file
+   sheet       name of the sheet (optional, default first sheet)
+
+   raw         cell array with the data in the sheet
+   flag        0 if everything worked, -1 if it didn't
+
+ Usage: [raw, flag]=loadSheet(workbook, sheet)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + + + +

SOURCE CODE ^

+
0001 % loadSheet
+0002 %   Loads an Excel sheet into a cell matrix using the Java library Apache POI
+0003 %
+0004 %   workbook    Workbook object representing the Excel file
+0005 %   sheet       name of the sheet (optional, default first sheet)
+0006 %
+0007 %   raw         cell array with the data in the sheet
+0008 %   flag        0 if everything worked, -1 if it didn't
+0009 %
+0010 % Usage: [raw, flag]=loadSheet(workbook, sheet)
+0011 
+0012 function [raw, flag]=loadSheet(workbook, sheet)
+0013 if nargin<2
+0014     sheet=[];
+0015 end
+0016 flag=0;
+0017 raw={};
+0018 
+0019 if any(sheet)
+0020     sh=workbook.getSheet(sheet);
+0021 else
+0022     sh=workbook.getSheetAt(0);
+0023 end
+0024 if isempty(sh)
+0025     flag=-1;
+0026     return;
+0027 end
+0028 
+0029 lastRow=sh.getLastRowNum();
+0030 wasEmpty=false(lastRow+1,1);
+0031 raw=cell(lastRow+1,0); %Allocate space for the cell array. The number of columns isn't know yet, as it's saved row-by-row
+0032 for i=0:lastRow
+0033     row=sh.getRow(i);
+0034     %Sometimes the last rows only contain formatting (or some other weird
+0035     %Excel thing). Ignore such empty rows. Note the +1 to deal with that
+0036     %Matlab indexing starts at 1
+0037     if isempty(row)
+0038         wasEmpty(i+1)=true;
+0039         continue;
+0040     end
+0041     lastCol=row.getLastCellNum();
+0042     
+0043     %Adjust the size of the cell array if needed
+0044     if (lastCol+1)>size(raw,2)
+0045         raw=[raw cell(lastRow+1,lastCol+1-size(raw,2))];
+0046     end
+0047     
+0048     %Loop over the columns
+0049     for j=0:lastCol
+0050         c=row.getCell(j,row.RETURN_BLANK_AS_NULL);
+0051         if ~isempty(c)
+0052             %Then decide how to save it depending on the type. First check
+0053             %if it's a formula. If so the cached value should be used
+0054             if c.getCellType()==c.CELL_TYPE_FORMULA
+0055                 type=c.getCachedFormulaResultType();
+0056             else
+0057                 type=c.getCellType();
+0058             end
+0059             
+0060             switch type
+0061                 case c.CELL_TYPE_STRING
+0062                     raw{i+1,j+1}=char(c.getRichStringCellValue().getString());
+0063                 case c.CELL_TYPE_NUMERIC
+0064                     raw{i+1,j+1}=c.getNumericCellValue();
+0065                 case c.CELL_TYPE_BOOLEAN
+0066                     raw{i+1,j+1}=c.getBooleanCellValue();
+0067             end
+0068         end
+0069     end
+0070 end
+0071 
+0072 %Remove empty rows
+0073 raw(wasEmpty,:)=[];
+0074 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/io/loadWorkbook.html b/doc/io/loadWorkbook.html new file mode 100644 index 000000000..945e419a3 --- /dev/null +++ b/doc/io/loadWorkbook.html @@ -0,0 +1,119 @@ + + + + Description of loadWorkbook + + + + + + + + + +
Home > io > loadWorkbook.m
+ + + +

loadWorkbook +

+ +

PURPOSE ^

+
loadWorkbook
+ +

SYNOPSIS ^

+
function workbook=loadWorkbook(fileName,createEmpty)
+ +

DESCRIPTION ^

+
 loadWorkbook
+   Loads an Excel file into a Workbook object using the Java library Apache POI
+
+   fileName    name of the Excel file. If it doesn't exist it will be
+               created
+   createEmpty true if an empty workbook should be created if the file
+               didn't exist (optional, default false)
+
+   workbook    Workbook object representing the Excel file
+
+ Usage: workbook=loadWorkbook(fileName,createEmpty)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function workbook=loadWorkbook(fileName,createEmpty)
+0002 % loadWorkbook
+0003 %   Loads an Excel file into a Workbook object using the Java library Apache POI
+0004 %
+0005 %   fileName    name of the Excel file. If it doesn't exist it will be
+0006 %               created
+0007 %   createEmpty true if an empty workbook should be created if the file
+0008 %               didn't exist (optional, default false)
+0009 %
+0010 %   workbook    Workbook object representing the Excel file
+0011 %
+0012 % Usage: workbook=loadWorkbook(fileName,createEmpty)
+0013 
+0014 if nargin<2
+0015     createEmpty=false;
+0016 end
+0017 
+0018 %Check if the user has MATLAB Text Analytics Toolbox installed, as it comes
+0019 %with its own conflicting version of the required Apache POI files
+0020 if exist('vaderSentimentScores.m')== 2
+0021     error(['MATLAB Text Analytics Toolbox found. This should be uninstalled ' ...
+0022            'if you want to read/write Excel files. See RAVEN GitHub Issues '...
+0023            'page for instructions.'])    
+0024 end
+0025     
+0026 %Adds the required classes to the static Java path if not already added
+0027 addJavaPaths();
+0028 
+0029 %Import required classes from Apache POI
+0030 import org.apache.poi.ss.usermodel.*;
+0031 import org.apache.poi.ss.util.*;
+0032 import java.io.FileInputStream;
+0033 import org.apache.poi.hssf.usermodel.*;
+0034 import org.apache.poi.xssf.usermodel.*;
+0035 
+0036 %Check if the file exists
+0037 if ~isfile(fileName)
+0038     if createEmpty==false
+0039         EM='The Excel file could not be found';
+0040         dispEM(EM);
+0041     else
+0042         %Create an empty workbook
+0043         [~,~,I]=fileparts(fileName);
+0044         if strcmpi(I,'.xls')
+0045             workbook=HSSFWorkbook();
+0046         else
+0047             if strcmpi(I,'.xlsx')
+0048                 workbook=XSSFWorkbook();
+0049             else
+0050                 EM='The file name must end in .xls or .xlsx';
+0051                 dispEM(EM);
+0052             end
+0053         end
+0054     end
+0055 else
+0056     %Opens the workbook. The input stream is needed since it will otherwise
+0057     %keep the file open
+0058     is=FileInputStream(getFullPath(fileName));
+0059     workbook=WorkbookFactory.create(is);
+0060     is.close();
+0061 end
+0062 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/io/readYAMLmodel.html b/doc/io/readYAMLmodel.html new file mode 100644 index 000000000..d1e03747e --- /dev/null +++ b/doc/io/readYAMLmodel.html @@ -0,0 +1,750 @@ + + + + Description of readYAMLmodel + + + + + + + + + +
Home > io > readYAMLmodel.m
+ + + +

readYAMLmodel +

+ +

PURPOSE ^

+
readYAMLmodel
+ +

SYNOPSIS ^

+
function model=readYAMLmodel(fileName, verbose)
+ +

DESCRIPTION ^

+
 readYAMLmodel
+   Reads a yaml file matching (roughly) the cobrapy yaml structure
+
+   Input:
+   fileName    a model file in yaml file format. A dialog window will open
+               if no file name is specified.
+   verbose     set as true to monitor progress (optional, default false)
+
+   Output:
+   model       a model structure
+
+ Usage: model = readYAMLmodel(fileName, verbose)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 function model=readYAMLmodel(fileName, verbose)
+0002 % readYAMLmodel
+0003 %   Reads a yaml file matching (roughly) the cobrapy yaml structure
+0004 %
+0005 %   Input:
+0006 %   fileName    a model file in yaml file format. A dialog window will open
+0007 %               if no file name is specified.
+0008 %   verbose     set as true to monitor progress (optional, default false)
+0009 %
+0010 %   Output:
+0011 %   model       a model structure
+0012 %
+0013 % Usage: model = readYAMLmodel(fileName, verbose)
+0014 if nargin<1 || isempty(fileName)
+0015     [fileName, pathName] = uigetfile({'*.yml;*.yaml'}, 'Please select the model file');
+0016     if fileName == 0
+0017         error('You should select a model file')
+0018     else
+0019         fileName = fullfile(pathName,fileName);
+0020     end
+0021 end
+0022 if nargin < 2
+0023     verbose = false;
+0024 end
+0025 
+0026 if ~isfile(fileName)
+0027     error('Yaml file %s cannot be found', string(fileName));
+0028 end
+0029 
+0030 if verLessThan('matlab','9.9') %readlines introduced 2020b
+0031     fid=fopen(fileName);
+0032     line_raw=cell(1000000,1);
+0033     i=1;
+0034     while ~feof(fid)
+0035         line_raw{i}=fgetl(fid);
+0036         i=i+1;
+0037     end
+0038     line_raw(i:end)=[];
+0039     line_raw=string(line_raw);
+0040     fclose(fid);
+0041 else
+0042     line_raw=readlines(fileName);
+0043 end
+0044 % If entry is broken of multiple lines, concatenate. Assumes at least 6
+0045 % leading spaces to avoid metaData to be concatenated.
+0046 newLine=regexp(line_raw,'^ {6,}([\w\(\)].*)','tokenExtents');
+0047 brokenLine=find(~cellfun('isempty',newLine));
+0048 for i=flip(1:numel(brokenLine))
+0049     extraLine = char(line_raw(brokenLine(i)));
+0050     extraLine = extraLine(newLine{brokenLine(i)}{1}(1):end);
+0051     line_raw{brokenLine(i)-1} = strjoin({line_raw{brokenLine(i)-1},extraLine},' ');
+0052 end
+0053 line_raw(brokenLine)=[];
+0054 
+0055 line_key = regexprep(line_raw,'^ *-? ([^:]+)(:)($| .*)','$1');
+0056 line_key = regexprep(line_key,'(.*!!omap)|(---)|( {4,}.*)','');
+0057 
+0058 line_value = regexprep(line_raw, '.*:$','');
+0059 line_value = regexprep(line_value, '[^":]+: "?(.+)"?$','$1');
+0060 line_value = regexprep(line_value, '(")|(^ {4,}- )','');
+0061 line_value(strcmp(line_value,'''''')) = {''};
+0062 line_value(strcmp(line_value,line_raw)) = {''};
+0063 
+0064 modelFields =   {'id',char();...
+0065                'name',char();...
+0066         'description',char();...
+0067             'version',char();...
+0068                'date',char();...
+0069          'annotation',struct();...
+0070                'rxns',{};...
+0071            'rxnNames',{};...
+0072                'mets',{};...
+0073            'metNames',{};...
+0074                   'S',sparse([]);...
+0075                  'lb',{};... %Changed to double in the end.
+0076                  'ub',{};... %Changed to double in the end.
+0077                 'rev',{};... %Changed to double in the end.
+0078                   'c',[];...
+0079                   'b',cell(0,0);... %Changed to double in the end.
+0080               'genes',cell(0,0);...
+0081             'grRules',cell(0,0);...
+0082          'rxnGeneMat',sparse([]);...
+0083            'rxnComps',cell(0,0);... %Changed to double in the end.
+0084          'subSystems',cell(0,0);...
+0085             'eccodes',cell(0,0);...
+0086          'rxnMiriams',cell(0,0);...
+0087           'rxnDeltaG',{};... %Changed to double in the end.
+0088            'rxnNotes',cell(0,0);...
+0089       'rxnReferences',cell(0,0);...
+0090 'rxnConfidenceScores',cell(0,0);...
+0091            'metComps',cell(0,0);... %Changed to double in the end.
+0092              'inchis',cell(0,0);...
+0093           'metSmiles',cell(0,0);...
+0094         'metFormulas',cell(0,0);...
+0095          'metMiriams',cell(0,0);...
+0096           'metDeltaG',{};... %Changed to double in the end.
+0097          'metCharges',cell(0,0);... %Changed to double in the end.
+0098            'metNotes',cell(0,0);...
+0099               'comps',cell(0,0);...
+0100           'compNames',cell(0,0);...
+0101         'compOutside',cell(0,0);...
+0102           'geneComps',cell(0,0);... %Changed to double in the end.
+0103         'geneMiriams',cell(0,0);...
+0104      'geneShortNames',cell(0,0);...
+0105        'proteins',cell(0,0);...
+0106       'unconstrained',cell(0,0);... %Changed to double in the end.
+0107             'metFrom',cell(0,0);...
+0108             'rxnFrom',cell(0,0)};
+0109 for i=1:size(modelFields,1)
+0110     model.(modelFields{i,1})=modelFields{i,2};
+0111 end
+0112 
+0113 % If GECKO model
+0114 if any(contains(line_key,'geckoLight'))
+0115     isGECKO=true;
+0116     ecFields = {'geckoLight', false;...
+0117                       'rxns', {};...
+0118                       'kcat', {};...
+0119                     'source', cell(0,0);...
+0120                      'notes', cell(0,0);...
+0121                    'eccodes', cell(0,0);...
+0122                      'genes', cell(0,0);...
+0123                    'enzymes', cell(0,0);...
+0124                         'mw', cell(0,0);...
+0125                   'sequence', cell(0,0);...
+0126                      'concs', cell(0,0);...
+0127                  'rxnEnzMat', []};
+0128     for i=1:size(ecFields,1)
+0129         model.ec.(ecFields{i,1})=ecFields{i,2};
+0130     end
+0131     ecGecko=cell(25000,2);      ecGeckoNo=1;
+0132     enzStoich=cell(100000,3);   enzStoichNo=1;
+0133 else
+0134     isGECKO=false;
+0135 end
+0136 
+0137 section = 0;
+0138 metMiriams=cell(100000,3);   metMirNo=1;
+0139 rxnMiriams=cell(100000,3);   rxnMirNo=1;
+0140 geneMiriams=cell(100000,3);  genMirNo=1;
+0141 subSystems=cell(100000,2);   subSysNo=1;
+0142 eccodes=cell(100000,2);      ecCodeNo=1;
+0143 equations=cell(100000,3);    equatiNo=1;
+0144 
+0145 for i=1:numel(line_key)
+0146     tline_raw = line_raw{i};
+0147     tline_key = line_key{i};
+0148     tline_value = line_value{i};
+0149     % import different sections
+0150     switch tline_raw
+0151         case '- metaData:'
+0152             section = 1;
+0153             if verbose
+0154                 fprintf('\t%d\n', section);
+0155             end
+0156             continue % Go to next line
+0157         case '- metabolites:'
+0158             section = 2;
+0159             if verbose
+0160                 fprintf('\t%d\n', section);
+0161             end
+0162             pos=0;
+0163             continue
+0164         case '- reactions:'
+0165             section = 3;
+0166             if verbose
+0167                 fprintf('\t%d\n', section);
+0168             end
+0169             pos=0;
+0170             continue
+0171         case '- genes:'
+0172             section = 4;
+0173             if verbose
+0174                 fprintf('\t%d\n', section);
+0175             end
+0176             pos=0;
+0177             continue
+0178         case '- compartments: !!omap'
+0179             section = 5;
+0180             if verbose
+0181                 fprintf('\t%d\n', section);
+0182             end
+0183             pos=0;
+0184             continue
+0185         case '- ec-rxns:'
+0186             section = 6;
+0187             if verbose
+0188                 fprintf('\t%d\n', section);
+0189             end
+0190             pos=0;
+0191             continue
+0192         case '- ec-enzymes:'
+0193             section = 7;
+0194             if verbose
+0195                 fprintf('\t%d\n', section);
+0196             end
+0197             pos=0;
+0198             continue
+0199     end
+0200 
+0201     % skip over empty keys
+0202     if isempty(tline_raw) || (isempty(tline_key) && contains(tline_raw,'!!omap'))
+0203         continue;
+0204     end
+0205     
+0206     % import metaData
+0207     if section == 1
+0208         switch tline_key
+0209             case {'short_name','id'} %short_name used by human-GEM
+0210                 model.id = tline_value;
+0211             case 'name'
+0212                 model.name = tline_value;                
+0213             case 'full_name' %used by human-GEM
+0214                 model.description = tline_value;
+0215             case 'version'
+0216                 model.version = tline_value;
+0217             case 'date'
+0218                 model.date = tline_value;                
+0219             case 'taxonomy'
+0220                 model.annotation.taxonomy = tline_value;
+0221             case {'description','note'} %description used by human-GEM
+0222                 model.annotation.note = tline_value;
+0223             case 'github'
+0224                 model.annotation.sourceUrl = tline_value;
+0225             case 'sourceUrl'
+0226                 model.annotation.sourceUrl = tline_value;                
+0227             case 'givenName'
+0228                 model.annotation.givenName = tline_value;
+0229             case 'familyName'
+0230                 model.annotation.familyName = tline_value;
+0231             case 'authors'
+0232                 model.annotation.authorList = tline_value;
+0233             case 'email'
+0234                 model.annotation.email = tline_value;
+0235             case 'organization'
+0236                 model.annotation.organization = tline_value;
+0237             case 'geckoLight'
+0238                 if strcmp(tline_value,'true')
+0239                     model.ec.geckoLight = true;
+0240                 end
+0241         end; continue
+0242     end
+0243 
+0244     % import metabolites:
+0245     if section == 2
+0246         switch tline_key
+0247             case 'id'
+0248                 pos = pos + 1;
+0249                 model = readFieldValue(model, 'mets', tline_value,pos);
+0250                 readList=''; miriamKey='';
+0251             case 'name'
+0252                 model = readFieldValue(model, 'metNames', tline_value, pos);
+0253                 readList=''; miriamKey='';
+0254             case 'compartment'
+0255                 model = readFieldValue(model, 'metComps', tline_value, pos);
+0256                 readList=''; miriamKey='';
+0257             case 'formula'
+0258                 model = readFieldValue(model, 'metFormulas', tline_value, pos);
+0259                 readList=''; miriamKey='';
+0260             case 'charge'
+0261                 model = readFieldValue(model, 'metCharges', tline_value, pos);
+0262                 readList=''; miriamKey='';
+0263             case 'notes'
+0264                 model = readFieldValue(model, 'metNotes', tline_value, pos);
+0265                 readList=''; miriamKey='';
+0266             case 'inchis'
+0267                 model = readFieldValue(model, 'inchis', tline_value, pos);
+0268                 readList=''; miriamKey='';
+0269             case 'smiles'
+0270                 model = readFieldValue(model, 'metSmiles', tline_value, pos);
+0271                 readList=''; miriamKey='';    
+0272             case 'deltaG'
+0273                 model = readFieldValue(model, 'metDeltaG', tline_value, pos);
+0274                 readList=''; miriamKey='';                                
+0275             case 'metFrom'
+0276                 model = readFieldValue(model, 'metFrom', tline_value, pos);
+0277                 readList=''; miriamKey='';
+0278             case 'annotation'
+0279                 readList = 'annotation';
+0280             otherwise
+0281                 switch readList
+0282                     case 'annotation'
+0283                         [metMiriams, miriamKey, metMirNo] = gatherAnnotation(pos,metMiriams,tline_key,tline_value,miriamKey,metMirNo);
+0284                     otherwise
+0285                         error(['Unknown entry in yaml file: ' tline_raw])
+0286                 end
+0287         end; continue
+0288     end
+0289 
+0290     % import reactions:
+0291     if section == 3
+0292         switch tline_key
+0293             case 'id'
+0294                 pos = pos + 1;
+0295                 model = readFieldValue(model, 'rxns', tline_value,pos);
+0296                 readList=''; miriamKey='';
+0297             case 'name'
+0298                 model = readFieldValue(model, 'rxnNames', tline_value, pos);
+0299                 readList=''; miriamKey='';
+0300             case 'lower_bound'
+0301                 model.lb(pos,1) = {tline_value};
+0302                 readList=''; miriamKey='';
+0303             case 'upper_bound'
+0304                 model.ub(pos,1) = {tline_value};
+0305                 readList=''; miriamKey='';
+0306             case 'rev'
+0307                 model.rev(pos,1) = {tline_value};
+0308                 readList=''; miriamKey='';
+0309             case 'gene_reaction_rule'
+0310                 model = readFieldValue(model, 'grRules', tline_value, pos);
+0311                 readList=''; miriamKey='';
+0312             case 'rxnNotes'
+0313                 model = readFieldValue(model, 'rxnNotes', tline_value, pos);
+0314                 readList=''; miriamKey='';
+0315             case 'rxnFrom'
+0316                 model = readFieldValue(model, 'rxnFrom', tline_value, pos);
+0317                 readList=''; miriamKey='';
+0318             case 'deltaG'
+0319                 model = readFieldValue(model, 'rxnDeltaG', tline_value, pos);
+0320                 readList=''; miriamKey='';                
+0321             case 'objective_coefficient'
+0322                 model.c(pos,1) = 1;
+0323                 readList=''; miriamKey='';
+0324             case 'references'
+0325                 model = readFieldValue(model, 'rxnReferences', tline_value, pos);
+0326                 readList=''; miriamKey='';
+0327             case 'confidence_score'
+0328                 model = readFieldValue(model, 'rxnConfidenceScores', tline_value, pos);
+0329                 readList=''; miriamKey='';
+0330             case 'eccodes'
+0331                 if isempty(tline_value)
+0332                     readList = 'eccodes';
+0333                 else
+0334                     eccodes(ecCodeNo,1:2)={pos,tline_value};
+0335                     ecCodeNo=ecCodeNo+1;
+0336                 end
+0337             case 'subsystem'
+0338                 if isempty(tline_value)
+0339                     readList = 'subsystem';
+0340                 else
+0341                     subSystems(subSysNo,1:2)={pos,tline_value};
+0342                     subSysNo=subSysNo+1;
+0343                 end
+0344             case 'metabolites'
+0345                 readList = 'equation';
+0346             case 'annotation'
+0347                 readList = 'annotation';
+0348                 
+0349             otherwise
+0350                 switch readList
+0351                     case 'eccodes'
+0352                         eccodes(ecCodeNo,1:2)={pos,regexprep(tline_value,'^ +- "?(.*)"?$','$1')};
+0353                         ecCodeNo=ecCodeNo+1;
+0354                     case 'subsystem'
+0355                         subSystems(subSysNo,1:2)={pos,regexprep(tline_value,'^ +- "?(.*)"?$','$1')};
+0356                         subSysNo=subSysNo+1;
+0357                     case 'annotation'
+0358                         [rxnMiriams, miriamKey,rxnMirNo] = gatherAnnotation(pos,rxnMiriams,tline_key,tline_value,miriamKey,rxnMirNo);
+0359                     case 'equation'
+0360                         coeff = sscanf(tline_value,'%f');
+0361                         equations(equatiNo,1:3)={pos,tline_key,coeff};
+0362                         equatiNo=equatiNo+1;
+0363                     otherwise
+0364                         error(['Unknown entry in yaml file: ' tline_raw])
+0365                 end                
+0366         end; continue
+0367     end
+0368 
+0369     % import genes:
+0370     if section == 4
+0371         switch tline_key
+0372             case 'id'
+0373                 pos = pos + 1;
+0374                 model = readFieldValue(model, 'genes', tline_value, pos);
+0375                 readList = '';
+0376                 miriamKey = '';
+0377             case 'name'
+0378                 model = readFieldValue(model, 'geneShortNames', tline_value, pos);
+0379             case 'protein'
+0380                 model = readFieldValue(model, 'proteins', tline_value, pos);
+0381             case 'annotation'
+0382                 readList = 'annotation';
+0383             otherwise
+0384                 switch readList
+0385                     case 'annotation'
+0386                         [geneMiriams, miriamKey,genMirNo] = gatherAnnotation(pos,geneMiriams,tline_key,tline_value,miriamKey,genMirNo);
+0387                     otherwise
+0388                         error(['Unknown entry in yaml file: ' tline_raw])
+0389                 end
+0390         end; continue
+0391     end
+0392 
+0393     % import compartments:
+0394     if section == 5
+0395         model.comps(end+1,1) = {tline_key};
+0396         model.compNames(end+1,1) = {tline_value};
+0397     end
+0398 
+0399     % import ec reaction info
+0400     if section == 6
+0401         switch tline_key
+0402             case 'id'
+0403                 pos = pos + 1;
+0404                 model.ec = readFieldValue(model.ec, 'rxns', tline_value, pos);
+0405                 readList='';
+0406             case 'kcat'
+0407                 model.ec = readFieldValue(model.ec, 'kcat', tline_value, pos);
+0408                 readList='';
+0409             case 'source'
+0410                 model.ec = readFieldValue(model.ec, 'source', tline_value, pos);
+0411                 readList='';
+0412             case 'notes'
+0413                 model.ec = readFieldValue(model.ec, 'notes', tline_value, pos);
+0414                 readList='';
+0415             case 'eccodes'
+0416                 if isempty(tline_value)
+0417                     readList = 'eccodes';
+0418                 else
+0419                     ecGecko(ecGeckoNo,1:2)={pos,tline_value};
+0420                     ecGeckoNo=ecGeckoNo+1;
+0421                 end
+0422             case 'enzymes'
+0423                 readList = 'enzStoich';
+0424             otherwise
+0425                 switch readList
+0426                     case 'eccodes'
+0427                         ecGecko(ecGeckoNo,1:2)={pos,regexprep(tline_value,'^ +- "?(.*)"?$','$1')};
+0428                         ecGeckoNo=ecGeckoNo+1;
+0429                     case 'enzStoich'
+0430                         coeff = sscanf(tline_value,'%f');
+0431                         enzStoich(enzStoichNo,1:3)={pos,tline_key,coeff};
+0432                         enzStoichNo=enzStoichNo+1;
+0433                     otherwise
+0434                         error(['Unknown entry in yaml file: ' tline_raw])
+0435                 end
+0436         end; continue
+0437     end
+0438 
+0439     % import ec enzyme info
+0440     if section == 7
+0441         switch tline_key
+0442             case 'genes'
+0443                 pos = pos + 1;
+0444                 model.ec = readFieldValue(model.ec, 'genes', tline_value, pos);
+0445             case 'enzymes'
+0446                 model.ec = readFieldValue(model.ec, 'enzymes', tline_value, pos);
+0447             case 'mw'
+0448                 model.ec = readFieldValue(model.ec, 'mw', tline_value, pos);
+0449             case 'sequence'
+0450                 model.ec = readFieldValue(model.ec, 'sequence', tline_value, pos);
+0451             case 'concs'
+0452                 model.ec = readFieldValue(model.ec, 'concs', tline_value, pos);
+0453             otherwise
+0454                 error(['Unknown entry in yaml file: ' tline_raw])
+0455         end; continue
+0456     end
+0457 end
+0458 
+0459 %Parse annotations
+0460 if ~isempty(metMiriams)
+0461     locs = cell2mat(metMiriams(:,1));
+0462     for i=unique(locs)'
+0463         model.metMiriams{i,1}.name=metMiriams(locs==i,2);
+0464         model.metMiriams{i,1}.value=metMiriams(locs==i,3);
+0465     end
+0466 end
+0467 if ~isempty(rxnMiriams)
+0468     locs = cell2mat(rxnMiriams(:,1));
+0469     for i=unique(locs)'
+0470         model.rxnMiriams{i,1}.name=rxnMiriams(locs==i,2);
+0471         model.rxnMiriams{i,1}.value=rxnMiriams(locs==i,3);
+0472     end
+0473 end
+0474 if ~isempty(geneMiriams)
+0475     locs = cell2mat(geneMiriams(:,1));
+0476     for i=unique(locs)'
+0477         model.geneMiriams{i,1}.name=geneMiriams(locs==i,2);
+0478         model.geneMiriams{i,1}.value=geneMiriams(locs==i,3);
+0479     end
+0480 end
+0481 
+0482 %Parse subSystems
+0483 if ~isempty(subSystems)
+0484     locs = cell2mat(subSystems(:,1));
+0485     for i=unique(locs)'
+0486         model.subSystems{i,1}=subSystems(locs==i,2);
+0487     end
+0488 end
+0489 
+0490 %Parse ec-codes
+0491 if ~isempty(eccodes)
+0492     locs = cell2mat(eccodes(:,1));
+0493     for i=unique(locs)'
+0494         eccodesCat=strjoin(eccodes(locs==i,2),';');
+0495         model.eccodes{i,1}=eccodesCat;
+0496     end
+0497     emptyEc=cellfun('isempty',model.eccodes);
+0498     model.eccodes(emptyEc)={''};
+0499 end
+0500 
+0501 % follow-up data processing
+0502 if verbose
+0503     fprintf('\nimporting completed\nfollow-up processing...');
+0504 end
+0505 [~, model.metComps] = ismember(model.metComps, model.comps);
+0506 [~, model.geneComps] = ismember(model.geneComps, model.comps);
+0507 [~, model.rxnComps] = ismember(model.rxnComps, model.comps);
+0508 
+0509 % Fill S-matrix
+0510 rxnIdx = cellfun('isempty', equations(:,1));
+0511 equations(rxnIdx,:) = '';
+0512 rxnIdx = cell2mat(equations(:,1));
+0513 [~,metIdx] = ismember(equations(:,2),model.mets);
+0514 coeffs = cell2mat(equations(:,3));
+0515 model.S=sparse(max(metIdx),max(rxnIdx));
+0516 linearIndices = sub2ind([max(metIdx), max(rxnIdx)],metIdx,rxnIdx);
+0517 model.S(linearIndices) = coeffs;
+0518 
+0519 % Convert strings to numeric
+0520 model.metCharges = str2double(model.metCharges);
+0521 model.lb = str2double(model.lb);
+0522 model.ub = str2double(model.ub);
+0523 model.rxnConfidenceScores = str2double(model.rxnConfidenceScores);
+0524 model.b = zeros(length(model.mets),1);
+0525 model.metDeltaG = str2double(model.metDeltaG);
+0526 model.rxnDeltaG = str2double(model.rxnDeltaG);
+0527 
+0528 % Fill some other fields
+0529 model.annotation.defaultLB = min(model.lb);
+0530 model.annotation.defaultUB = max(model.ub);
+0531 if numel(model.lb)<numel(model.rxns) %No LB reported = min
+0532     model.lb(end+1:numel(model.rxns)-numel(model.lb),1) = double(model.annotation.defaultLB);
+0533 end
+0534 if numel(model.ub)<numel(model.rxns) %No UB reported = max
+0535     model.ub(end+1:numel(model.rxns)-numel(model.ub),1) = double(model.annotation.defaultUB);
+0536 end
+0537 if ~all(cellfun('isempty',model.rev))
+0538     model.rev = str2double(model.rev);
+0539 else
+0540     model.rev = [];
+0541 end
+0542 if numel(model.rev)<numel(model.rxns) %No rev reported, assume from LB and UB
+0543     model.rev(end+1:numel(model.rxns)-numel(model.rev),1) = double(model.lb<0 & model.ub>0);
+0544 end
+0545 
+0546 % Remove empty fields, otherwise fill to correct length
+0547 % Reactions
+0548 for i={'rxnNames','grRules','eccodes','rxnNotes','rxnReferences',...
+0549        'rxnFrom','subSystems','rxnMiriams'} % Empty strings
+0550    model = emptyOrFill(model,i{1},{''},'rxns');
+0551 end
+0552 for i={'c'} % Zeros
+0553    model = emptyOrFill(model,i{1},0,'rxns',true);
+0554 end
+0555 for i={'rxnConfidenceScores','rxnDeltaG'} % NaNs
+0556    model = emptyOrFill(model,i{1},NaN,'rxns');
+0557 end
+0558 for i={'rxnComps'} % Ones, assume first compartment
+0559    model = emptyOrFill(model,i{1},1,'rxns');
+0560 end
+0561 % Metabolites
+0562 for i={'metNames','inchis','metFormulas','metMiriams','metFrom','metSmiles','metNotes'} % Empty strings
+0563    model = emptyOrFill(model,i{1},{''},'mets');
+0564 end
+0565 for i={'metCharges','unconstrained'} % Zeros
+0566    model = emptyOrFill(model,i{1},0,'mets');
+0567 end
+0568 for i={'metDeltaG'} % % NaNs
+0569     model = emptyOrFill(model,i{1},NaN,'mets');
+0570  end
+0571 for i={'metComps'} % Ones, assume first compartment
+0572    model = emptyOrFill(model,i{1},1,'mets');
+0573 end
+0574 % Genes
+0575 for i={'geneMiriams','geneShortNames','proteins'} % Empty strings
+0576    model = emptyOrFill(model,i{1},{''},'genes');
+0577 end
+0578 for i={'geneComps'} % Ones, assume first compartment
+0579    model = emptyOrFill(model,i{1},1,'genes');
+0580 end
+0581 % Comps
+0582 for i={'compNames'} % Empty strings
+0583    model = emptyOrFill(model,i{1},{''},'comps');
+0584 end
+0585 for i={'compOutside'} % First comp
+0586    model = emptyOrFill(model,i{1},model.comps{1},'comps');
+0587 end
+0588 % Single fields are kept, even if empty
+0589 % for i={'description','name','version','date','annotation'}
+0590 %     if isempty(model.(i{1}))
+0591 %         model = rmfield(model,i{1});
+0592 %     end
+0593 % end
+0594 
+0595 if isfield(model,'subSystems')
+0596 % If all entries are 1x1, then flatten
+0597     if all(cellfun(@(x) numel(x) <= 1, model.subSystems))
+0598         model.subSystems = transpose([model.subSystems{:}]);
+0599     end
+0600 end
+0601 
+0602 % Make rxnGeneMat fields and map to the existing model.genes field
+0603 if isfield(model,'grRules')
+0604     [genes, rxnGeneMat] = getGenesFromGrRules(model.grRules);
+0605     model.rxnGeneMat = sparse(numel(model.rxns),numel(model.genes));
+0606     [~,geneOrder] = ismember(genes,model.genes);
+0607     if any(geneOrder == 0)
+0608         error(['The grRules includes the following gene(s), that are not in '...
+0609             'the list of model genes: ', genes{~geneOrder}])
+0610     end
+0611     model.rxnGeneMat(:,geneOrder) = rxnGeneMat;
+0612 end
+0613 
+0614 % Finalize GECKO model
+0615 if isGECKO
+0616     % Fill in empty fields and empty entries
+0617     for i={'kcat','source','notes','eccodes'} % Even keep empty
+0618         model.ec = emptyOrFill(model.ec,i{1},{''},'rxns',true);
+0619     end
+0620     for i={'enzymes','mw','sequence'}
+0621         model.ec = emptyOrFill(model.ec,i{1},{''},'genes',true);
+0622     end
+0623     model.ec = emptyOrFill(model.ec,'concs',{'NaN'},'genes',true);
+0624     model.ec = emptyOrFill(model.ec,'kcat',{'0'},'genes',true);
+0625     % Change string to double
+0626     for i={'kcat','mw','concs'}
+0627         if isfield(model.ec,i{1})
+0628             model.ec.(i{1}) = str2double(model.ec.(i{1}));
+0629         end
+0630     end
+0631     % Fill rxnEnzMat
+0632     rxnIdx              = cellfun('isempty', enzStoich(:,1));
+0633     enzStoich(rxnIdx,:) = '';
+0634     rxnIdx              = cell2mat(enzStoich(:,1));
+0635     [~,enzIdx]          = ismember(enzStoich(:,2),model.ec.enzymes);
+0636     coeffs              = cell2mat(enzStoich(:,3));
+0637     model.ec.rxnEnzMat  = zeros(numel(model.ec.rxns), numel(model.ec.genes));
+0638     linearIndices       = sub2ind([numel(model.ec.rxns), numel(model.ec.genes)], rxnIdx, enzIdx);
+0639     model.ec.rxnEnzMat(linearIndices) = coeffs;
+0640     %Parse ec-codes
+0641     if ~isempty(ecGecko)
+0642         locs = cell2mat(ecGecko(:,1));
+0643         for i=unique(locs)'
+0644             ecGeckoCat=strjoin(ecGecko(locs==i,2),';');
+0645             model.ec.eccodes{i,1}=ecGeckoCat;
+0646         end
+0647         emptyEc=cellfun('isempty',model.ec.eccodes);
+0648         model.ec.eccodes(emptyEc)={''};
+0649     end
+0650 end
+0651 
+0652 if verbose
+0653     fprintf(' Done!\n');
+0654 end
+0655 end
+0656 
+0657 function model = emptyOrFill(model,field,emptyEntry,type,keepEmpty)
+0658 if nargin<5
+0659     keepEmpty=false;
+0660 end
+0661 if isnumeric(emptyEntry)
+0662     emptyCells=isempty(model.(field));
+0663 else
+0664     emptyCells=cellfun('isempty',model.(field));
+0665 end
+0666 if all(emptyCells) && ~keepEmpty
+0667     model = rmfield(model, field);
+0668 elseif numel(model.(field))<numel(model.(type))
+0669     model.(field)(end+1:numel(model.(type)),1)=emptyEntry;
+0670 end
+0671 end
+0672 
+0673 function model = readFieldValue(model, fieldName, value, pos)
+0674 if numel(model.(fieldName))<pos-1
+0675     model.(fieldName)(end+1:pos,1) = {''};
+0676 end
+0677 model.(fieldName)(pos,1) = {value};
+0678 end
+0679 
+0680 function [miriams,miriamKey,entryNumber] = gatherAnnotation(pos,miriams,key,value,miriamKey,entryNumber)
+0681 if isempty(key)
+0682     key=miriamKey;
+0683 else
+0684     miriamKey=key;
+0685 end
+0686 if ~isempty(value)
+0687     miriams(entryNumber,1:3) = {pos, key, strip(value)};
+0688     entryNumber = entryNumber + 1;
+0689 end
+0690 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/io/sortIdentifiers.html b/doc/io/sortIdentifiers.html new file mode 100644 index 000000000..1198cb318 --- /dev/null +++ b/doc/io/sortIdentifiers.html @@ -0,0 +1,83 @@ + + + + Description of sortIdentifiers + + + + + + + + + +
Home > io > sortIdentifiers.m
+ + + +

sortIdentifiers +

+ +

PURPOSE ^

+
exportModel
+ +

SYNOPSIS ^

+
function newModel = sortIdentifiers(model)
+ +

DESCRIPTION ^

+
 exportModel
+   Sort reactions, metabolites, genes and compartments alphabetically by
+   their identifier.
+
+   Input:
+   model       a model structure
+
+   Output:
+   newModel    an updated model structure with alphabetically sorted
+               identifiers
+
+ Usage: newModel=sortIdentifiers(model)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function newModel = sortIdentifiers(model)
+0002 % exportModel
+0003 %   Sort reactions, metabolites, genes and compartments alphabetically by
+0004 %   their identifier.
+0005 %
+0006 %   Input:
+0007 %   model       a model structure
+0008 %
+0009 %   Output:
+0010 %   newModel    an updated model structure with alphabetically sorted
+0011 %               identifiers
+0012 %
+0013 % Usage: newModel=sortIdentifiers(model)
+0014 
+0015 [~,I]=sort(model.rxns);
+0016 newModel=permuteModel(model,I,'rxns');
+0017 [~,I]=sort(newModel.mets);
+0018 newModel=permuteModel(newModel,I,'mets');
+0019 if isfield(newModel,'genes')
+0020     [~,I]=sort(newModel.genes);
+0021     newModel=permuteModel(newModel,I,'genes');
+0022 end
+0023 [~,I]=sort(newModel.comps);
+0024 newModel=permuteModel(newModel,I,'comps');
+0025 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/io/startup.html b/doc/io/startup.html new file mode 100644 index 000000000..1f8c31159 --- /dev/null +++ b/doc/io/startup.html @@ -0,0 +1,49 @@ + + + + Description of startup + + + + + + + + + +
Home > io > startup.m
+ + + +

startup +

+ +

PURPOSE ^

+
Add the Java Paths at startup in order to be ready for use if the Toolbox is on the path
+ +

SYNOPSIS ^

+
This is a script file.
+ +

DESCRIPTION ^

+
Add the Java Paths at startup in order to be ready for use if the Toolbox is on the path
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 %Add the Java Paths at startup in order to be ready for use if the Toolbox is on the path
+0002 addJavaPaths()
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/io/writeSheet.html b/doc/io/writeSheet.html new file mode 100644 index 000000000..049b90ffb --- /dev/null +++ b/doc/io/writeSheet.html @@ -0,0 +1,211 @@ + + + + Description of writeSheet + + + + + + + + + +
Home > io > writeSheet.m
+ + + +

writeSheet +

+ +

PURPOSE ^

+
writeSheet
+ +

SYNOPSIS ^

+
function wb=writeSheet(wb,sheetName,sheetPosition,captions,units,raw,isIntegers)
+ +

DESCRIPTION ^

+
 writeSheet
+   Writes a cell matrix to an Excel sheet into using the Java library Apache POI
+
+   workbook        Workbook object representing the Excel file
+   sheetName       name of the sheet
+   sheetPosition   0-based position of the sheet
+   captions        cell array of captions (optional)
+   units           WRITE INFO
+   raw             cell array with the data in the sheet
+   isIntegers      true if numeric values should be integers (optional, default
+                   true)
+
+ Usage: wb=writeSheet(wb,sheetName,sheetPosition,captions,units,raw)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 function wb=writeSheet(wb,sheetName,sheetPosition,captions,units,raw,isIntegers)
+0002 % writeSheet
+0003 %   Writes a cell matrix to an Excel sheet into using the Java library Apache POI
+0004 %
+0005 %   workbook        Workbook object representing the Excel file
+0006 %   sheetName       name of the sheet
+0007 %   sheetPosition   0-based position of the sheet
+0008 %   captions        cell array of captions (optional)
+0009 %   units           WRITE INFO
+0010 %   raw             cell array with the data in the sheet
+0011 %   isIntegers      true if numeric values should be integers (optional, default
+0012 %                   true)
+0013 %
+0014 % Usage: wb=writeSheet(wb,sheetName,sheetPosition,captions,units,raw)
+0015 
+0016 if nargin<7
+0017     isIntegers=true;
+0018 end
+0019 
+0020 %Adds the required classes to the static Java path if not already added
+0021 addJavaPaths();
+0022 
+0023 %Import required classes from Apache POI.
+0024 import org.apache.poi.ss.usermodel.*;
+0025 import org.apache.poi.ss.util.*;
+0026 import org.apache.poi.hssf.usermodel.*;
+0027 import org.apache.poi.xssf.usermodel.*;
+0028 
+0029 %Set default style object and bold style object
+0030 defaultStyle = wb.createCellStyle();
+0031 if isIntegers
+0032     idx = wb.getCreationHelper().createDataFormat().getFormat('0');
+0033 else
+0034     idx = wb.getCreationHelper().createDataFormat().getFormat('##0.00');
+0035 end
+0036 defaultStyle.setDataFormat(idx);
+0037 
+0038 boldFont=wb.createFont();
+0039 boldFont.setBoldweight(boldFont.BOLDWEIGHT_BOLD);
+0040 boldStyle=defaultStyle.clone();
+0041 boldStyle.setFont(boldFont);
+0042 
+0043 s=wb.createSheet();
+0044 wb.setSheetName(sheetPosition, sheetName);
+0045 
+0046 %Create the header row and units
+0047 counter=0;
+0048 if ~isempty(captions)
+0049     r=s.createRow(counter);
+0050     for i=0:numel(captions)-1
+0051         c=r.createCell(i);
+0052         c.setCellValue(captions{i+1});
+0053         c.setCellStyle(boldStyle);
+0054     end
+0055     counter=counter+1;
+0056 end
+0057 if ~isempty(units)
+0058     r=s.createRow(counter);
+0059     for i=0:numel(units)-1
+0060         c=r.createCell(i);
+0061         content=units{i+1};
+0062         if iscell(content) && numel(content)==2
+0063             c.setCellValue(content{1});
+0064             
+0065             %This means that the cell should have a list of allowed values
+0066             dvHelper=XSSFDataValidationHelper(s);
+0067             
+0068             cellRange=CellRangeAddressList(1,1,i,i); %Units are on the second line
+0069             dvConstraint=dvHelper.createExplicitListConstraint(toValid(content{2}));
+0070             validation=dvHelper.createValidation(dvConstraint, cellRange);
+0071             validation.setShowErrorBox(true);
+0072             s.addValidationData(validation);
+0073         else
+0074             c.setCellValue(content{1});
+0075         end
+0076         c.setCellStyle(boldStyle);
+0077     end
+0078     counter=counter+1;
+0079 end
+0080 
+0081 %Loop through and fill in the values
+0082 for i=0:size(raw,1)-1
+0083     r=s.createRow(i+counter);
+0084     
+0085     for j=0:size(raw,2)-1
+0086         if ~isempty(raw{i+1,j+1})
+0087             c=r.createCell(j);
+0088             content=raw{i+1,j+1};
+0089             if iscell(content) && numel(content)==2
+0090                 c.setCellValue(content{1});
+0091                 
+0092                 %This means that the cell should have a list of allowed
+0093                 %values
+0094                 dvHelper=XSSFDataValidationHelper(s);
+0095                 cellRange=CellRangeAddressList(i+1,i+1,j,j);
+0096                 dvConstraint=dvHelper.createExplicitListConstraint(toValid(content{2}));
+0097                 validation=dvHelper.createValidation(dvConstraint, cellRange);
+0098                 validation.setShowErrorBox(true);
+0099                 s.addValidationData(validation);
+0100             else
+0101                 c.setCellValue(content);
+0102             end
+0103             c.setCellStyle(defaultStyle);
+0104         end
+0105     end
+0106 end
+0107 
+0108 %Pre-determine column widths for each sheet
+0109 if strcmp(sheetName,'RXNS')
+0110     widths=[786;2358;7860;15719;3406;7860;3406;3406;2358;3406;7860;7860;3668;7860;7860;4192];
+0111 elseif strcmp(sheetName,'METS')
+0112     widths=[786;7860;7860;3668;7860;7860;7860;3406;3668;1834];
+0113 elseif strcmp(sheetName,'COMPS')
+0114     widths=[786;3144;7860;3144;7860];
+0115 elseif strcmp(sheetName,'GENES')
+0116     widths=[786;3144;7860;3144;3406];
+0117 elseif strcmp(sheetName,'MODEL')
+0118     widths=[786;3144;7860;3668;3668;5240;5240;7860;7860;2620;7860];
+0119 end;
+0120 
+0121 %Resize columns
+0122 for i=0:size(raw,2)-1
+0123     s.setColumnWidth(i,widths(i+1));
+0124 end
+0125 
+0126 %Add freeze panes
+0127 if counter>0
+0128     s.createFreezePane(0,counter,0,counter);
+0129 end
+0130 end
+0131 
+0132 function I=toValid(J)
+0133 I=cell(numel(J),1);
+0134 for i=1:numel(J)
+0135     if ischar(J{i})
+0136         I(i)=J(i);
+0137     else
+0138         if islogical(J{i})
+0139             if J{i}==true
+0140                 I{i}='TRUE';
+0141             else
+0142                 I{i}='FALSE';
+0143             end
+0144         else
+0145             %Other, most likely numbers
+0146             I{i}=num2str(J{i});
+0147         end
+0148     end
+0149 end
+0150 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/io/writeYAMLmodel.html b/doc/io/writeYAMLmodel.html new file mode 100644 index 000000000..e41204160 --- /dev/null +++ b/doc/io/writeYAMLmodel.html @@ -0,0 +1,448 @@ + + + + Description of writeYAMLmodel + + + + + + + + + +
Home > io > writeYAMLmodel.m
+ + + +

writeYAMLmodel +

+ +

PURPOSE ^

+
writeYAMLmodel
+ +

SYNOPSIS ^

+
function writeYAMLmodel(model,fileName,preserveQuotes,sortIds)
+ +

DESCRIPTION ^

+
 writeYAMLmodel
+   Writes a yaml file matching (roughly) the cobrapy yaml structure
+
+   model           a model structure
+   fileName        name that the file will have.  A dialog window will 
+                   open if no file name is specified.
+   preserveQuotes  if quotes should be preserved for strings
+                   (logical, default=true)
+   sortIds         if metabolites, reactions, genes and compartments
+                   should be sorted alphabetically by their identifier,
+                   otherwise they are kept in their original order
+                   (logical, default=false)   
+
+ Usage: writeYAMLmodel(model,fileName,preserveQuotes,sortIds)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 function writeYAMLmodel(model,fileName,preserveQuotes,sortIds)
+0002 % writeYAMLmodel
+0003 %   Writes a yaml file matching (roughly) the cobrapy yaml structure
+0004 %
+0005 %   model           a model structure
+0006 %   fileName        name that the file will have.  A dialog window will
+0007 %                   open if no file name is specified.
+0008 %   preserveQuotes  if quotes should be preserved for strings
+0009 %                   (logical, default=true)
+0010 %   sortIds         if metabolites, reactions, genes and compartments
+0011 %                   should be sorted alphabetically by their identifier,
+0012 %                   otherwise they are kept in their original order
+0013 %                   (logical, default=false)
+0014 %
+0015 % Usage: writeYAMLmodel(model,fileName,preserveQuotes,sortIds)
+0016 if nargin<2|| isempty(fileName)
+0017     [fileName, pathName] = uiputfile({'*.yml;*.yaml'}, 'Select file for model export',[model.id '.yml']);
+0018     if fileName == 0
+0019         error('You should provide a file location')
+0020     else
+0021         fileName = fullfile(pathName,fileName);
+0022     end
+0023 end
+0024 fileName=char(fileName);
+0025 
+0026 if nargin < 3
+0027     preserveQuotes = true;
+0028 end
+0029 if nargin < 4
+0030     sortIds = false;
+0031 end
+0032 if ~endsWith(fileName,{'.yml','.yaml'})
+0033     fileName = strcat(fileName,'.yml');
+0034 end
+0035 
+0036 %Check that model is in RAVEN format:
+0037 if isfield(model,'rules')
+0038     model = ravenCobraWrapper(model);
+0039 end
+0040 
+0041 %Check that the model structure has no problems
+0042 checkModelStruct(model);
+0043 
+0044 %Sort identifiers alphabetically
+0045 if sortIds == true
+0046     model = sortIdentifiers(model);
+0047 end
+0048 
+0049 %Simplify Miriam fields:
+0050 if isfield(model,'metMiriams')
+0051     [model.newMetMiriams,model.newMetMiriamNames]   = extractMiriam(model.metMiriams);
+0052 end
+0053 if isfield(model,'rxnMiriams')
+0054     [model.newRxnMiriams,model.newRxnMiriamNames]   = extractMiriam(model.rxnMiriams);
+0055 end
+0056 if isfield(model,'geneMiriams')
+0057     [model.newGeneMiriams,model.newGeneMiriamNames] = extractMiriam(model.geneMiriams);
+0058 end
+0059 if isfield(model,'compMiriams')
+0060     [model.newCompMiriams,model.newCompMiriamNames] = extractMiriam(model.compMiriams);
+0061 end
+0062 
+0063 %Open file:
+0064 fid = fopen(fileName,'wt');
+0065 if fid == -1
+0066     error(['Cannot write to ' fileName ', does the directory exist?'])
+0067 end
+0068 fprintf(fid,'---\n!!omap\n');
+0069 
+0070 %Insert file header (metadata)
+0071 writeMetadata(model,fid);
+0072 
+0073 %Metabolites:
+0074 fprintf(fid,'- metabolites:\n');
+0075 for i = 1:length(model.mets)
+0076     fprintf(fid,'    - !!omap\n');
+0077     writeField(model, fid, 'mets',        'txt', i, '  - id',          preserveQuotes)
+0078     writeField(model, fid, 'metNames',    'txt', i, '  - name',        preserveQuotes)
+0079     writeField(model, fid, 'metComps',    'txt', i, '  - compartment', preserveQuotes)
+0080     writeField(model, fid, 'metFormulas', 'txt', i, '  - formula',     preserveQuotes)
+0081     writeField(model, fid, 'metCharges',  'num', i, '  - charge',      preserveQuotes)
+0082     writeField(model, fid, 'inchis',      'txt', i, '  - inchis',      preserveQuotes)
+0083     writeField(model, fid, 'metSmiles',   'txt', i, '  - smiles',      preserveQuotes)
+0084     writeField(model, fid, 'metMiriams',  'txt', i, '  - annotation',  preserveQuotes)
+0085     writeField(model, fid, 'metDeltaG',   'num', i, '  - deltaG',      preserveQuotes)
+0086     writeField(model, fid, 'metNotes',    'txt', i, '  - notes',       preserveQuotes)
+0087     writeField(model, fid, 'metFrom',     'txt', i, '  - metFrom',     preserveQuotes)
+0088 end
+0089 
+0090 %Reactions:
+0091 fprintf(fid,'- reactions:\n');
+0092 for i = 1:length(model.rxns)
+0093     fprintf(fid,'    - !!omap\n');
+0094     writeField(model, fid, 'rxns',                 'txt', i, '  - id',                    preserveQuotes)
+0095     writeField(model, fid, 'rxnNames',             'txt', i, '  - name',                  preserveQuotes)
+0096     writeField(model, fid, 'S',                    'txt', i, '  - metabolites',           preserveQuotes)
+0097     writeField(model, fid, 'lb',                   'num', i, '  - lower_bound',           preserveQuotes)
+0098     writeField(model, fid, 'ub',                   'num', i, '  - upper_bound',           preserveQuotes)
+0099     writeField(model, fid, 'grRules',              'txt', i, '  - gene_reaction_rule',    preserveQuotes)
+0100     writeField(model, fid, 'rxnFrom',              'txt', i, '  - rxnFrom',               preserveQuotes)
+0101     if model.c(i)~=0
+0102         writeField(model, fid, 'c',                    'num', i, '  - objective_coefficient', preserveQuotes)    
+0103     end
+0104     writeField(model, fid, 'eccodes',              'txt', i, '  - eccodes',               preserveQuotes)
+0105     writeField(model, fid, 'rxnReferences',        'txt', i, '  - references',            preserveQuotes)
+0106     writeField(model, fid, 'subSystems',           'txt', i, '  - subsystem',             preserveQuotes)
+0107     writeField(model, fid, 'rxnMiriams',           'txt', i, '  - annotation',            preserveQuotes)
+0108     writeField(model, fid, 'rxnDeltaG',            'num', i, '  - deltaG',                preserveQuotes)
+0109     writeField(model, fid, 'rxnConfidenceScores',  'num', i, '  - confidence_score',      preserveQuotes)
+0110     writeField(model, fid, 'rxnNotes',             'txt', i, '  - rxnNotes',              preserveQuotes)
+0111 end
+0112 
+0113 %Genes:
+0114 if isfield(model,'genes')
+0115     fprintf(fid,'- genes:\n');
+0116     for i = 1:length(model.genes)
+0117         fprintf(fid,'    - !!omap\n');
+0118         writeField(model, fid, 'genes',          'txt', i, '  - id',         preserveQuotes)
+0119         writeField(model, fid, 'geneShortNames', 'txt', i, '  - name',       preserveQuotes)
+0120         writeField(model, fid, 'proteins',   'txt', i, '  - protein',    preserveQuotes)
+0121         writeField(model, fid, 'geneMiriams',    'txt', i, '  - annotation', preserveQuotes)
+0122     end
+0123 end
+0124 
+0125 %Compartments:
+0126 fprintf(fid,'- compartments: !!omap\n');
+0127 for i = 1:length(model.comps)
+0128     writeField(model, fid, 'compNames',   'txt', i, ['- ' model.comps{i}], preserveQuotes)
+0129     writeField(model, fid, 'compMiriams', 'txt', i, '- annotation',             preserveQuotes)
+0130 end
+0131 
+0132 
+0133 %EC-model:
+0134 if isfield(model,'ec')
+0135     fprintf(fid,'- ec-rxns:\n');
+0136     for i = 1:length(model.ec.rxns)
+0137         fprintf(fid,'  - !!omap\n');
+0138         writeField(model.ec, fid, 'rxns',      'txt', i, '- id',      preserveQuotes)
+0139         writeField(model.ec, fid, 'kcat',      'num', i, '- kcat',    preserveQuotes)
+0140         writeField(model.ec, fid, 'source',    'txt', i, '- source',  preserveQuotes)
+0141         writeField(model.ec, fid, 'notes',     'txt', i, '- notes',   preserveQuotes)
+0142         writeField(model.ec, fid, 'eccodes',   'txt', i, '- eccodes', preserveQuotes)
+0143         writeField(model.ec, fid, 'rxnEnzMat', 'txt', i, '- enzymes', preserveQuotes)
+0144     end
+0145 
+0146     fprintf(fid,'- ec-enzymes:\n');
+0147     for i = 1:length(model.ec.genes)
+0148         fprintf(fid,'  - !!omap\n');
+0149         writeField(model.ec, fid, 'genes',    'txt', i, '- genes',    preserveQuotes)
+0150         writeField(model.ec, fid, 'enzymes',  'txt', i, '- enzymes',  preserveQuotes)
+0151         writeField(model.ec, fid, 'mw',       'num', i, '- mw',       preserveQuotes)
+0152         writeField(model.ec, fid, 'sequence', 'txt', i, '- sequence', preserveQuotes)
+0153         writeField(model.ec, fid, 'concs',    'num', i, '- concs',    preserveQuotes)
+0154     end
+0155 end
+0156 
+0157 %Close file:
+0158 fclose(fid);
+0159 
+0160 end
+0161 
+0162 function writeField(model,fid,fieldName,type,pos,name,preserveQuotes)
+0163 %Writes a new line in the yaml file if the field exists and the field is
+0164 %not empty at the correspoinding position. It's recursive for some fields
+0165 %(metMiriams, rxnMiriams, and S)
+0166 
+0167 if isfield(model,fieldName)
+0168     if strcmp(fieldName,'metComps')
+0169         %metComps: write full name
+0170         fieldName = 'comps';
+0171         pos       = model.metComps(pos);
+0172     end
+0173     
+0174     field = model.(fieldName);
+0175     
+0176     if strcmp(fieldName,'metMiriams')
+0177         if ~isempty(model.metMiriams{pos})
+0178             fprintf(fid,'    %s: !!omap\n',name);
+0179             for i=1:size(model.newMetMiriams,2)
+0180                 %'i' represents the different miriam names, e.g.
+0181                 %kegg.compound or chebi
+0182                 if ~isempty(model.newMetMiriams{pos,i})
+0183                     %As during the following writeField call the value of
+0184                     %'i' would be lost, it is temporarily concatenated to
+0185                     %'name' parameter, which will be edited later
+0186                     writeField(model, fid, 'newMetMiriams', 'txt', pos, ['      - ' model.newMetMiriamNames{i} '_' sprintf('%d',i)], preserveQuotes)
+0187                 end
+0188             end
+0189         end
+0190         
+0191     elseif strcmp(fieldName,'rxnMiriams')
+0192         if ~isempty(model.rxnMiriams{pos})
+0193             fprintf(fid,'    %s: !!omap\n',name);
+0194             for i=1:size(model.newRxnMiriams,2)
+0195                 if ~isempty(model.newRxnMiriams{pos,i})
+0196                     writeField(model, fid, 'newRxnMiriams', 'txt', pos, ['      - ' model.newRxnMiriamNames{i} '_' sprintf('%d',i)], preserveQuotes)
+0197                 end
+0198             end
+0199         end
+0200         
+0201     elseif strcmp(fieldName,'geneMiriams')
+0202         if ~isempty(model.geneMiriams{pos})
+0203             fprintf(fid,'    %s: !!omap\n',name);
+0204             for i=1:size(model.newGeneMiriams,2)
+0205                 if ~isempty(model.newGeneMiriams{pos,i})
+0206                     writeField(model, fid, 'newGeneMiriams', 'txt', pos, ['      - ' model.newGeneMiriamNames{i} '_' sprintf('%d',i)], preserveQuotes)
+0207                 end
+0208             end
+0209         end
+0210         
+0211     elseif strcmp(fieldName,'compMiriams')
+0212         if ~isempty(model.compMiriams{pos})
+0213             fprintf(fid,'    %s: !!omap\n',name);
+0214             for i=1:size(model.newCompMiriams,2)
+0215                 if ~isempty(model.newCompMiriams{pos,i})
+0216                     writeField(model, fid, 'newCompMiriams', 'txt', pos, ['      - ' model.newCompMiriamNames{i} '_' sprintf('%d',i)], preserveQuotes)
+0217                 end
+0218             end
+0219         end
+0220         
+0221     elseif strcmp(fieldName,'S')
+0222         %S: create header & write each metabolite in a new line
+0223         fprintf(fid,'    %s: !!omap\n',name);
+0224         if sum(field(:,pos) ~= 0) > 0
+0225             model.mets   = model.mets(field(:,pos) ~= 0);
+0226             model.coeffs = field(field(:,pos) ~= 0,pos);
+0227             %Sort metabolites:
+0228             [model.mets,order] = sort(model.mets);
+0229             model.coeffs       = model.coeffs(order);
+0230             for i = 1:length(model.mets)
+0231                 writeField(model, fid, 'coeffs',  'num', i, ['      - ' model.mets{i}], preserveQuotes)
+0232             end
+0233         end
+0234 
+0235     elseif strcmp(fieldName,'rxnEnzMat')
+0236         %S: create header & write each enzyme in a new line
+0237         fprintf(fid,'    %s: !!omap\n',name);
+0238         if sum(field(pos,:) ~= 0) > 0
+0239             model.enzymes = model.enzymes(field(pos,:) ~= 0);
+0240             model.coeffs  = field(pos,field(pos,:) ~= 0);
+0241             %Sort metabolites:
+0242             [model.enzymes,order] = sort(model.enzymes);
+0243             model.coeffs          = model.coeffs(order);
+0244             for i = 1:length(model.enzymes)
+0245                 writeField(model, fid, 'coeffs',  'num', i, ['    - ' model.enzymes{i}], preserveQuotes)
+0246             end
+0247         end        
+0248 
+0249     elseif sum(strcmp({'subSystems','newMetMiriams','newRxnMiriams','newGeneMiriams','newCompMiriams','eccodes'},fieldName)) > 0
+0250         %eccodes/rxnNotes: if 1 write in 1 line, if more create header and list
+0251         if strcmp(fieldName,'subSystems')
+0252             list = field{pos};  %subSystems already comes in a cell array
+0253             if isempty(list)
+0254                 return
+0255             end
+0256         elseif strcmp(fieldName,'newMetMiriams')
+0257             index = str2double(regexprep(name,'^.+_',''));
+0258             name  = regexprep(name,'_\d+$','');
+0259             list = strsplit(model.newMetMiriams{pos,index},'; ');
+0260         elseif strcmp(fieldName,'newRxnMiriams')
+0261             index = str2double(regexprep(name,'^.+_',''));
+0262             name  = regexprep(name,'_\d+$','');
+0263             list = strsplit(model.newRxnMiriams{pos,index},'; ');
+0264         elseif strcmp(fieldName,'newGeneMiriams')
+0265             index = str2double(regexprep(name,'^.+_',''));
+0266             name  = regexprep(name,'_\d+$','');
+0267             list = strsplit(model.newGeneMiriams{pos,index},'; ');
+0268         elseif strcmp(fieldName,'newCompMiriams')
+0269             index = str2double(regexprep(name,'^.+_',''));
+0270             name  = regexprep(name,'_\d+$','');
+0271             list = strsplit(model.newCompMiriams{pos,index},'; ');
+0272         elseif ~isempty(field{pos})
+0273             list = strrep(field{pos},' ','');
+0274             list = strsplit(list,';');
+0275         else
+0276             return % empty, needs no line in file
+0277         end
+0278         list=strip(list);
+0279 
+0280         if length(list) == 1 && ~strcmp(list{1},'') && ~strcmp(fieldName,'subSystems')
+0281             if preserveQuotes
+0282                 list = ['"' list{1} '"'];
+0283             end
+0284             if iscell(list)
+0285                 list=list{1};
+0286             end
+0287             fprintf(fid,'    %s: %s\n',name,list);
+0288         elseif ischar(list) && strcmp(fieldName,'subSystems')
+0289             if preserveQuotes
+0290                 list = ['"' list '"'];
+0291             end
+0292             fprintf(fid,'    %s: %s\n',name,list);            
+0293         elseif length(list) > 1 || strcmp(fieldName,'subSystems')
+0294             if preserveQuotes
+0295                 for j=1:numel(list)
+0296                     list{j} = ['"' list{j} '"'];
+0297                 end
+0298             end
+0299             fprintf(fid,'    %s:\n',name);
+0300             for i = 1:length(list)
+0301                 fprintf(fid,'%s        - %s\n',regexprep(name,'(^\s*).*','$1'),list{i});
+0302             end
+0303         end
+0304         
+0305     elseif sum(pos) > 0
+0306         %All other fields:
+0307         if strcmp(type,'txt')
+0308             value = field{pos};
+0309             if preserveQuotes && ~isempty(value)
+0310                 value = ['"',value,'"'];
+0311             end
+0312         elseif strcmp(type,'num')
+0313             if isnan(field(pos))
+0314                 value = [];
+0315             else
+0316                 value = sprintf('%.15g',full(field(pos)));
+0317             end
+0318         end
+0319         if ~isempty(value)
+0320             fprintf(fid,'    %s: %s\n',name,value);
+0321         end
+0322     end
+0323 end
+0324 end
+0325 
+0326 function writeMetadata(model,fid)
+0327 % Writes model metadata to the yaml file. This information will eventually
+0328 % be extracted entirely from the model, but for now, many of the entries
+0329 % are hard-coded defaults for HumanGEM.
+0330 
+0331 fprintf(fid, '- metaData:\n');
+0332 if isfield(model,'id')
+0333     fprintf(fid, '    id: "%s"\n',  model.id);
+0334 else
+0335     fprintf(fid, '    id: "blankID"\n');
+0336 end
+0337 if isfield(model,'name')
+0338     fprintf(fid, '    name: "%s"\n',model.name);
+0339 else
+0340     fprintf(fid, '    name: "blankName"\n');
+0341 end
+0342 if isfield(model,'version')
+0343     fprintf(fid, '    version: "%s"\n',model.version);
+0344 end
+0345 fprintf(fid, '    date: "%s"\n',datestr(now,29));  % 29=YYYY-MM-DD
+0346 if isfield(model,'annotation')
+0347     if isfield(model.annotation,'defaultLB')
+0348         fprintf(fid, '    defaultLB: "%g"\n',   model.annotation.defaultLB);
+0349     end
+0350     if isfield(model.annotation,'defaultUB')
+0351         fprintf(fid, '    defaultUB: "%g"\n',   model.annotation.defaultUB);
+0352     end
+0353     if isfield(model.annotation,'givenName')
+0354         fprintf(fid, '    givenName: "%s"\n',   model.annotation.givenName);
+0355     end
+0356     if isfield(model.annotation,'familyName')
+0357         fprintf(fid, '    familyName: "%s"\n',  model.annotation.familyName);
+0358     end
+0359     if isfield(model.annotation,'authors')
+0360         fprintf(fid, '    authors: "%s"\n',     model.annotation.authors);
+0361     end
+0362     if isfield(model.annotation,'email')
+0363         fprintf(fid, '    email: "%s"\n',       model.annotation.email);
+0364     end
+0365     if isfield(model.annotation,'organization')
+0366         fprintf(fid, '    organization: "%s"\n',model.annotation.organization);
+0367     end
+0368     if isfield(model.annotation,'taxonomy')
+0369         fprintf(fid, '    taxonomy: "%s"\n',    model.annotation.taxonomy);
+0370     end
+0371     if isfield(model.annotation,'note')
+0372         fprintf(fid, '    note: "%s"\n',        model.annotation.note);
+0373     end
+0374     if isfield(model.annotation,'sourceUrl')
+0375         fprintf(fid, '    sourceUrl: "%s"\n',   model.annotation.sourceUrl);
+0376     end
+0377 end
+0378 if isfield(model,'ec')
+0379     if model.ec.geckoLight
+0380         geckoLight = 'true';
+0381     else
+0382         geckoLight = 'false';
+0383     end
+0384     fprintf(fid,'    geckoLight: "%s"\n',geckoLight);
+0385 end
+0386 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/left.png b/doc/left.png new file mode 100644 index 0000000000000000000000000000000000000000..404df045f40970496c71ca6b8c1f1357af271e27 GIT binary patch literal 136 zcmeAS@N?(olHy`uVBq!ia0vp^{2}w1qqB3TN5VEvJYV8 a;bDlI$G>{!EB$9cJq(_%elF{r5}E)JM + + + Description of changeGeneAssoc + + + + + + + + + +
Home > legacy > core > changeGeneAssoc.m
+ + + +

changeGeneAssoc +

+ +

PURPOSE ^

+
changeGeneAssoc
+ +

SYNOPSIS ^

+
function model = changeGeneAssoc(model,rxnID,geneAssoc,replace)
+ +

DESCRIPTION ^

+
 changeGeneAssoc
+   Changes gene association for a defined reaction
+
+   model       a model structure to change the gene association
+   rxnID       string or cell array of reaction IDs
+   geneAssoc   string of additional or replacement gene association.
+               Should be written with ' and ' to indicate subunits, ' or '
+               to indicate isoenzymes, and brackets '()' to separate
+               different instances
+   replace     true if old gene association should be replaced with new
+               association. False if new gene association should be
+               concatenated to the old association (optional, default true)
+
+   model       an updated model structure
+
+ Usage: changeGeneAssoc(model,rxnID,geneAssoc,replace)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function model = changeGeneAssoc(model,rxnID,geneAssoc,replace)
+0002 % changeGeneAssoc
+0003 %   Changes gene association for a defined reaction
+0004 %
+0005 %   model       a model structure to change the gene association
+0006 %   rxnID       string or cell array of reaction IDs
+0007 %   geneAssoc   string of additional or replacement gene association.
+0008 %               Should be written with ' and ' to indicate subunits, ' or '
+0009 %               to indicate isoenzymes, and brackets '()' to separate
+0010 %               different instances
+0011 %   replace     true if old gene association should be replaced with new
+0012 %               association. False if new gene association should be
+0013 %               concatenated to the old association (optional, default true)
+0014 %
+0015 %   model       an updated model structure
+0016 %
+0017 % Usage: changeGeneAssoc(model,rxnID,geneAssoc,replace)
+0018 
+0019 if nargin==3
+0020     replace=true;
+0021 end
+0022 
+0023 if isstr(rxnID)
+0024     rxnID={rxnID};
+0025 end
+0026 
+0027 if ~isstr(geneAssoc)
+0028     EM='geneAssoc has to be string';
+0029     error(sprintf(EM))
+0030 end
+0031 
+0032 
+0033 % Add genes to model
+0034 geneList=transpose(cell(unique(regexp(geneAssoc,'[)(]*|( and )*|( or )*','split')))); % Extract individual, unique genes from the geneAssoc provided
+0035 geneList=geneList(~cellfun(@isempty, geneList));
+0036 genesToAdd.genes=setdiff(geneList,model.genes); % Only keep the genes that are not yet part of the model.genes.
+0037 if ~isempty(genesToAdd.genes)
+0038     model=addGenesRaven(model,genesToAdd); % Add genes
+0039 end
+0040 
+0041 % Find reaction and gene indices
+0042 idx=getIndexes(model,rxnID,'rxns');
+0043 
+0044 % Change gene associations
+0045 if replace==true % Replace old gene associations
+0046     model.grRules(idx)=cellstr(geneAssoc);
+0047 else % Add gene associations, add new gene rules after 'OR'.
+0048     model.grRules(idx)=cellstr('(',[model.grRules{idx},') or (',geneAssoc,')']);
+0049 end
+0050 
+0051 %Fix grRules and reconstruct rxnGeneMat
+0052 [grRules,rxnGeneMat] = standardizeGrRules(model,true);
+0053 model.grRules = grRules;
+0054 model.rxnGeneMat = rxnGeneMat;
+0055 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/legacy/core/index.html b/doc/legacy/core/index.html new file mode 100644 index 000000000..6ebe50eec --- /dev/null +++ b/doc/legacy/core/index.html @@ -0,0 +1,29 @@ + + + + Index for Directory legacy\core + + + + + + + + + + +
< Master indexIndex for legacy\core >
+ +

Index for legacy\core

+ +

Matlab files in this directory:

+ +
 changeGeneAssocchangeGeneAssoc
+ + + + +
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/legacy/external/constructPathwayFromCelldesigner.html b/doc/legacy/external/constructPathwayFromCelldesigner.html new file mode 100644 index 000000000..0a25f26fe --- /dev/null +++ b/doc/legacy/external/constructPathwayFromCelldesigner.html @@ -0,0 +1,590 @@ + + + + Description of constructPathwayFromCelldesigner + + + + + + + + + +
Home > legacy > external > constructPathwayFromCelldesigner.m
+ + + +

constructPathwayFromCelldesigner +

+ +

PURPOSE ^

+
constructPathwayFromCelldesigner
+ +

SYNOPSIS ^

+
function pathway = constructPathwayFromCelldesigner(inputFile)
+ +

DESCRIPTION ^

+
 constructPathwayFromCelldesigner
+    Constructs a pathway structure from a CellDesigner XML file.
+
+    inputFile   string representing the pathway of the Celldesigner XML 
+               file
+
+    pathway
+       listOfCompartments      structure with information on the compartments
+                               in the Celldesigner file
+           x                   the x position
+           y                   the y position
+           h                   the height
+           w                   the width
+           compartment         string representing the compartment
+           id                  alias of the compartment. Used if there are
+                               several instances of the same compartment
+           name                the name of the compartment
+       listOfSpecies           structure with information on each species in
+                               the Celldesigner file. Both metabolites and
+                               enzymes are species
+           x                   the x position
+           y                   the y position
+           h                   the height
+           w                   the width
+           species             string representing the species
+           alias               alias of the species. Used if the species is
+                               present in several places in the map
+           name                the name of the species
+           type                the type of the species. At the moment only
+                               'SIMPLE_MOLECULE' (for metabolites) and
+                               'PROTEIN' (for enzymes) are supported
+           note                string that can be used on enzymes to link them
+                               to the corresponding reaction in a model
+       listOfReactions         structure with information on each of the
+                               reactions in the Celldesigner file
+           reversible          true if the reaction is reversible
+           middlePoint         vector with the x and y points of the middle
+                               point of the reaction. All reactions are
+                               defines as having one reactant and one product.
+                               They may also have a number of modifiers (such
+                               as cofactors or enzymes). Each of these
+                               modifiers are drawn as being connected to the
+                               middle point. The middle point is calculated
+                               from the positions of the reactant and the
+                               product
+           componentList       structure with information on the reactant,
+                               product, and modifiers of the reaction
+               alias           string representing the alias of the
+                               species. Corresponds to the alias in
+                               listOfSpecies
+               species         string representing the species.
+                               Corresponds to the species in listOfSpecies
+               anchor          vector with the x and y points of the
+                               connecting point of the species
+               baseReaction    true if the species is the base reactant
+               baseProduct     true if the species is the base product
+               toArrow         true if the line connecting the species
+                               to the middle point should start with an
+                               arrow
+               fromArrow       true if the line connecting the species
+                               to the middle point should end with an
+                               arrow
+               type            'METABOLITE' or 'ENZYME'
+
+    Usage: pathway = constructPathwayFromCelldesigner(inputFile)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 function pathway = constructPathwayFromCelldesigner(inputFile)
+0002 % constructPathwayFromCelldesigner
+0003 %    Constructs a pathway structure from a CellDesigner XML file.
+0004 %
+0005 %    inputFile   string representing the pathway of the Celldesigner XML
+0006 %               file
+0007 %
+0008 %    pathway
+0009 %       listOfCompartments      structure with information on the compartments
+0010 %                               in the Celldesigner file
+0011 %           x                   the x position
+0012 %           y                   the y position
+0013 %           h                   the height
+0014 %           w                   the width
+0015 %           compartment         string representing the compartment
+0016 %           id                  alias of the compartment. Used if there are
+0017 %                               several instances of the same compartment
+0018 %           name                the name of the compartment
+0019 %       listOfSpecies           structure with information on each species in
+0020 %                               the Celldesigner file. Both metabolites and
+0021 %                               enzymes are species
+0022 %           x                   the x position
+0023 %           y                   the y position
+0024 %           h                   the height
+0025 %           w                   the width
+0026 %           species             string representing the species
+0027 %           alias               alias of the species. Used if the species is
+0028 %                               present in several places in the map
+0029 %           name                the name of the species
+0030 %           type                the type of the species. At the moment only
+0031 %                               'SIMPLE_MOLECULE' (for metabolites) and
+0032 %                               'PROTEIN' (for enzymes) are supported
+0033 %           note                string that can be used on enzymes to link them
+0034 %                               to the corresponding reaction in a model
+0035 %       listOfReactions         structure with information on each of the
+0036 %                               reactions in the Celldesigner file
+0037 %           reversible          true if the reaction is reversible
+0038 %           middlePoint         vector with the x and y points of the middle
+0039 %                               point of the reaction. All reactions are
+0040 %                               defines as having one reactant and one product.
+0041 %                               They may also have a number of modifiers (such
+0042 %                               as cofactors or enzymes). Each of these
+0043 %                               modifiers are drawn as being connected to the
+0044 %                               middle point. The middle point is calculated
+0045 %                               from the positions of the reactant and the
+0046 %                               product
+0047 %           componentList       structure with information on the reactant,
+0048 %                               product, and modifiers of the reaction
+0049 %               alias           string representing the alias of the
+0050 %                               species. Corresponds to the alias in
+0051 %                               listOfSpecies
+0052 %               species         string representing the species.
+0053 %                               Corresponds to the species in listOfSpecies
+0054 %               anchor          vector with the x and y points of the
+0055 %                               connecting point of the species
+0056 %               baseReaction    true if the species is the base reactant
+0057 %               baseProduct     true if the species is the base product
+0058 %               toArrow         true if the line connecting the species
+0059 %                               to the middle point should start with an
+0060 %                               arrow
+0061 %               fromArrow       true if the line connecting the species
+0062 %                               to the middle point should end with an
+0063 %                               arrow
+0064 %               type            'METABOLITE' or 'ENZYME'
+0065 %
+0066 %    Usage: pathway = constructPathwayFromCelldesigner(inputFile)
+0067 
+0068 %Loads the specified xml file using XML Toolbox
+0069 ravenPath=findRAVENroot();
+0070 
+0071 %Current path and xml toolbox path
+0072 cp=pwd;
+0073 xt=fullfile(ravenPath,'software','xml_toolbox');
+0074 
+0075 %Change path, run the script and change back
+0076 cd(xt);
+0077 v = xml_parseany(fileread(inputFile));
+0078 cd(cp);
+0079 
+0080 %Saves information on each compartment
+0081 for i=1:length(v.model{1,1}.annotation{1,1}.listOfCompartmentAliases{1,1}.compartmentAlias)
+0082     pathway.listOfCompartments(i).x=str2double(v.model{1,1}.annotation{1,1}.listOfCompartmentAliases{1,1}...
+0083         .compartmentAlias{1,i}.bounds{1,1}.ATTRIBUTE.x);
+0084     pathway.listOfCompartments(i).y=str2double(v.model{1,1}.annotation{1,1}.listOfCompartmentAliases{1,1}...
+0085         .compartmentAlias{1,i}.bounds{1,1}.ATTRIBUTE.y);
+0086     pathway.listOfCompartments(i).h=str2double(v.model{1,1}.annotation{1,1}.listOfCompartmentAliases{1,1}...
+0087         .compartmentAlias{1,i}.bounds{1,1}.ATTRIBUTE.h);
+0088     pathway.listOfCompartments(i).w=str2double(v.model{1,1}.annotation{1,1}.listOfCompartmentAliases{1,1}...
+0089         .compartmentAlias{1,i}.bounds{1,1}.ATTRIBUTE.w);
+0090     pathway.listOfCompartments(i).compartment=v.model{1,1}.annotation{1,1}.listOfCompartmentAliases{1,1}...
+0091         .compartmentAlias{1,i}.ATTRIBUTE.compartment;
+0092     pathway.listOfCompartments(i).id=v.model{1,1}.annotation{1,1}.listOfCompartmentAliases{1,1}...
+0093         .compartmentAlias{1,i}.ATTRIBUTE.id;
+0094     
+0095     %Finds the name of the compartment
+0096     for j=1:length(v.model{1,1}.listOfCompartments{1,1}.compartment)
+0097         if strcmpi(v.model{1,1}.listOfCompartments{1,1}.compartment{1,j}.ATTRIBUTE.id,...
+0098                 pathway.listOfCompartments(i).compartment)
+0099             pathway.listOfCompartments(i).name=v.model{1,1}.listOfCompartments{1,1}.compartment{1,j}.ATTRIBUTE.name;
+0100             break;
+0101         end
+0102     end
+0103 end
+0104 
+0105 %Saves information on each species and enzyme
+0106 for i=1:length(v.model{1,1}.annotation{1,1}.listOfSpeciesAliases{1,1}.speciesAlias)
+0107     pathway.listOfSpecies(i).x=str2double(v.model{1,1}.annotation{1,1}.listOfSpeciesAliases{1,1}...
+0108         .speciesAlias{1,i}.bounds{1,1}.ATTRIBUTE.x);
+0109     pathway.listOfSpecies(i).y=str2double(v.model{1,1}.annotation{1,1}.listOfSpeciesAliases{1,1}...
+0110         .speciesAlias{1,i}.bounds{1,1}.ATTRIBUTE.y);
+0111     pathway.listOfSpecies(i).h=str2double(v.model{1,1}.annotation{1,1}.listOfSpeciesAliases{1,1}...
+0112         .speciesAlias{1,i}.bounds{1,1}.ATTRIBUTE.h);
+0113     pathway.listOfSpecies(i).w=str2double(v.model{1,1}.annotation{1,1}.listOfSpeciesAliases{1,1}...
+0114         .speciesAlias{1,i}.bounds{1,1}.ATTRIBUTE.w);
+0115     pathway.listOfSpecies(i).alias=v.model{1,1}.annotation{1,1}.listOfSpeciesAliases{1,1}...
+0116         .speciesAlias{1,i}.ATTRIBUTE.id;
+0117     pathway.listOfSpecies(i).species=v.model{1,1}.annotation{1,1}.listOfSpeciesAliases{1,1}...
+0118         .speciesAlias{1,i}.ATTRIBUTE.species;
+0119     %Find the name and type of the species/enzyme
+0120     for j=1:length(v.model{1,1}.listOfSpecies{1,1}.species)
+0121         if strcmpi(v.model{1,1}.listOfSpecies{1,1}.species{1,j}.ATTRIBUTE.id,...
+0122                 pathway.listOfSpecies(i).species)
+0123             pathway.listOfSpecies(i).name=v.model{1,1}.listOfSpecies{1,1}.species{1,j}.ATTRIBUTE.name;
+0124             pathway.listOfSpecies(i).type=v.model{1,1}.listOfSpecies{1,1}.species{1,j}.annotation{1,1}...
+0125                 .speciesIdentity{1,1}.class{1,1}.CONTENT;
+0126             
+0127             %The Celldesigner chart can be linked to a model (e.g. for
+0128             %visualization of fluxes) by making a note in Celldesigner for
+0129             %the protein in interest (this can only be done for proteins at
+0130             %the moment). The note (not protein note!) should only contain
+0131             %the reaction id in the model which corresponds to the protein
+0132             %in Celldesigner.
+0133             if strcmpi(pathway.listOfSpecies(i).type,'PROTEIN')
+0134                 if isfield(v.model{1,1}.listOfSpecies{1,1}.species{1,j},'notes')
+0135                     pathway.listOfSpecies(i).note=cellstr(strtrim(v.model{1,1}.listOfSpecies{1,1}.species{1,j}...
+0136                         .notes{1,1}.html{1,1}.body{1,1}.CONTENT));
+0137                 end
+0138             end
+0139             break;
+0140         end
+0141     end
+0142 end
+0143 
+0144 %Saves information on each reaction
+0145 for i=1:length(v.model{1,1}.listOfReactions{1,1}.reaction)
+0146     %This is because it is standard for a reaction to be defined as
+0147     %reversible
+0148     if isfield(v.model{1,1}.listOfReactions{1,1}.reaction{1,i}.ATTRIBUTE,'reversible')
+0149         pathway.listOfReactions(i).reversible=v.model{1,1}.listOfReactions{1,1}...
+0150             .reaction{1,i}.ATTRIBUTE.reversible;
+0151     else
+0152         pathway.listOfReactions(i).reversible='true';
+0153     end
+0154     
+0155     %NOTE: As far as I know there can only be one base reactant/product per
+0156     %reaction. This method is written with that assumption.
+0157     
+0158     %Finds the alias of the base reactant
+0159     baseReactant=v.model{1,1}.listOfReactions{1,1}...
+0160         .reaction{1,i}.annotation{1,1}.baseReactants{1,1}.baseReactant{1,1}...
+0161         .ATTRIBUTE.alias;
+0162     
+0163     %Finds the alias of the base product
+0164     baseProduct=v.model{1,1}.listOfReactions{1,1}...
+0165         .reaction{1,i}.annotation{1,1}.baseProducts{1,1}.baseProduct{1,1}...
+0166         .ATTRIBUTE.alias;
+0167     
+0168     %Saves the middle point
+0169     [x1,y1]=getBindingPos(pathway,baseReactant,...
+0170         v.model{1,1}.listOfReactions{1,1}.reaction{1,i}.annotation{1,1}...
+0171         .baseReactants{1,1}.baseReactant{1,1}.linkAnchor{1,1}.ATTRIBUTE.position);
+0172     [x2,y2]=getBindingPos(pathway,baseProduct,...
+0173         v.model{1,1}.listOfReactions{1,1}.reaction{1,i}.annotation{1,1}...
+0174         .baseProducts{1,1}.baseProduct{1,1}.linkAnchor{1,1}.ATTRIBUTE.position);
+0175     pathway.listOfReactions(i).middlePoint(1)=x1+(x2-x1)/2;
+0176     pathway.listOfReactions(i).middlePoint(2)=y1+(y2-y1)/2;
+0177     
+0178     %Saves information on each of the components
+0179     counter=1; %Keeps track of where in componentList to add a component
+0180     
+0181     %Adds the base reactant
+0182     pathway.listOfReactions(i).componentList(counter).alias=v.model{1,1}...
+0183         .listOfReactions{1,1}.reaction{1,i}.annotation{1,1}.baseReactants{1,1}...
+0184         .baseReactant{1,1}.ATTRIBUTE.alias;
+0185     pathway.listOfReactions(i).componentList(counter).species=v.model{1,1}...
+0186         .listOfReactions{1,1}.reaction{1,i}.annotation{1,1}.baseReactants{1,1}...
+0187         .baseReactant{1,1}.ATTRIBUTE.species;
+0188     [x,y]=getBindingPos(pathway,baseReactant,v.model{1,1}.listOfReactions{1,1}...
+0189         .reaction{1,i}.annotation{1,1}.baseReactants{1,1}.baseReactant{1,1}...
+0190         .linkAnchor{1,1}.ATTRIBUTE.position);
+0191     pathway.listOfReactions(i).componentList(counter).anchor(1)=x;
+0192     pathway.listOfReactions(i).componentList(counter).anchor(2)=y;
+0193     pathway.listOfReactions(i).componentList(counter).baseReactant='true';
+0194     pathway.listOfReactions(i).componentList(counter).baseProduct='false';
+0195     
+0196     %toArrow should be true if the reaction is reversible
+0197     pathway.listOfReactions(i).componentList(counter).toArrow=...
+0198         pathway.listOfReactions(i).reversible;
+0199     pathway.listOfReactions(i).componentList(counter).fromArrow='false';
+0200     pathway.listOfReactions(i).componentList(counter).type='METABOLITE';
+0201     counter=counter+1;
+0202     
+0203     %Adds the base product
+0204     pathway.listOfReactions(i).componentList(counter).alias=v.model{1,1}...
+0205         .listOfReactions{1,1}.reaction{1,i}.annotation{1,1}.baseProducts{1,1}...
+0206         .baseProduct{1,1}.ATTRIBUTE.alias;
+0207     pathway.listOfReactions(i).componentList(counter).species=v.model{1,1}...
+0208         .listOfReactions{1,1}.reaction{1,i}.annotation{1,1}.baseProducts{1,1}...
+0209         .baseProduct{1,1}.ATTRIBUTE.species;
+0210     [x,y]=getBindingPos(pathway,baseProduct,v.model{1,1}.listOfReactions{1,1}...
+0211         .reaction{1,i}.annotation{1,1}.baseProducts{1,1}.baseProduct{1,1}...
+0212         .linkAnchor{1,1}.ATTRIBUTE.position);
+0213     pathway.listOfReactions(i).componentList(counter).anchor(1)=x;
+0214     pathway.listOfReactions(i).componentList(counter).anchor(2)=y;
+0215     pathway.listOfReactions(i).componentList(counter).baseReactant='false';
+0216     pathway.listOfReactions(i).componentList(counter).baseProduct='true';
+0217     pathway.listOfReactions(i).componentList(counter).toArrow='true';
+0218     pathway.listOfReactions(i).componentList(counter).fromArrow='false';
+0219     pathway.listOfReactions(i).componentList(counter).type='METABOLITE';
+0220     counter=counter+1;
+0221     
+0222     %Adds the non-base reactants Not all reactions have any non-base
+0223     %reactants
+0224     if isfield(v.model{1,1}.listOfReactions{1,1}.reaction{1,i}.annotation{1,1}...
+0225             ,'listOfReactantLinks')
+0226         for j=1:length(v.model{1,1}.listOfReactions{1,1}.reaction{1,i}.annotation{1,1}...
+0227                 .listOfReactantLinks{1,1}.reactantLink)
+0228             pathway.listOfReactions(i).componentList(counter).alias=v.model{1,1}...
+0229                 .listOfReactions{1,1}.reaction{1,i}.annotation{1,1}...
+0230                 .listOfReactantLinks{1,1}.reactantLink{1,j}.ATTRIBUTE.alias;
+0231             pathway.listOfReactions(i).componentList(counter).species=v.model{1,1}...
+0232                 .listOfReactions{1,1}.reaction{1,i}.annotation{1,1}...
+0233                 .listOfReactantLinks{1,1}.reactantLink{1,j}.ATTRIBUTE.reactant;
+0234             [x,y]=getBindingPos(pathway,pathway.listOfReactions(i).componentList(counter).alias...
+0235                 ,v.model{1,1}.listOfReactions{1,1}.reaction{1,i}.annotation{1,1}...
+0236                 .listOfReactantLinks{1,1}.reactantLink{1,j}.linkAnchor{1,1}...
+0237                 .ATTRIBUTE.position);
+0238             pathway.listOfReactions(i).componentList(counter).anchor(1)=x;
+0239             pathway.listOfReactions(i).componentList(counter).anchor(2)=y;
+0240             pathway.listOfReactions(i).componentList(counter).baseReactant='false';
+0241             pathway.listOfReactions(i).componentList(counter).baseProduct='false';
+0242             pathway.listOfReactions(i).componentList(counter).toArrow='false';
+0243             pathway.listOfReactions(i).componentList(counter).fromArrow='false';
+0244             pathway.listOfReactions(i).componentList(counter).type='METABOLITE';
+0245             counter=counter+1;
+0246         end
+0247     end
+0248     
+0249     %Adds the non-base products Not all reactions have any non-base
+0250     %products
+0251     if isfield(v.model{1,1}.listOfReactions{1,1}.reaction{1,i}.annotation{1,1}...
+0252             ,'listOfProductLinks')
+0253         for j=1:length(v.model{1,1}.listOfReactions{1,1}.reaction{1,i}.annotation{1,1}...
+0254                 .listOfProductLinks{1,1}.productLink)
+0255             pathway.listOfReactions(i).componentList(counter).alias=v.model{1,1}...
+0256                 .listOfReactions{1,1}.reaction{1,i}.annotation{1,1}...
+0257                 .listOfProductLinks{1,1}.productLink{1,j}.ATTRIBUTE.alias;
+0258             pathway.listOfReactions(i).componentList(counter).species=v.model{1,1}...
+0259                 .listOfReactions{1,1}.reaction{1,i}.annotation{1,1}...
+0260                 .listOfProductLinks{1,1}.productLink{1,j}.ATTRIBUTE.product;
+0261             [x,y]=getBindingPos(pathway,pathway.listOfReactions(i).componentList(counter).alias...
+0262                 ,v.model{1,1}.listOfReactions{1,1}.reaction{1,i}.annotation{1,1}...
+0263                 .listOfProductLinks{1,1}.productLink{1,j}.linkAnchor{1,1}...
+0264                 .ATTRIBUTE.position);
+0265             pathway.listOfReactions(i).componentList(counter).anchor(1)=x;
+0266             pathway.listOfReactions(i).componentList(counter).anchor(2)=y;
+0267             pathway.listOfReactions(i).componentList(counter).baseReactant='false';
+0268             pathway.listOfReactions(i).componentList(counter).baseProduct='false';
+0269             pathway.listOfReactions(i).componentList(counter).toArrow='true';
+0270             pathway.listOfReactions(i).componentList(counter).fromArrow='false';
+0271             pathway.listOfReactions(i).componentList(counter).type='METABOLITE';
+0272             counter=counter+1;
+0273         end
+0274     end
+0275     
+0276     %Adds the modifiers (enzymes) Not all reactions have any modifiers
+0277     if isfield(v.model{1,1}.listOfReactions{1,1}.reaction{1,i}.annotation{1,1}...
+0278             ,'listOfModification')
+0279         for j=1:length(v.model{1,1}.listOfReactions{1,1}.reaction{1,i}.annotation{1,1}...
+0280                 .listOfModification{1,1}.modification)
+0281             pathway.listOfReactions(i).componentList(counter).alias=v.model{1,1}...
+0282                 .listOfReactions{1,1}.reaction{1,i}.annotation{1,1}.listOfModification{1,1}...
+0283                 .modification{1,j}.linkTarget{1,1}.ATTRIBUTE.alias;
+0284             pathway.listOfReactions(i).componentList(counter).species=v.model{1,1}...
+0285                 .listOfReactions{1,1}.reaction{1,i}.annotation{1,1}.listOfModification{1,1}...
+0286                 .modification{1,j}.linkTarget{1,1}.ATTRIBUTE.species;
+0287             [x,y]=getBindingPos(pathway,pathway.listOfReactions(i).componentList(counter).alias...
+0288                 ,v.model{1,1}.listOfReactions{1,1}.reaction{1,i}.annotation{1,1}...
+0289                 .listOfModification{1,1}.modification{1,j}.linkTarget{1,1}...
+0290                 .linkAnchor{1,1}.ATTRIBUTE.position);
+0291             pathway.listOfReactions(i).componentList(counter).anchor(1)=x;
+0292             pathway.listOfReactions(i).componentList(counter).anchor(2)=y;
+0293             pathway.listOfReactions(i).componentList(counter).baseReactant='false';
+0294             pathway.listOfReactions(i).componentList(counter).baseProduct='false';
+0295             pathway.listOfReactions(i).componentList(counter).toArrow='false';
+0296             pathway.listOfReactions(i).componentList(counter).fromArrow='false';
+0297             pathway.listOfReactions(i).componentList(counter).type='ENZYME';
+0298             counter=counter+1;
+0299         end
+0300     end
+0301 end
+0302 end
+0303 
+0304 function [x,y]=getBindingPos(pathway,speciesAlias,bindingSite)
+0305 % getBindingPos
+0306 %   Calculates the position of a given binding site for a specified species
+0307 %
+0308 %   pathway         the pathway structure which should be modified
+0309 %   speciesAlias    the alias of the species bindingSite     The binding
+0310 %   site in Celldesigner is a string of up to
+0311 %                   three letters that defines which of the 16 bindings
+0312 %                   sites on each species to use. They are written as N
+0313 %                   (north), NNW (north north west) and so on
+0314 %
+0315 %   [x, y]          The position of the binding site for the species
+0316 %
+0317 % Usage: [x,y]=getBindingPos(pathway,speciesAlias,bindingSite)
+0318 
+0319 %Find the species
+0320 for i=1:length(pathway.listOfSpecies)
+0321     if strcmpi(pathway.listOfSpecies(i).alias,speciesAlias)
+0322         xpos=pathway.listOfSpecies(i).x;
+0323         ypos=pathway.listOfSpecies(i).y;
+0324         h=pathway.listOfSpecies(i).h;
+0325         w=pathway.listOfSpecies(i).w;
+0326         
+0327         %Species marked as "PROTEIN" should be drawn as rectangles. There
+0328         %is one binding site in each corner and three in between on each
+0329         %side.
+0330         if strcmpi(pathway.listOfSpecies(i).type,'PROTEIN')
+0331             %The binding sites clockwise from the top position
+0332             if strcmpi(bindingSite,'N')
+0333                 x=xpos+0.5*w;
+0334                 y=ypos;
+0335                 break;
+0336             end
+0337             if strcmpi(bindingSite,'NNE')
+0338                 x=xpos+0.75*w;
+0339                 y=ypos;
+0340                 break;
+0341             end
+0342             if strcmpi(bindingSite,'NE')
+0343                 x=xpos+w;
+0344                 y=ypos;
+0345                 break;
+0346             end
+0347             if strcmpi(bindingSite,'ENE')
+0348                 x=xpos+w;
+0349                 y=ypos+0.25*h;
+0350                 break;
+0351             end
+0352             if strcmpi(bindingSite,'E')
+0353                 x=xpos+w;
+0354                 y=ypos+0.5*h;
+0355                 break;
+0356             end
+0357             if strcmpi(bindingSite,'ESE')
+0358                 x=xpos+w;
+0359                 y=ypos+0.75*h;
+0360                 break;
+0361             end
+0362             if strcmpi(bindingSite,'SE')
+0363                 x=xpos+w;
+0364                 y=ypos+h;
+0365                 break;
+0366             end
+0367             if strcmpi(bindingSite,'SSE')
+0368                 x=xpos+0.75*w;
+0369                 y=ypos+h;
+0370                 break;
+0371             end
+0372             if strcmpi(bindingSite,'S')
+0373                 x=xpos+0.5*w;
+0374                 y=ypos+h;
+0375                 break;
+0376             end
+0377             if strcmpi(bindingSite,'SSW')
+0378                 x=xpos+0.25*w;
+0379                 y=ypos+h;
+0380                 break;
+0381             end
+0382             if strcmpi(bindingSite,'SW')
+0383                 x=xpos;
+0384                 y=ypos+h;
+0385                 break;
+0386             end
+0387             if strcmpi(bindingSite,'WSW')
+0388                 x=xpos;
+0389                 y=ypos+0.75*h;
+0390                 break;
+0391             end
+0392             if strcmpi(bindingSite,'W')
+0393                 x=xpos;
+0394                 y=ypos+0.5*h;
+0395                 break;
+0396             end
+0397             if strcmpi(bindingSite,'WNW')
+0398                 x=xpos;
+0399                 y=ypos+0.25*h;
+0400                 break;
+0401             end
+0402             if strcmpi(bindingSite,'NW')
+0403                 x=xpos;
+0404                 y=ypos;
+0405                 break;
+0406             end
+0407             if strcmpi(bindingSite,'NNW')
+0408                 x=xpos+0.25*w;
+0409                 y=ypos;
+0410                 break;
+0411             end
+0412         end
+0413         
+0414         %Species marked as "SIMPLE_MOLECULE" should be drawn as ellipses.
+0415         %There is one binding site in each extreme point and three in
+0416         %between on each side
+0417         if strcmpi(pathway.listOfSpecies(i).type,'SIMPLE_MOLECULE')
+0418             %Find the center of the ellipse
+0419             centerX=xpos+0.5*w;
+0420             centerY=ypos+0.5*h;
+0421             
+0422             %The binding sites clockwise from the top position
+0423             if strcmpi(bindingSite,'N')
+0424                 angle=(4/8)*pi;
+0425             end
+0426             if strcmpi(bindingSite,'NNE')
+0427                 angle=(5/8)*pi;
+0428             end
+0429             if strcmpi(bindingSite,'NE')
+0430                 angle=(6/8)*pi;
+0431             end
+0432             if strcmpi(bindingSite,'ENE')
+0433                 angle=(7/8)*pi;
+0434             end
+0435             if strcmpi(bindingSite,'E')
+0436                 angle=(8/8)*pi;
+0437             end
+0438             if strcmpi(bindingSite,'ESE')
+0439                 angle=(9/8)*pi;
+0440             end
+0441             if strcmpi(bindingSite,'SE')
+0442                 angle=(10/8)*pi;
+0443             end
+0444             if strcmpi(bindingSite,'SSE')
+0445                 angle=(11/8)*pi;
+0446             end
+0447             if strcmpi(bindingSite,'S')
+0448                 angle=(12/8)*pi;
+0449             end
+0450             if strcmpi(bindingSite,'SSW')
+0451                 angle=(13/8)*pi;
+0452             end
+0453             if strcmpi(bindingSite,'SW')
+0454                 angle=(14/8)*pi;
+0455             end
+0456             if strcmpi(bindingSite,'WSW')
+0457                 angle=(15/8)*pi;
+0458             end
+0459             if strcmpi(bindingSite,'W')
+0460                 angle=(16/8)*pi;
+0461             end
+0462             if strcmpi(bindingSite,'WNW')
+0463                 angle=(1/8)*pi;
+0464             end
+0465             if strcmpi(bindingSite,'NW')
+0466                 angle=(2/8)*pi;
+0467             end
+0468             if strcmpi(bindingSite,'NNW')
+0469                 angle=(3/8)*pi;
+0470             end
+0471             x=centerX-(0.5*w)*cos(angle);
+0472             y=centerY-(0.5*h)*sin(angle);
+0473             break;
+0474         end
+0475     end
+0476 end
+0477 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/legacy/external/index.html b/doc/legacy/external/index.html new file mode 100644 index 000000000..91f40e6db --- /dev/null +++ b/doc/legacy/external/index.html @@ -0,0 +1,29 @@ + + + + Index for Directory legacy\external + + + + + + + + + + +
< Master indexIndex for legacy\external >
+ +

Index for legacy\external

+ +

Matlab files in this directory:

+ +
 constructPathwayFromCelldesignerconstructPathwayFromCelldesigner
+ + + + +
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/linux.png b/doc/linux.png new file mode 100644 index 0000000000000000000000000000000000000000..42c0c328ee43a884158a8363682c493d4a4c335f GIT binary patch literal 272 zcmV+r0q_2aP)z zQ4WJ342H|%(dbp$Gu5lqySaxtLO>W(rpx%_LnVK(UrGTT5y42B06;|UPU9jm^JJ0Z z`TTUN(6TJ&=lPPn_WX zId~2>0yJfGb3Up-MDlH7S}Vx-I*N`iO3-5Ff$K-Ed9Nepzm`zojRl WMtq7>mNL`;0000slDkd7sMUhm~nn@(#}qULHtXTzoc}*_9Non9cn|mMot$6xao(HD{Btemfo7KftJ(gq<~Y~G z@qZoHkA=+tS8)7W&Uw9q`Tr8me+#(&&u0HSm+S9Tw*NEO-*s^O@8dn4!TPz8qu!P4 zK_1Jw46grGoai}Etj@tK_}C@RCk z%#`S6Zs-xzlqxAD$1kf8AM0wN?c%>SMNC?Phc6~Pz{yO{A+R?kRa_)AA;iir?(CQ-4ncIv-nB)Nx{hL?F`wWg|rwizO*(ixxOASOWm3r><21 literal 0 HcmV?d00001 diff --git a/doc/mex.png b/doc/mex.png new file mode 100644 index 0000000000000000000000000000000000000000..396f1bc943e311539c64aa839ba14242c3b1493c GIT binary patch literal 242 zcmeAS@N?(olHy`uVBq!ia0vp^GC<7D!VDzmefZDNn{1``2&1H zT>k^XH6VupNCU}&+~7Mvim@cfFPOpM*^M+1C&}C0g`tC0)&t1lEbxdd1{y2`!i<;h z*8KqrvX^-Jy0Ty9km3|#4DWEh2o&=1ba4!+m=oK_$albigXt^#BmNKn`(>_}oOavV zHb=Afht|Vg%9B``@)jwvpOrK#Ny(Hf&TUq{A5ne4dvCr*%)z?JLGp XX&kFA6^pR}&1LX(^>bP0l+XkK#Yar! literal 0 HcmV?d00001 diff --git a/doc/pathway/colorPathway.html b/doc/pathway/colorPathway.html new file mode 100644 index 000000000..e9632c9f6 --- /dev/null +++ b/doc/pathway/colorPathway.html @@ -0,0 +1,143 @@ + + + + Description of colorPathway + + + + + + + + + +
Home > pathway > colorPathway.m
+ + + +

colorPathway +

+ +

PURPOSE ^

+
colorPathway
+ +

SYNOPSIS ^

+
function returnPathway = colorPathway(pathway, reactionIDs, fluxes, referenceFluxes,cutOff, defaultColor, upColor, downColor)
+ +

DESCRIPTION ^

+
 colorPathway
+    Calculates the color for those reactions that should be marked in the
+    map and returns an updated pathway structure.
+
+   pathway         pathway structure of the metabolic network
+   reactionsIDs    cell array with the names of the reactions in the model
+   fluxes          vector with flux values from the simulation
+   referenceFluxes vector with fluxes for the reference simulation
+   cutOff          a reaction is only colored if the absolute value of 
+                   at least one of the fluxes is above the cutoff value
+                   (optional, default 0)
+   defaultColor    a color in Matlab format to be used if there are no
+                   changes between the fluxes. This color is also used to 
+                   calculate the transition between the colors for up and
+                   down regulated fluxes (optional, default [1 1 1])
+   upColor         a color in Matlab format to be used if the flux is 
+                   larger than the reference flux (optional, default [0 1 0])
+   downColor       a color in Matlab format to be used if the flux is 
+                   smaller than the reference flux (optional, default [1 0 0])
+
+   returnPathway   updated pathway structure which contains coloring data
+       color       array indicating the coloring of the enzyme
+       signChange  true if the reaction has changed direction
+
+    Usage: returnPathway = colorPathway(pathway, reactionIDs, fluxes, referenceFluxes, ...
+           cutOff, defaultColor, upColor, downColor)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function returnPathway = colorPathway(pathway, reactionIDs, fluxes, referenceFluxes, ...
+0002     cutOff, defaultColor, upColor, downColor)
+0003 % colorPathway
+0004 %    Calculates the color for those reactions that should be marked in the
+0005 %    map and returns an updated pathway structure.
+0006 %
+0007 %   pathway         pathway structure of the metabolic network
+0008 %   reactionsIDs    cell array with the names of the reactions in the model
+0009 %   fluxes          vector with flux values from the simulation
+0010 %   referenceFluxes vector with fluxes for the reference simulation
+0011 %   cutOff          a reaction is only colored if the absolute value of
+0012 %                   at least one of the fluxes is above the cutoff value
+0013 %                   (optional, default 0)
+0014 %   defaultColor    a color in Matlab format to be used if there are no
+0015 %                   changes between the fluxes. This color is also used to
+0016 %                   calculate the transition between the colors for up and
+0017 %                   down regulated fluxes (optional, default [1 1 1])
+0018 %   upColor         a color in Matlab format to be used if the flux is
+0019 %                   larger than the reference flux (optional, default [0 1 0])
+0020 %   downColor       a color in Matlab format to be used if the flux is
+0021 %                   smaller than the reference flux (optional, default [1 0 0])
+0022 %
+0023 %   returnPathway   updated pathway structure which contains coloring data
+0024 %       color       array indicating the coloring of the enzyme
+0025 %       signChange  true if the reaction has changed direction
+0026 %
+0027 %    Usage: returnPathway = colorPathway(pathway, reactionIDs, fluxes, referenceFluxes, ...
+0028 %           cutOff, defaultColor, upColor, downColor)
+0029 
+0030 if nargin<8
+0031     downColor=[1 0 0];
+0032 end
+0033 if nargin<7
+0034     upColor=[0 1 0];
+0035 end
+0036 if nargin<6
+0037     defaultColor=[1 1 1];
+0038 end
+0039 if nargin<5
+0040     cutOff=0;
+0041 end
+0042 
+0043 %Loop through the components in the pathway. Check if any component has a
+0044 %note and then check for the corresponding reaction id
+0045 returnPathway=pathway;
+0046 
+0047 for i=1:length(pathway.listOfSpecies)
+0048     if strcmpi(pathway.listOfSpecies(i).type,'PROTEIN')
+0049         if isfield(pathway.listOfSpecies(i),'note')
+0050             if ~isempty(pathway.listOfSpecies(i).note)
+0051                 %If there is a note check if there is a corresponding
+0052                 %reaction id
+0053                 correspondingReaction=find(strcmpi(reactionIDs,pathway.listOfSpecies(i).note));
+0054                 if correspondingReaction>0
+0055                     %Check if either flux is above the cutoff value
+0056                     if abs(referenceFluxes(correspondingReaction))>=cutOff ||...
+0057                             abs(fluxes(correspondingReaction))>=cutOff
+0058                         %Calculate the corresponding color
+0059                         [color, signChange]=getColorCodes(referenceFluxes(correspondingReaction)...
+0060                             ,fluxes(correspondingReaction),1 , defaultColor, upColor, downColor);
+0061                         if ~isempty(color)
+0062                             returnPathway.listOfSpecies(i).color=color{1,1};
+0063                             returnPathway.listOfSpecies(i).signChange=signChange{1,1};
+0064                         end
+0065                     end
+0066                 end
+0067             end
+0068         end
+0069     end
+0070 end
+0071 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/pathway/getPathwayDimensions.html b/doc/pathway/getPathwayDimensions.html new file mode 100644 index 000000000..a9db91aaa --- /dev/null +++ b/doc/pathway/getPathwayDimensions.html @@ -0,0 +1,109 @@ + + + + Description of getPathwayDimensions + + + + + + + + + +
Home > pathway > getPathwayDimensions.m
+ + + +

getPathwayDimensions +

+ +

PURPOSE ^

+
getPathwayDimensions
+ +

SYNOPSIS ^

+
function dimensions=getPathwayDimensions(pathway)
+ +

DESCRIPTION ^

+
 getPathwayDimensions 
+   Retrieves the dimensions of metabolic network in a pathway structure.
+   Returns the position of the upper left corner, width and height.
+
+   pathway         pathway structure representing the pathway to be drawn
+
+   dimension       a 1x4 vector with x and y for the upper left corner,
+                   height and width
+
+ Usage: dimensions=getPathwayDimensions(pathway)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function dimensions=getPathwayDimensions(pathway)
+0002 % getPathwayDimensions
+0003 %   Retrieves the dimensions of metabolic network in a pathway structure.
+0004 %   Returns the position of the upper left corner, width and height.
+0005 %
+0006 %   pathway         pathway structure representing the pathway to be drawn
+0007 %
+0008 %   dimension       a 1x4 vector with x and y for the upper left corner,
+0009 %                   height and width
+0010 %
+0011 % Usage: dimensions=getPathwayDimensions(pathway)
+0012 
+0013 right=0;
+0014 left=inf;
+0015 top=inf;
+0016 bottom=0;
+0017 
+0018 %Loops through the compartments to find the right and bottom border and the
+0019 %position of the upper left corner
+0020 for i=1:length(pathway.listOfCompartments)
+0021     if pathway.listOfCompartments(1,i).x<left
+0022         left=pathway.listOfCompartments(1,i).x;
+0023     end
+0024     if pathway.listOfCompartments(1,i).y<top
+0025         top=pathway.listOfCompartments(1,i).y;
+0026     end
+0027     if (pathway.listOfCompartments(1,i).x+pathway.listOfCompartments(1,i).w)>right
+0028         right=pathway.listOfCompartments(1,i).x+pathway.listOfCompartments(1,i).w;
+0029     end
+0030     if (pathway.listOfCompartments(1,i).y+pathway.listOfCompartments(1,i).h)>bottom
+0031         bottom=pathway.listOfCompartments(1,i).y+pathway.listOfCompartments(1,i).h;
+0032     end
+0033 end
+0034 
+0035 %Loops through the species to find the object furthest to the right, left,
+0036 %top and bottom
+0037 for i=1:length(pathway.listOfSpecies)
+0038     if pathway.listOfSpecies(1,i).x<left
+0039         left=pathway.listOfSpecies(1,i).x;
+0040     end
+0041     if pathway.listOfSpecies(1,i).y<top
+0042         top=pathway.listOfSpecies(1,i).y;
+0043     end
+0044     if (pathway.listOfSpecies(1,i).x+pathway.listOfSpecies(1,i).w)>right
+0045         right=pathway.listOfSpecies(1,i).x+pathway.listOfSpecies(1,i).w;
+0046     end
+0047     if (pathway.listOfSpecies(1,i).y+pathway.listOfSpecies(1,i).h)>bottom
+0048         bottom=pathway.listOfSpecies(1,i).y+pathway.listOfSpecies(1,i).h;
+0049     end
+0050 end
+0051 
+0052 dimensions=[left,top,right-left,bottom-top];
+0053 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/pathway/index.html b/doc/pathway/index.html new file mode 100644 index 000000000..b2c907cb4 --- /dev/null +++ b/doc/pathway/index.html @@ -0,0 +1,29 @@ + + + + Index for Directory pathway + + + + + + + + + + +
< Master indexIndex for pathway >
+ +

Index for pathway

+ +

Matlab files in this directory:

+ +
 colorPathwaycolorPathway
 getPathwayDimensionsgetPathwayDimensions
 mapPathwayRxnNamesmapPathwayRxnNames
 markPathwayWithExpressionmarkPathwayWithExpression
 markPathwayWithFluxesmarkPathwayWithFluxes
 trimPathwaytrimPathway
+ + + + +
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/pathway/mapPathwayRxnNames.html b/doc/pathway/mapPathwayRxnNames.html new file mode 100644 index 000000000..7c7c0132b --- /dev/null +++ b/doc/pathway/mapPathwayRxnNames.html @@ -0,0 +1,98 @@ + + + + Description of mapPathwayRxnNames + + + + + + + + + +
Home > pathway > mapPathwayRxnNames.m
+ + + +

mapPathwayRxnNames +

+ +

PURPOSE ^

+
mapPathwayRxnNames
+ +

SYNOPSIS ^

+
function [pathway, notMapped]=mapPathwayRxnNames(pathway,originalLabels,newLabels)
+ +

DESCRIPTION ^

+
 mapPathwayRxnNames
+   For mapping labels in the pathway object. Useful if you want to change
+   what is shown in the reaction boxes.
+
+   pathway         pathway structure representing the pathway to be drawn
+   originalLabels  cell array with the original reaction labels
+   newLabels       cell array with the new reaction labels
+
+   pathway         an updated pathway structure
+   notMapped       a cell array with labels that could not be found in the
+                   pathway object
+
+ Usage: [pathway, notMapped]=mapPathwayRxnNames(pathway,originalLabels,newLabels)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function [pathway, notMapped]=mapPathwayRxnNames(pathway,originalLabels,newLabels)
+0002 % mapPathwayRxnNames
+0003 %   For mapping labels in the pathway object. Useful if you want to change
+0004 %   what is shown in the reaction boxes.
+0005 %
+0006 %   pathway         pathway structure representing the pathway to be drawn
+0007 %   originalLabels  cell array with the original reaction labels
+0008 %   newLabels       cell array with the new reaction labels
+0009 %
+0010 %   pathway         an updated pathway structure
+0011 %   notMapped       a cell array with labels that could not be found in the
+0012 %                   pathway object
+0013 %
+0014 % Usage: [pathway, notMapped]=mapPathwayRxnNames(pathway,originalLabels,newLabels)
+0015 
+0016 if numel(originalLabels)~=numel(newLabels)
+0017     EM='The new label cell array must have the same length as the old label cell array';
+0018     dispEM(EM);
+0019 end
+0020 
+0021 mapped=false(numel(originalLabels),1);
+0022 
+0023 for i=1:numel(pathway.listOfSpecies)
+0024     if strcmpi(pathway.listOfSpecies(i).type,'PROTEIN')
+0025         I=find(ismember(originalLabels,pathway.listOfSpecies(i).name));
+0026         if any(I)
+0027             if numel(I)==1
+0028                 pathway.listOfSpecies(i).name=newLabels{I};
+0029                 mapped(I)=true;
+0030             else
+0031                 EM=['The label "' pathway.listOfSpecies(i).name '" was found in several positions in oldLabels'];
+0032                 dispEM(EM);
+0033             end
+0034         end
+0035     end
+0036 end
+0037 
+0038 notMapped=originalLabels(~mapped);
+0039 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/pathway/markPathwayWithExpression.html b/doc/pathway/markPathwayWithExpression.html new file mode 100644 index 000000000..bfd985f1d --- /dev/null +++ b/doc/pathway/markPathwayWithExpression.html @@ -0,0 +1,118 @@ + + + + Description of markPathwayWithExpression + + + + + + + + + +
Home > pathway > markPathwayWithExpression.m
+ + + +

markPathwayWithExpression +

+ +

PURPOSE ^

+
markPathwayWithExpression
+ +

SYNOPSIS ^

+
function pathway=markPathwayWithExpression(pathway,model,experiment,experimentOrder)
+ +

DESCRIPTION ^

+
 markPathwayWithExpression
+   Adds gene expression data to a pathway object
+
+   pathway           map structure as generated by constructPathwayFromCelldesigner
+   model             a model structure
+   experiment        experiment structure as generated by getExpressionStructure
+   experimentOrder   cell array with two experiment names as defined in
+                     'experiment'
+
+   pathway           updated pathway object
+
+ Usage: pathway=markPathwayWithExpression(pathway,model,experiment,experimentOrder)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function pathway=markPathwayWithExpression(pathway,model,experiment,experimentOrder)
+0002 % markPathwayWithExpression
+0003 %   Adds gene expression data to a pathway object
+0004 %
+0005 %   pathway           map structure as generated by constructPathwayFromCelldesigner
+0006 %   model             a model structure
+0007 %   experiment        experiment structure as generated by getExpressionStructure
+0008 %   experimentOrder   cell array with two experiment names as defined in
+0009 %                     'experiment'
+0010 %
+0011 %   pathway           updated pathway object
+0012 %
+0013 % Usage: pathway=markPathwayWithExpression(pathway,model,experiment,experimentOrder)
+0014 
+0015 if numel(experimentOrder)~=2
+0016     EM='This can only be done for two cases at the moment (experimentOrder must be two elements)';
+0017     dispEM(EM);
+0018 end
+0019 
+0020 %Check that experiment fit with experimentOrder
+0021 [present, expIds]=ismember(experimentOrder,experiment.experiments);
+0022 
+0023 if ~all(present)
+0024     EM='Not all experiments could be found in the experiment structure';
+0025     dispEM(EM);
+0026 end
+0027 
+0028 experiment.data=experiment.data(:,expIds);
+0029 experiment.experiments=experiment.experiments(:,expIds);
+0030 
+0031 %Go through each species in pathway and if it's a reaction, get it's genes
+0032 %and log2-fold change in expression from model and experiment
+0033 for i=1:numel(pathway.listOfSpecies)
+0034     if strcmp('PROTEIN', pathway.listOfSpecies(i).type)
+0035         if isfield(pathway.listOfSpecies(i),'note')
+0036             if ~isempty(pathway.listOfSpecies(i).note)
+0037                 %Get the reaction if present in model
+0038                 [present, index]=ismember(pathway.listOfSpecies(i).note,model.rxns);
+0039                 
+0040                 %If present, then get the genes
+0041                 if any(present)
+0042                     [~, genes]=find(model.rxnGeneMat(index,:));
+0043                     
+0044                     %If it was associated with genes match them to the ORFs
+0045                     if any(genes)
+0046                         [present, experimentIndexes]=ismember(model.genes(genes),experiment.orfs);
+0047                         
+0048                         %Add annotation to pathway structure
+0049                         if any(present)
+0050                             pathway.listOfSpecies(i).orfs=experiment.orfs(experimentIndexes(present));
+0051                             pathway.listOfSpecies(i).expA=experiment.data(experimentIndexes(present),1);
+0052                             pathway.listOfSpecies(i).expB=experiment.data(experimentIndexes(present),2);
+0053                         end
+0054                     end
+0055                 end
+0056             end
+0057         end
+0058     end
+0059 end
+0060 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/pathway/markPathwayWithFluxes.html b/doc/pathway/markPathwayWithFluxes.html new file mode 100644 index 000000000..10c86f548 --- /dev/null +++ b/doc/pathway/markPathwayWithFluxes.html @@ -0,0 +1,111 @@ + + + + Description of markPathwayWithFluxes + + + + + + + + + +
Home > pathway > markPathwayWithFluxes.m
+ + + +

markPathwayWithFluxes +

+ +

PURPOSE ^

+
markPathwayWithFluxes
+ +

SYNOPSIS ^

+
function [returnPathway, errorFlag]= markPathwayWithFluxes(pathway, reactionIDs, fluxes, referenceFluxes)
+ +

DESCRIPTION ^

+
 markPathwayWithFluxes
+   Marks each enzyme in a pathway structure with the corresponding fluxes
+   from two simulation results. This is done for enzymes that has the name
+   of a reaction in the note field. The reaction has to be present in
+   reactionIDs.
+
+   pathway         pathway structure of the metabolic network
+   reactionsIDs    cell array with the names of the reactions in the model
+   fluxes          vector with flux values
+   referenceFluxes vector with fluxes to compare to
+
+   returnPathway   updates the original pathway structure by adding the
+                   fields flux and referenceFlux for each marked reaction
+   errorFlag       true if there has been an error
+
+ Usage: [returnPathway, errorFlag] = markPathwayWithFluxes(pathway, reactionIDs,
+   fluxes, referenceFluxes)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function [returnPathway, errorFlag]= markPathwayWithFluxes(pathway, reactionIDs, fluxes, referenceFluxes)
+0002 % markPathwayWithFluxes
+0003 %   Marks each enzyme in a pathway structure with the corresponding fluxes
+0004 %   from two simulation results. This is done for enzymes that has the name
+0005 %   of a reaction in the note field. The reaction has to be present in
+0006 %   reactionIDs.
+0007 %
+0008 %   pathway         pathway structure of the metabolic network
+0009 %   reactionsIDs    cell array with the names of the reactions in the model
+0010 %   fluxes          vector with flux values
+0011 %   referenceFluxes vector with fluxes to compare to
+0012 %
+0013 %   returnPathway   updates the original pathway structure by adding the
+0014 %                   fields flux and referenceFlux for each marked reaction
+0015 %   errorFlag       true if there has been an error
+0016 %
+0017 % Usage: [returnPathway, errorFlag] = markPathwayWithFluxes(pathway, reactionIDs,
+0018 %   fluxes, referenceFluxes)
+0019 
+0020 %Check if all variables are of the correct dimension
+0021 if length(reactionIDs)~=length(fluxes) || length(reactionIDs)~=length(referenceFluxes)
+0022     returnPathway=pathway;
+0023     errorFlag=1;
+0024     fprintf('reactionIDs, fluxes, and referenceFluxes do not have the same number of elements.');
+0025     return;
+0026 end
+0027 
+0028 %Loop through the components in the pathway. Check if any component has a
+0029 %note and then check for the corresponding reaction id
+0030 returnPathway=pathway;
+0031 
+0032 for i=1:length(pathway.listOfSpecies)
+0033     if strcmpi(pathway.listOfSpecies(i).type,'PROTEIN')
+0034         if isfield(pathway.listOfSpecies(i),'note')
+0035             if ~isempty(pathway.listOfSpecies(i).note)
+0036                 %If there is a note check if there is a corresponding
+0037                 %reaction id
+0038                 index=find(strcmpi(reactionIDs,pathway.listOfSpecies(i).note));
+0039                 %If there is a match
+0040                 if any(index)
+0041                     returnPathway.listOfSpecies(i).flux=fluxes(index);
+0042                     returnPathway.listOfSpecies(i).referenceFlux=referenceFluxes(index);
+0043                 end
+0044             end
+0045         end
+0046     end
+0047 end
+0048 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/pathway/trimPathway.html b/doc/pathway/trimPathway.html new file mode 100644 index 000000000..84d26ee25 --- /dev/null +++ b/doc/pathway/trimPathway.html @@ -0,0 +1,146 @@ + + + + Description of trimPathway + + + + + + + + + +
Home > pathway > trimPathway.m
+ + + +

trimPathway +

+ +

PURPOSE ^

+
trimPathway
+ +

SYNOPSIS ^

+
function pathway=trimPathway(pathway, rxnsToKeep, deleteUnconnectedMets)
+ +

DESCRIPTION ^

+
 trimPathway
+   Delete reactions from a pathway object
+
+   pathway                   map structure as generated by 
+                             constructPathwayFromCelldesigner
+   rxnsToKeep                cell array with the IDs of the reactions to
+                             keep
+   deleteUnconnectedMets     delete metabolites that are no longer connected
+                             by any reactions (optional, default true)
+
+     pathway                   an updated pathway object
+
+ Usage: pathway=trimPathway(pathway, rxnsToKeep, deleteUnconnectedMets)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function pathway=trimPathway(pathway, rxnsToKeep, deleteUnconnectedMets)
+0002 % trimPathway
+0003 %   Delete reactions from a pathway object
+0004 %
+0005 %   pathway                   map structure as generated by
+0006 %                             constructPathwayFromCelldesigner
+0007 %   rxnsToKeep                cell array with the IDs of the reactions to
+0008 %                             keep
+0009 %   deleteUnconnectedMets     delete metabolites that are no longer connected
+0010 %                             by any reactions (optional, default true)
+0011 %
+0012 %     pathway                   an updated pathway object
+0013 %
+0014 % Usage: pathway=trimPathway(pathway, rxnsToKeep, deleteUnconnectedMets)
+0015 
+0016 if nargin<3
+0017     deleteUnconnectedMets=true;
+0018 end
+0019 
+0020 %First find the aliases and indexes of all reactions that should be deleted
+0021 indexesToDelete=false(numel(pathway.listOfSpecies),1);
+0022 aliasesToDelete={};
+0023 
+0024 for i=1:numel(pathway.listOfSpecies)
+0025     if strcmpi(pathway.listOfSpecies(i).type,'PROTEIN')
+0026         %Check if the name is in the list of reactions to delete
+0027         if ~ismember(pathway.listOfSpecies(i).name,rxnsToKeep)
+0028             indexesToDelete(i)=true;
+0029             aliasesToDelete=[aliasesToDelete;pathway.listOfSpecies(i).alias];
+0030         end
+0031     end
+0032 end
+0033 
+0034 %Then go through each of the reactions and delete the ones that only have
+0035 %modifiers that are in the aliasesToDelete list
+0036 rxnsToDelete=false(numel(pathway.listOfReactions),1);
+0037 
+0038 for i=1:numel(pathway.listOfReactions)
+0039     %Keeps track of which components to delete. -1=enzyme to delete,
+0040     %0=metabolite, 1=enzyme to keep
+0041     componentsToDelete=zeros(numel(pathway.listOfReactions(i).componentList),1);
+0042     for j=1:numel(pathway.listOfReactions(i).componentList)
+0043         if strcmpi(pathway.listOfReactions(i).componentList(j).type,'ENZYME')
+0044             %If the enzyme alias is not in the list then should it not be
+0045             %deleted
+0046             if ismember(pathway.listOfReactions(i).componentList(j).alias,aliasesToDelete)
+0047                 componentsToDelete(j)=-1;
+0048             else
+0049                 componentsToDelete(j)=1;
+0050             end
+0051         end
+0052     end
+0053     %If all enzymes should be deleted then should the whole reacction be
+0054     %deleted. Otherwise only delete those enzymes
+0055     if ~any(componentsToDelete==1)
+0056         rxnsToDelete(i)=true;
+0057     else
+0058         pathway.listOfReactions(i).componentList(componentsToDelete==-1)=[];
+0059     end
+0060 end
+0061 
+0062 %Delete the reactions and components that should be deleted
+0063 pathway.listOfSpecies(indexesToDelete)=[];
+0064 pathway.listOfReactions(rxnsToDelete)=[];
+0065 
+0066 %This is not neat but it goes through all the reactions and adds the
+0067 %aliases that should be kept. All other are deleted
+0068 aliasesToKeeep={};
+0069 if deleteUnconnectedMets==true
+0070     for i=1:numel(pathway.listOfReactions)
+0071         for j=1:numel(pathway.listOfReactions(i).componentList)
+0072             aliasesToKeeep=[aliasesToKeeep;pathway.listOfReactions(i).componentList(j).alias];
+0073         end
+0074     end
+0075     
+0076     %Go through the species again and only keep those that are in the
+0077     %aliasesToKeeep list
+0078     indexesToDelete=true(numel(pathway.listOfSpecies),1);
+0079     for i=1:numel(pathway.listOfSpecies)
+0080         if ismember(pathway.listOfSpecies(i).alias,aliasesToKeeep)
+0081             indexesToDelete(i)=false;
+0082         end
+0083     end
+0084     
+0085     pathway.listOfSpecies(indexesToDelete)=[];
+0086 end
+0087 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/pcode.png b/doc/pcode.png new file mode 100644 index 0000000000000000000000000000000000000000..6801bd9a259131e6de7d7957789598a451c04334 GIT binary patch literal 212 zcmeAS@N?(olHy`uVBq!ia0vp^Qb5ej!3-qBCsR(zDBw1As!D z1s;*bKxKj;%vhfiKM^R%lJ4m1$iT3%pZiZDD@aj*Pl)S(AYk|pNdQueB|(0{ z3=Yq3qyagOo-U3d6}OTT4lqj`WYF%P$jKq`kl`G&cO%P#Bm=oF5vkS`g + + + Description of colorSubsystem + + + + + + + + + +
Home > plotting > colorSubsystem.m
+ + + +

colorSubsystem +

+ +

PURPOSE ^

+
Modified from colorSubsystemCD as distributed through COBRA Toolbox
+ +

SYNOPSIS ^

+
function newMap = colorSubsystem(map, model, subsystem, color)
+ +

DESCRIPTION ^

+
 Modified from colorSubsystemCD as distributed through COBRA Toolbox
+ https://github.com/opencobra/cobratoolbox/blob/src/visualization/metabolicCartography/colorSubsystemCD.m
+
+ Color every reaction in a specific subsystem
+
+ USAGE:
+
+   [newMap] = colorSubsystemCD(map, model, subsystem, color, areaWidth);
+
+ INPUTS:
+   map:            File from CellDesigner parsed to MATLAB format
+   model:          COBRA model structure
+   subsystem:      Name of a subsystem as a String
+
+ OPTIONAL INPUTS:
+   color:          Color desired for reactions in CAPITALS
+   areaWidth:          Width desired for reactions
+
+ OUTPUT:
+   newMap          MATLAB structure of map with reaction modifications
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function newMap = colorSubsystem(map, model, subsystem, color)
+0002 % Modified from colorSubsystemCD as distributed through COBRA Toolbox
+0003 % https://github.com/opencobra/cobratoolbox/blob/src/visualization/metabolicCartography/colorSubsystemCD.m
+0004 %
+0005 % Color every reaction in a specific subsystem
+0006 %
+0007 % USAGE:
+0008 %
+0009 %   [newMap] = colorSubsystemCD(map, model, subsystem, color, areaWidth);
+0010 %
+0011 % INPUTS:
+0012 %   map:            File from CellDesigner parsed to MATLAB format
+0013 %   model:          COBRA model structure
+0014 %   subsystem:      Name of a subsystem as a String
+0015 %
+0016 % OPTIONAL INPUTS:
+0017 %   color:          Color desired for reactions in CAPITALS
+0018 %   areaWidth:          Width desired for reactions
+0019 %
+0020 % OUTPUT:
+0021 %   newMap          MATLAB structure of map with reaction modifications
+0022 if nargin < 4
+0023     color = 'RED';
+0024 end
+0025 
+0026 newMap = map;
+0027 rxnList = model.rxns(ismember([model.subSystems{:}]', subsystem));
+0028 colors = createColorsMap;
+0029 
+0030 index = find(ismember(newMap.rxnName, rxnList));
+0031 for j = index'
+0032     newMap.rxnColor{j, 1} = colors(color);
+0033     %newMap.rxnWidth{j, 1} = areaWidth;
+0034 end
+0035 
+0036 % Use the existence of reactant lines to check if the map has the
+0037 % complete structure, and if so change also secondary lines.
+0038 if any(strcmp('rxnReactantLineColor', fieldnames(newMap))) == 1
+0039     for j = index'
+0040         if ~isempty(newMap.rxnReactantLineColor{j})
+0041             for k = 1:length(newMap.rxnReactantLineColor{j})
+0042                 newMap.rxnReactantLineColor{j, 1}{k, 1} = colors(color);
+0043                 %newMap.rxnReactantLineWidth{j, 1}{k, 1} = areaWidth;
+0044             end
+0045         end
+0046         if ~isempty(newMap.rxnProductLineColor{j})
+0047             for m = 1:1:length(newMap.rxnProductLineColor{j})
+0048                 newMap.rxnProductLineColor{j, 1}{m, 1} = colors(color);
+0049                 %newMap.rxnProductLineWidth{j, 1}{m, 1} = areaWidth;
+0050             end
+0051         end
+0052     end
+0053 end
+0054 
+0055 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/plotting/drawMap.html b/doc/plotting/drawMap.html new file mode 100644 index 000000000..8175725c3 --- /dev/null +++ b/doc/plotting/drawMap.html @@ -0,0 +1,211 @@ + + + + Description of drawMap + + + + + + + + + +
Home > plotting > drawMap.m
+ + + +

drawMap +

+ +

PURPOSE ^

+
drawMap
+ +

SYNOPSIS ^

+
function notMapped=drawMap(title,pathway,modelA,conditionA,conditionB,modelB,filename,cutOff,supressOpen)
+ +

DESCRIPTION ^

+
 drawMap
+   Imports a previously drawn map of the metabolic network and plots
+   the fluxes on that map. If the pathway contains expression data the log-fold
+   changes are plotted as well
+
+   title           title to be printed on the map
+   pathway         map structure as generated by
+                   constructPathwayFromCelldesigner
+   modelA            model structure for condition A
+   conditionA      flux vector for condition A
+   conditionB        flux vector for condition B (optional)
+   modelB            model structure for condition B (optional, default modelA)
+   filename        exports the map as a pdf (optional)
+   cutOff          only print fluxes where one of the fluxes are above this
+                   value (optional, default 10^-7)
+   supressOpen     true if the pdf file should not be opened (optional, default
+                   false)
+
+   notMapped         the reaction ids that carried a flux in either of the
+                   conditions but that were not present in the metabolic map
+
+   The objective function in modelA is assumed to be the objective function
+   in both cases. If only one flux is supplied then that flux is printed two
+   times in each box.
+
+ Usage: notMapped=drawMap(title,pathway,modelA,conditionA,...
+           conditionB,modelB,filename,cutOff,supressOpen)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function notMapped=drawMap(title,pathway,modelA,conditionA,conditionB,modelB,filename,cutOff,supressOpen)
+0002 % drawMap
+0003 %   Imports a previously drawn map of the metabolic network and plots
+0004 %   the fluxes on that map. If the pathway contains expression data the log-fold
+0005 %   changes are plotted as well
+0006 %
+0007 %   title           title to be printed on the map
+0008 %   pathway         map structure as generated by
+0009 %                   constructPathwayFromCelldesigner
+0010 %   modelA            model structure for condition A
+0011 %   conditionA      flux vector for condition A
+0012 %   conditionB        flux vector for condition B (optional)
+0013 %   modelB            model structure for condition B (optional, default modelA)
+0014 %   filename        exports the map as a pdf (optional)
+0015 %   cutOff          only print fluxes where one of the fluxes are above this
+0016 %                   value (optional, default 10^-7)
+0017 %   supressOpen     true if the pdf file should not be opened (optional, default
+0018 %                   false)
+0019 %
+0020 %   notMapped         the reaction ids that carried a flux in either of the
+0021 %                   conditions but that were not present in the metabolic map
+0022 %
+0023 %   The objective function in modelA is assumed to be the objective function
+0024 %   in both cases. If only one flux is supplied then that flux is printed two
+0025 %   times in each box.
+0026 %
+0027 % Usage: notMapped=drawMap(title,pathway,modelA,conditionA,...
+0028 %           conditionB,modelB,filename,cutOff,supressOpen)
+0029 
+0030 if nargin<4
+0031     conditionB=conditionA;
+0032 end
+0033 
+0034 if nargin<5
+0035     modelB=modelA;
+0036 end
+0037 
+0038 if nargin<8
+0039     cutOff=10^-7;
+0040 end
+0041 
+0042 if nargin<9
+0043     supressOpen=false;
+0044 end
+0045 
+0046 if isempty(conditionB)
+0047     conditionB=conditionA;
+0048 end
+0049 
+0050 if isempty(modelB)
+0051     modelB=modelA;
+0052 end
+0053 
+0054 objectiveNames=modelA.rxns(modelA.c~=0);
+0055 objectiveValues=modelA.c(modelA.c~=0);
+0056 
+0057 %Replace all values which are below the cut-off with 0.0
+0058 conditionA(abs(conditionA)<cutOff)=0;
+0059 conditionB(abs(conditionB)<cutOff)=0;
+0060 
+0061 %Get the reactions that could not be mapped
+0062 carriesFlux=union(modelA.rxns,modelB.rxns);
+0063 
+0064 rxnsInModel={};
+0065 %Loop through the pathway structure and get the reaction that can be mapped
+0066 for i=1:numel(pathway.listOfSpecies)
+0067     if strcmp(pathway.listOfSpecies(i).type,'PROTEIN')
+0068         if ~isempty(pathway.listOfSpecies(i).note)
+0069             rxnsInModel=[rxnsInModel;pathway.listOfSpecies(i).note(1)];
+0070         end
+0071     end
+0072 end
+0073 
+0074 %Find all reaction bounds that are "non-standard". Since the default bounds
+0075 %are not indicated in the model structure it is assumed that the maximal
+0076 %bound value is the default one.
+0077 rxnBoundsA=find(modelA.ub~=max(modelA.ub) | (modelA.lb~=-max(modelA.ub) & modelA.rev==1) | (modelA.lb~=0 & modelA.rev==0));
+0078 rxnBoundsB=find(modelB.ub~=max(modelB.ub) | (modelB.lb~=-max(modelB.ub) & modelB.rev==1) | (modelB.lb~=0 & modelB.rev==0));
+0079 
+0080 notMapped=setdiff(carriesFlux,rxnsInModel);
+0081 
+0082 pathway=colorPathway(pathway,modelA.rxns,conditionA,conditionB,cutOff);
+0083 pathway=markPathwayWithFluxes(pathway,modelA.rxns,conditionA,conditionB);
+0084 
+0085 h=figure('Visible','Off');
+0086 drawPathway(pathway,h,cutOff);
+0087 
+0088 %Plot labels and title at pathway map
+0089 plotLabels(h,pathway);
+0090 setTitle(h,pathway,title);
+0091 
+0092 %Plot example box, color example and additional information
+0093 exampleBoxText(1)={'Reaction ID'};
+0094 exampleBoxText(2)={'Condition A'};
+0095 exampleBoxText(3)={'Condition B'};
+0096 if nargin>7
+0097     exampleBoxText(4)={'Other data'};
+0098 end
+0099 
+0100 additionalText={};
+0101 additionalText=[additionalText;{'Objective function'}];
+0102 
+0103 additionalText=[additionalText;{getObjectiveString(true, objectiveNames, objectiveValues)}];
+0104 additionalText=[additionalText;{''}];
+0105 additionalText=[additionalText;{'Constraints (condition A)'}];
+0106 
+0107 counter=numel(additionalText)+1;
+0108 for i=1:length(rxnBoundsA)
+0109     additionalText{counter}=[modelA.rxns{rxnBoundsA(i)} '  [' ...
+0110         num2str([modelA.lb(rxnBoundsA(i)) modelA.ub(rxnBoundsA(i))]) ']'];
+0111     counter=counter+1;
+0112 end
+0113 
+0114 additionalText=[additionalText;{''}];
+0115 additionalText=[additionalText;{'Constraints (condition B)'}];
+0116 
+0117 counter=numel(additionalText)+1;
+0118 for i=1:length(rxnBoundsB)
+0119     additionalText{counter}=[modelB.rxns{rxnBoundsB(i)} '  [' ...
+0120         num2str([modelB.lb(rxnBoundsB(i)) modelB.ub(rxnBoundsB(i))]) ']'];
+0121     counter=counter+1;
+0122 end
+0123 
+0124 plotAdditionalInfo(h, pathway, additionalText, exampleBoxText, 1);
+0125 
+0126 if nargin>5
+0127     if any(filename)
+0128         set(gcf, 'PaperType', 'A4');
+0129         orient landscape;
+0130         print('-dpdf', '-r600', filename);
+0131         fprintf('File saved as %s\n',filename);
+0132     end
+0133 end
+0134 
+0135 if supressOpen==false
+0136     open(filename);
+0137 end
+0138 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/plotting/drawPathway.html b/doc/plotting/drawPathway.html new file mode 100644 index 000000000..3328522f8 --- /dev/null +++ b/doc/plotting/drawPathway.html @@ -0,0 +1,481 @@ + + + + Description of drawPathway + + + + + + + + + +
Home > plotting > drawPathway.m
+ + + +

drawPathway +

+ +

PURPOSE ^

+
drawPathway
+ +

SYNOPSIS ^

+
function drawPathway(pathway, h, cutOff, defaultColor)
+ +

DESCRIPTION ^

+
 drawPathway
+    Draws a metabolic network to a figure.
+
+   pathway         pathway structure representing the pathway to be drawn
+   handle          handle to a figure (optional)
+   cutOff          the fluxes are only printed if the absolute value of
+                   at least one of the fluxes is above the cutoff value
+                   (optional, default 0)
+   defaultColor    color in Matlab format to be used as the background
+                   color for enzymes if no color is specified in the
+                   pathway structure (optional, default [1 1 1])
+
+   NOTE:   At the moment all text sizes and some positions are hard coded.
+           This means that this code is not appliable for any map
+
+ Usage: drawPathway(pathway, handle, cutOff, defaultColor)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 function drawPathway(pathway, h, cutOff, defaultColor)
+0002 % drawPathway
+0003 %    Draws a metabolic network to a figure.
+0004 %
+0005 %   pathway         pathway structure representing the pathway to be drawn
+0006 %   handle          handle to a figure (optional)
+0007 %   cutOff          the fluxes are only printed if the absolute value of
+0008 %                   at least one of the fluxes is above the cutoff value
+0009 %                   (optional, default 0)
+0010 %   defaultColor    color in Matlab format to be used as the background
+0011 %                   color for enzymes if no color is specified in the
+0012 %                   pathway structure (optional, default [1 1 1])
+0013 %
+0014 %   NOTE:   At the moment all text sizes and some positions are hard coded.
+0015 %           This means that this code is not appliable for any map
+0016 %
+0017 % Usage: drawPathway(pathway, handle, cutOff, defaultColor)
+0018 
+0019 if nargin<4
+0020     defaultColor=[1 1 1];
+0021 end
+0022 if nargin<3
+0023     cutOff=0;
+0024 end
+0025 if nargin<2
+0026     if ishandle(gcf)
+0027         h=gcf;
+0028     else
+0029         h=figure();
+0030     end
+0031 end
+0032 
+0033 %Will contain all metabolite info and where to print them
+0034 metText={};
+0035 metX=[];
+0036 metY=[];
+0037 metRec=[];
+0038 
+0039 %Same for reaction text (names, fluxes and maybe other)
+0040 rxnText={};
+0041 rxnX=[];
+0042 rxnY=[];
+0043 rxnLinesX=[];
+0044 rxnLinesY=[];
+0045 rxnRec=[];
+0046 rxnFace=[];
+0047 rxnEdge=[];
+0048 rxnArrows=[];
+0049 rxnArrowsColor=[];
+0050 
+0051 %Expression boxes
+0052 expRec=[];
+0053 expFace=[];
+0054 
+0055 %Lines to enzymes
+0056 enzLinesX=[];
+0057 enzLinesY=[];
+0058 
+0059 %Same for compartments
+0060 compText={};
+0061 compX=[];
+0062 compY=[];
+0063 compRec=[];
+0064 
+0065 %Check if it should plot expression data
+0066 if isfield(pathway.listOfSpecies(1),'orfs')
+0067     drawExpression=true;
+0068 else
+0069     drawExpression=false;
+0070 end
+0071 
+0072 %Get the dimensions of the network
+0073 dimension=getPathwayDimensions(pathway);
+0074 
+0075 %Specify the properties of the figure
+0076 set(h, 'PaperOrientation', 'landscape');
+0077 set(h, 'Color', [1 1 1]);
+0078 xmargin=0.83;
+0079 ymargin=1.32;
+0080 set(h, 'PaperPosition', [xmargin ymargin 29.67743169791-2*xmargin 20.98404194812-2*ymargin]);
+0081 set(h, 'Renderer', 'painters');
+0082 set(h, 'Position', [10 10 1000 700]);
+0083 
+0084 %The height has to be at least the height of the information panel
+0085 %(approximately 3000)
+0086 height=dimension(2)+dimension(4)+200;
+0087 height=max(height,3000);
+0088 
+0089 axes('ytick',[],'ydir','reverse','xtick',[],'ycolor',[1 1 1], 'xcolor',...
+0090     [1 1 1],'position',[0 0 1 1], 'xLim',[dimension(1)-40 dimension(1)+dimension(3)+800],...
+0091     'yLim', [dimension(2)-200 height]);
+0092 daspect([1,1,1]);
+0093 
+0094 %Loops through the compartments.
+0095 for i=1:length(pathway.listOfCompartments)
+0096     position=[pathway.listOfCompartments(1,i).x pathway.listOfCompartments(1,i).y...
+0097         pathway.listOfCompartments(1,i).w pathway.listOfCompartments(1,i).h];
+0098     compRec=[compRec;position];
+0099     compText=[compText;upper(pathway.listOfCompartments(i).name)];
+0100     compX=[compX;position(1)+0.5*position(3)];
+0101     compY=[compY;position(2)+position(4)-70];
+0102 end
+0103 
+0104 %Get positions of lines
+0105 for i=1:length(pathway.listOfReactions)
+0106     for j=1:length(pathway.listOfReactions(i).componentList)
+0107         %The line is always drawn from the middle to the component
+0108         middle=pathway.listOfReactions(i).middlePoint;
+0109         x(1)=middle(1);
+0110         y(1)=middle(2);
+0111         x(2)=pathway.listOfReactions(i).componentList(j).anchor(1);
+0112         y(2)=pathway.listOfReactions(i).componentList(j).anchor(2);
+0113         
+0114         %Check to see if a line or an arrow should be drawn
+0115         if strcmpi(pathway.listOfReactions(i).componentList(j).toArrow,'true')
+0116             rxnArrows=[rxnArrows;x(1) y(1) x(2) y(2)];
+0117             
+0118             %Draw a red arrow if it's a base product
+0119             if strcmpi(pathway.listOfReactions(i).componentList(j).baseProduct,'true')
+0120                 rxnArrowsColor=[rxnArrowsColor;1 0 0];
+0121             else
+0122                 rxnArrowsColor=[rxnArrowsColor;0 0 0];
+0123             end
+0124         else
+0125             %If the component is an enzyme then a different line should be
+0126             %used
+0127             if strcmpi(pathway.listOfReactions(i).componentList(j).type,'ENZYME')
+0128                 enzLinesX=[enzLinesX;x(1) x(2)];
+0129                 enzLinesY=[enzLinesY;y(1) y(2)];
+0130             else
+0131                 rxnLinesX=[rxnLinesX;x(1) x(2)];
+0132                 rxnLinesY=[rxnLinesY;y(1) y(2)];
+0133             end
+0134         end
+0135     end
+0136 end
+0137 
+0138 %Loops through the species
+0139 for i=1:length(pathway.listOfSpecies)
+0140     %Species should be represented with ellipses and enzymes with
+0141     %rectangles
+0142     position=[pathway.listOfSpecies(i).x pathway.listOfSpecies(i).y...
+0143         pathway.listOfSpecies(i).w pathway.listOfSpecies(i).h];
+0144     if strcmpi(pathway.listOfSpecies(i).type, 'SIMPLE_MOLECULE')
+0145         metRec=[metRec;position];
+0146         metText=[metText;pathway.listOfSpecies(i).name];
+0147         metX=[metX;position(1)+0.3*position(3)];
+0148         metY=[metY;position(2)+0.5*position(4)];
+0149     end
+0150     if strcmpi(pathway.listOfSpecies(i).type, 'PROTEIN')
+0151         %The color of the enzyme can be specified in the pathway object.
+0152         %The default color is used if there is no 'color' field present.
+0153         %If neither of the fluxes are above the cutoff value, then use the
+0154         %default color
+0155         faceColor=defaultColor;
+0156         if isfield(pathway.listOfSpecies(i),'color')
+0157             if any(pathway.listOfSpecies(i).color)
+0158                 %Check that the fluxes are specified
+0159                 if isfield(pathway.listOfSpecies(i),'flux') && isfield(pathway.listOfSpecies(i),'referenceFlux')
+0160                     %Check that the value of one of the fluxes is above the cutoff value
+0161                     if abs(pathway.listOfSpecies(i).referenceFlux)>=cutOff || abs(pathway.listOfSpecies(i).flux)>=cutOff
+0162                         faceColor=pathway.listOfSpecies(i).color;
+0163                     end
+0164                 end
+0165             end
+0166         end
+0167         
+0168         %If the reaction is associated with a sign change and either of the
+0169         %fluxes are larger than the cutoff value, then use a different frame
+0170         edgeColor=[0 0 0];
+0171         if isfield(pathway.listOfSpecies(i),'signChange')
+0172             if any(pathway.listOfSpecies(i).signChange)
+0173                 if (pathway.listOfSpecies(i).signChange==true) && (abs(pathway.listOfSpecies(i).referenceFlux)>=cutOff || abs(pathway.listOfSpecies(i).flux)>=cutOff)
+0174                     edgeColor=[1 0.6 0.2];
+0175                 end
+0176             end
+0177         end
+0178         
+0179         rxnFace=[rxnFace;faceColor];
+0180         rxnEdge=[rxnEdge;edgeColor];
+0181         
+0182         %Draw smaller boxes if expression data should also be printed
+0183         if drawExpression==true
+0184             rxnRec=[rxnRec;position-[0 0 40 0]];
+0185             
+0186             %Draw rectangles representing each gene. Max 8 circles are used.
+0187             %Their width is hardcoded and so is the width of the area where
+0188             %they are printed (40)
+0189             if any(pathway.listOfSpecies(i).expA)
+0190                 %Calculate the position of the dots. 4 in each column.
+0191                 firstFourX=pathway.listOfSpecies(i).x+pathway.listOfSpecies(i).w-34;
+0192                 fourY=pathway.listOfSpecies(i).y:pathway.listOfSpecies(i).h/4:pathway.listOfSpecies(i).y+pathway.listOfSpecies(i).h;
+0193                 
+0194                 nExp=numel(pathway.listOfSpecies(i).expA);
+0195                 
+0196                 %One log10-fold change is total up or down
+0197                 colorCodes=getColorCodes(pathway.listOfSpecies(i).expA, pathway.listOfSpecies(i).expB);
+0198                 
+0199                 %Plot the circles
+0200                 for j=1:min(nExp,4)
+0201                     expRec=[expRec;firstFourX fourY(j) 16 pathway.listOfSpecies(i).h/4];
+0202                     expFace=[expFace;colorCodes{j}];
+0203                 end
+0204                 
+0205                 %If a second row is needed
+0206                 if nExp>4
+0207                     secondFourX=pathway.listOfSpecies(i).x+pathway.listOfSpecies(i).w-16;
+0208                     for j=5:min(nExp,8)
+0209                         expRec=[expRec;secondFourX fourY(j-4) 16 pathway.listOfSpecies(i).h/4];
+0210                         expFace=[expFace;colorCodes{j}];
+0211                     end
+0212                 end
+0213             end
+0214         else
+0215             rxnRec=[rxnRec;position];
+0216         end
+0217         
+0218         %If no fluxes are specified then should only the name be printed.
+0219         %Flux values should only be printed if at least one of the fluxes
+0220         %is above the cutoff value
+0221         textToPrint={};
+0222         
+0223         %NOTE:  This is done since I know that I have names including '_' which is a reserved
+0224         %       character in LaTeX. This should be done more systematically
+0225         
+0226         %NOTE:  The notation used means that only flux values with with less than
+0227         %       nine characters can be used
+0228         
+0229         textToPrint{1,1}=strrep(pathway.listOfSpecies(i).name,'_','\_');
+0230         
+0231         %Check that the fluxes are specified
+0232         %NOTE: Should you only print if there are two fluxes?
+0233         if isfield(pathway.listOfSpecies(i),'flux') && isfield(pathway.listOfSpecies(i),'referenceFlux')
+0234             %Check that the value of one of the fluxes is above the cutoff value
+0235             if ~isempty(pathway.listOfSpecies(i).flux) && ~isempty(pathway.listOfSpecies(i).referenceFlux)
+0236                 if abs(pathway.listOfSpecies(i).referenceFlux)>=cutOff || abs(pathway.listOfSpecies(i).flux)>=cutOff
+0237                     textToPrint{2,1}=num2str(pathway.listOfSpecies(i).flux,'%0.4g');
+0238                     textToPrint{3,1}=num2str(pathway.listOfSpecies(i).referenceFlux,'%0.4g');
+0239                 end
+0240             end
+0241         end
+0242         
+0243         xPos=ones(numel(textToPrint),1)*(position(1)+3);
+0244         distance=position(4)/(numel(textToPrint)+1);
+0245         yPos=position(2)+distance:distance:(position(2)+position(4)-distance);
+0246         
+0247         rxnText=[rxnText;textToPrint];
+0248         rxnX=[rxnX;xPos];
+0249         rxnY=[rxnY;yPos'];
+0250     end
+0251 end
+0252 
+0253 %*** Print everything ***
+0254 
+0255 %Compartment rectangles
+0256 for i=1:size(compRec,1)
+0257     rectangle('edgecolor',[1 0.8 0.2], 'facecolor', [1 0.91 0.55], 'linewidth', 2, 'curvature', [0.05 0.05],...
+0258         'position',compRec(i,:));
+0259     rectangle('edgecolor',[1 0.8 0.2], 'facecolor', [1 1 1], 'linewidth', 1, 'curvature', [0.05 0.05],...
+0260         'position',compRec(i,:)+[12 12 -24 -24]);
+0261 end
+0262 
+0263 %Reaction lines
+0264 line(rxnLinesX',rxnLinesY','linewidth',0.1,'color',[0 0 0]);
+0265 
+0266 %Arrow lines
+0267 hold on;
+0268 for i=1:size(rxnArrows,1)
+0269     plotArrow(rxnArrows(i,1),rxnArrows(i,2),rxnArrows(i,3),rxnArrows(i,4),'linewidth',0.1,'edgecolor',rxnArrowsColor(i,:),'facecolor',rxnArrowsColor(i,:));
+0270 end
+0271 hold off;
+0272 
+0273 %Enzyme lines
+0274 line(enzLinesX',enzLinesY','marker','o','markeredgecolor',[0 0 0],'markersize',0.5,...
+0275     'markerfacecolor',[1 0.969 0.922],'linewidth',0.1,'color',[0 0 0]);
+0276 
+0277 %Metabolite rectangles
+0278 for i=1:size(metRec,1)
+0279     rectangle('edgecolor', [0 0 0], 'facecolor', [1 1 0.78], 'curvature', [0.8 0.8],...
+0280         'position',metRec(i,:),'linewidth',0.1);
+0281 end
+0282 
+0283 %Reaction rectangles
+0284 for i=1:size(rxnRec,1)
+0285     rectangle('edgecolor', rxnEdge(i,:), 'facecolor', rxnFace(i,:), 'linewidth',0.1,...
+0286         'curvature', [0.1 0.1], 'position',rxnRec(i,:));
+0287 end
+0288 
+0289 %Expression rectangles
+0290 for i=1:size(expRec,1)
+0291     rectangle('facecolor', expFace(i,:), 'linewidth',0.1, 'curvature', [0.1 0.1],...
+0292         'position',expRec(i,:));
+0293 end
+0294 
+0295 %Metabolite text
+0296 %Temporary thing to get it right for small networks as well. Should be
+0297 %calculated better!
+0298 if dimension(3)<5000
+0299     textSize=3;
+0300 else
+0301     textSize=0.5;
+0302 end
+0303 
+0304 text(metX,metY,metText,'fontname','Small Fonts','fontsize',textSize,'interpreter','tex',...
+0305     'HorizontalAlignment','center','verticalalignment','middle');
+0306 
+0307 %Reaction text
+0308 text(rxnX,rxnY,rxnText,'fontname','Small Fonts','fontsize',textSize,'interpreter','tex',...
+0309     'verticalalignment','middle','HorizontalAlignment','left');
+0310 
+0311 %Compartment text. The text is centered and at the bottom of the compartment
+0312 text(compX, compY,compText,'fontname','Small Fonts','fontsize',7,'interpreter','none',...
+0313     'HorizontalAlignment','center','verticalalignment','middle');
+0314 end
+0315 
+0316 function handles = plotArrow( x1,y1,x2,y2,varargin )
+0317 %
+0318 % plotArrow - plots an arrow to the current plot
+0319 %
+0320 % format:   handles = plotArrow( x1,y1,x2,y2 [,options...] )
+0321 %
+0322 % input:    x1,y1   - starting point
+0323 %           x2,y2   - end point
+0324 %           options - come as pairs of "property","value" as defined for "line" and "patch"
+0325 %                     controls, see matlab help for listing of these properties.
+0326 %                     note that not all properties where added, one might add them at the end of this file.
+0327 %
+0328 %                     additional options are:
+0329 %                     'headwidth':  relative to complete arrow size, default value is 0.07
+0330 %                     'headheight': relative to complete arrow size, default value is 0.15
+0331 %                     (encoded are maximal values if pixels, for the case that the arrow is very long)
+0332 %
+0333 % output:   handles - handles of the graphical elements building the arrow
+0334 %
+0335 % Example:  plotArrow( -1,-1,15,12,'linewidth',2,'color',[0.5 0.5 0.5],'facecolor',[0.5 0.5 0.5] );
+0336 %           plotArrow( 0,0,5,4,'linewidth',2,'headwidth',0.25,'headheight',0.33 );
+0337 %           plotArrow;   % will launch demo
+0338 
+0339 % =============================================
+0340 % constants (can be edited)
+0341 % =============================================
+0342 %NOTE: These should be 100 times smaller
+0343 alpha       = 15;   % head length
+0344 beta        = 7;   % head width
+0345 max_length  = 11;
+0346 %max_width   = 7;
+0347 
+0348 % =============================================
+0349 % check if head properties are given
+0350 % =============================================
+0351 % if ratio is always fixed, this section can be removed!
+0352 if ~isempty( varargin )
+0353     for c = 1:floor(length(varargin)/2)
+0354         switch lower(varargin{c*2-1})
+0355             % head properties - do nothing, since handled above already
+0356             case 'headheight',alpha = max( min( varargin{c*2},1 ),0.01 );
+0357             case 'headwidth', beta = max( min( varargin{c*2},1 ),0.01 );
+0358         end
+0359     end
+0360 end
+0361 
+0362 % =============================================
+0363 % calculate the arrow head coordinates
+0364 % =============================================
+0365 den         = x2 - x1 + eps;                                % make sure no devision by zero occurs
+0366 teta        = atan( (y2-y1)/den ) + pi*(x2<x1) - pi/2;      % angle of arrow
+0367 cs          = cos(teta);                                    % rotation matrix
+0368 ss          = sin(teta);
+0369 R           = [cs -ss;ss cs];
+0370 line_length = sqrt( (y2-y1)^2 + (x2-x1)^2 );                % sizes
+0371 head_length = min( line_length*alpha,max_length );
+0372 head_width  = min( line_length*beta,max_length );
+0373 x0          = x2*cs + y2*ss;                                % build head coordinats
+0374 y0          = -x2*ss + y2*cs;
+0375 coords      = R*[x0 x0+head_width/2 x0-head_width/2; y0 y0-head_length y0-head_length];
+0376 
+0377 % =============================================
+0378 % plot arrow  (= line + patch of a triangle)
+0379 % =============================================
+0380 h1          = plot( [x1,x2],[y1,y2],'k' );
+0381 h2          = patch( coords(1,:),coords(2,:),[0 0 0] );
+0382 
+0383 % =============================================
+0384 % return handles
+0385 % =============================================
+0386 handles = [h1 h2];
+0387 
+0388 % =============================================
+0389 % check if styling is required
+0390 % =============================================
+0391 % if no styling, this section can be removed!
+0392 if ~isempty( varargin )
+0393     for c = 1:floor(length(varargin)/2)
+0394         switch lower(varargin{c*2-1})
+0395             
+0396             % only patch properties
+0397             case 'edgecolor',   set( h2,'EdgeColor',varargin{c*2} );
+0398             case 'facecolor',   set( h2,'FaceColor',varargin{c*2} );
+0399             case 'facelighting',set( h2,'FaceLighting',varargin{c*2} );
+0400             case 'edgelighting',set( h2,'EdgeLighting',varargin{c*2} );
+0401                 
+0402                 % only line properties
+0403             case 'color'    , set( h1,'Color',varargin{c*2} );
+0404                 
+0405                 % shared properties
+0406             case 'linestyle', set( handles,'LineStyle',varargin{c*2} );
+0407             case 'linewidth', set( handles,'LineWidth',varargin{c*2} );
+0408             case 'parent',    set( handles,'parent',varargin{c*2} );
+0409                 
+0410                 % head properties - do nothing, since handled above already
+0411             case 'headwidth',
+0412             case 'headheight',
+0413                 
+0414         end
+0415     end
+0416 end
+0417 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/plotting/getColorCodes.html b/doc/plotting/getColorCodes.html new file mode 100644 index 000000000..67b68cb5e --- /dev/null +++ b/doc/plotting/getColorCodes.html @@ -0,0 +1,208 @@ + + + + Description of getColorCodes + + + + + + + + + +
Home > plotting > getColorCodes.m
+ + + +

getColorCodes +

+ +

PURPOSE ^

+
getColorCodes
+ +

SYNOPSIS ^

+
function [colorCodes, signChange, errorFlag]= getColorCodes(referenceFluxes, fluxes, maxChange, defaultColor, upColor, downColor)
+ +

DESCRIPTION ^

+
 getColorCodes
+    Calculates the coloring for a number of fluxes by comparing them to
+   reference fluxes.
+
+   referenceFluxes     vector of reference fluxes
+   fluxes              vector of fluxes. The number of elements in fluxes
+                       and referenceFluxes must be equal
+   maxChange           the logfold increase or decrease that corresponds
+                       to full negative or full positive coloring. Must
+                       be a positive value (optional, default 1)
+   defaultColor        a color in Matlab format to be used if there are no
+                       changes between the fluxes. This color is also used to
+                       calculate the transition between the colors for up and
+                       down regulated fluxes (optional, default [1 1 1])
+   upColor             a color in Matlab format to be used if the flux is
+                       larger than the reference flux (optional, default [0 1 0])
+   downColor           a color in Matlab format to be used if the flux is
+                       smaller than the reference flux (optional, default [1 0 0])
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 function [colorCodes, signChange, errorFlag]= getColorCodes(referenceFluxes, fluxes, maxChange, defaultColor, upColor, downColor)
+0002 % getColorCodes
+0003 %    Calculates the coloring for a number of fluxes by comparing them to
+0004 %   reference fluxes.
+0005 %
+0006 %   referenceFluxes     vector of reference fluxes
+0007 %   fluxes              vector of fluxes. The number of elements in fluxes
+0008 %                       and referenceFluxes must be equal
+0009 %   maxChange           the logfold increase or decrease that corresponds
+0010 %                       to full negative or full positive coloring. Must
+0011 %                       be a positive value (optional, default 1)
+0012 %   defaultColor        a color in Matlab format to be used if there are no
+0013 %                       changes between the fluxes. This color is also used to
+0014 %                       calculate the transition between the colors for up and
+0015 %                       down regulated fluxes (optional, default [1 1 1])
+0016 %   upColor             a color in Matlab format to be used if the flux is
+0017 %                       larger than the reference flux (optional, default [0 1 0])
+0018 %   downColor           a color in Matlab format to be used if the flux is
+0019 %                       smaller than the reference flux (optional, default [1 0 0])
+0020 
+0021 %   colorCodes          array list of colors in Matlab format in the same
+0022 %                       order as the fluxes
+0023 %   signChange          array list of boolean values where true indicates
+0024 %                       that there has been a sign change between the
+0025 %                       fluxes. Reactions with sign changes are not
+0026 %                       colored, but rather marked in another way. The
+0027 %                       order correspondes to the order of the fluxes
+0028 %   errorFlag           true if there has been an error
+0029 %
+0030 % Usage: [colorCodes, signChange, errorFlag]=getColorCodes(referenceFluxes,...
+0031 %           fluxes, maxChange, defaultColor, upColor, downColor)
+0032 
+0033 if nargin<6
+0034     downColor=[1 0 0];
+0035 end
+0036 if nargin<5
+0037     upColor=[0 1 0];
+0038 end
+0039 if nargin<4
+0040     defaultColor=[1 1 1];
+0041 end
+0042 if nargin<3
+0043     maxChange=1;
+0044 end
+0045 
+0046 %Checks that the flux vector and the reference flux vector have the same
+0047 %number of elements
+0048 if length(fluxes)~=length(referenceFluxes)
+0049     colorCodes={};
+0050     signChange={};
+0051     errorFlag=1;
+0052     fprintf('fluxes and referenceFluxes must have the same dimensions');
+0053     return;
+0054 end
+0055 
+0056 %Loops through the fluxes. If the reference flux is 0, then mark as
+0057 %upColor, if the flux is 0 then mark as downColor, and if both fluxes are 0
+0058 %then mark as defaultColor
+0059 for i=1:length(fluxes)
+0060     signChange{i}=false;
+0061     
+0062     if referenceFluxes(i)==0 || fluxes(i)==0
+0063         if referenceFluxes(i)==0 && fluxes(i)==0
+0064             colorCodes{i}=defaultColor;
+0065         else
+0066             if referenceFluxes(i)==0
+0067                 colorCodes{i}=upColor;
+0068             else
+0069                 colorCodes{i}=downColor;
+0070             end
+0071         end
+0072     else
+0073         %At the moment a negative flux that gets more negative is counted
+0074         %as being upregulated. This might be counter intuitive.
+0075         logvalue=log10(abs(fluxes(i))/abs(referenceFluxes(i)));
+0076         
+0077         %If there is a sign change
+0078         if fluxes(i)*referenceFluxes(i)<0
+0079             colorCodes{i}=defaultColor;
+0080             signChange{i}=true;
+0081         else
+0082             colorCodes{i}=getColor(logvalue, defaultColor, upColor, downColor, maxChange);
+0083         end
+0084     end
+0085 end
+0086 end
+0087 
+0088 function colorValue=getColor(logvalue, defaultColor, upColor, downColor, maxChange)
+0089 % getColor
+0090 %   Calculates the color for a specified logvalue.
+0091 %
+0092 %   logvalue            the logfold increase or desrease of a flux
+0093 %   compared to the
+0094 %                       corresponding reference flux. Must be a
+0095 %                       positive value
+0096 %   defaultColor        a color in Matlab format to be used if
+0097 %   there are no
+0098 %                       changes between the fluxes. This color is
+0099 %                       also used to calculate the transition
+0100 %                       between the colors for up and down
+0101 %                       regulated fluxes
+0102 %   upColor             a color in Matlab format to be used if the
+0103 %   flux is
+0104 %                       larger than the reference flux
+0105 %   downColor           a color in Matlab format to be used if the
+0106 %   flux is
+0107 %                       smaller than the reference flux
+0108 %   maxChange           the logfold increase or decrease that
+0109 %   corresponds
+0110 %                       to full negative or full positive coloring
+0111 %
+0112 %   colorValue          vector with the calculated color
+0113 %
+0114 % Usage: colorValue=getColor(logvalue, defaultColor, upColor,
+0115 %   downColor, maxChange)
+0116 
+0117 %If the flux has decreased
+0118 if logvalue<0
+0119     %If the flux is lower than 10^-maxChange of the original then
+0120     %color as downColor
+0121     if logvalue<-maxChange
+0122         colorValue=downColor;
+0123     else
+0124         %The color is linear from defaultColor to downColor
+0125         colorValue=[defaultColor(1)+(downColor(1)-defaultColor(1))*logvalue/(-maxChange)...
+0126             defaultColor(2)+(downColor(2)-defaultColor(2))*logvalue/(-maxChange)...
+0127             defaultColor(3)+(downColor(3)-defaultColor(3))*logvalue/(-maxChange)];
+0128     end
+0129     %If it has increased
+0130 else
+0131     %If the flux is higher than 10^maxChange times the original
+0132     %then color green
+0133     if logvalue>maxChange
+0134         colorValue=upColor;
+0135     else
+0136         %The color is linear from defaultColor to upColor
+0137         colorValue=[defaultColor(1)+(upColor(1)-defaultColor(1))*logvalue/(maxChange)...
+0138             defaultColor(2)+(upColor(2)-defaultColor(2))*logvalue/(maxChange)...
+0139             defaultColor(3)+(upColor(3)-defaultColor(3))*logvalue/(maxChange)];
+0140     end
+0141 end
+0142 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/plotting/getObjectiveString.html b/doc/plotting/getObjectiveString.html new file mode 100644 index 000000000..190f91cf5 --- /dev/null +++ b/doc/plotting/getObjectiveString.html @@ -0,0 +1,114 @@ + + + + Description of getObjectiveString + + + + + + + + + +
Home > plotting > getObjectiveString.m
+ + + +

getObjectiveString +

+ +

PURPOSE ^

+
getObjectiveString
+ +

SYNOPSIS ^

+
function objectiveString = getObjectiveString(max, objectiveNames, objectiveValues)
+ +

DESCRIPTION ^

+
 getObjectiveString
+   Returns a string representing the objective function (e.g. 'MAX Growth
+   - 0.5 HXT4').
+
+   max                 true if the objective function should be maximized
+   objectiveNames      cell array of reaction names
+   objectiveValues     the corresponding coefficients for each reaction
+
+   objectiveString     the calculated objective function
+
+ Usage: objectiveString = getObjectiveString(max, objectiveNames,
+           objectiveValues)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function objectiveString = getObjectiveString(max, objectiveNames, objectiveValues)
+0002 % getObjectiveString
+0003 %   Returns a string representing the objective function (e.g. 'MAX Growth
+0004 %   - 0.5 HXT4').
+0005 %
+0006 %   max                 true if the objective function should be maximized
+0007 %   objectiveNames      cell array of reaction names
+0008 %   objectiveValues     the corresponding coefficients for each reaction
+0009 %
+0010 %   objectiveString     the calculated objective function
+0011 %
+0012 % Usage: objectiveString = getObjectiveString(max, objectiveNames,
+0013 %           objectiveValues)
+0014 
+0015 objectiveString='';
+0016 
+0017 if max==true
+0018     objectiveString=[objectiveString 'MAX: '];
+0019 else
+0020     objectiveString=[objectiveString 'MIN: '];
+0021 end
+0022 
+0023 %Loops through the reactions
+0024 for i=1:length(objectiveNames)
+0025     %Add no sign if it's the first reaction
+0026     if i>1
+0027         if objectiveValues(i)==1
+0028             objectiveString=[objectiveString ' + ' objectiveNames{i}];
+0029             continue;
+0030         end
+0031         if objectiveValues(i)==-1
+0032             objectiveString=[objectiveString ' - ' objectiveNames{i}];
+0033             continue;
+0034         end
+0035         if objectiveValues(i)>=0
+0036             objectiveString=[objectiveString ' + ' num2str(objectiveValues(i)) ' ' objectiveNames{i}];
+0037         else
+0038             objectiveString=[objectiveString ' - ' num2str(abs(objectiveValues(i))) ' ' objectiveNames{i}];
+0039         end
+0040     else
+0041         if objectiveValues(i)==1
+0042             objectiveString=[objectiveString objectiveNames{i}];
+0043             continue;
+0044         end
+0045         if objectiveValues(i)==-1
+0046             objectiveString=[objectiveString '- ' objectiveNames{i}];
+0047             continue;
+0048         end
+0049         if objectiveValues(i)>=0
+0050             objectiveString=[objectiveString num2str(objectiveValues(i)) ' ' objectiveNames{i}];
+0051         else
+0052             objectiveString=[objectiveString '- ' num2str(abs(objectiveValues(i))) ' ' objectiveNames{i}];
+0053         end
+0054     end
+0055 end
+0056 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/plotting/index.html b/doc/plotting/index.html new file mode 100644 index 000000000..60a564fa0 --- /dev/null +++ b/doc/plotting/index.html @@ -0,0 +1,29 @@ + + + + Index for Directory plotting + + + + + + + + + + +
< Master indexIndex for plotting >
+ +

Index for plotting

+ +

Matlab files in this directory:

+ +
 colorSubsystemModified from colorSubsystemCD as distributed through COBRA Toolbox
 drawMapdrawMap
 drawPathwaydrawPathway
 getColorCodesgetColorCodes
 getObjectiveStringgetObjectiveString
 plotAdditionalInfoplotAdditionalInfo
 plotLabelsplotLabels
 setColorToMapRxnsUSAGE:
 setOmicDataToRxnsUSAGE:
 setTitleplotLabels
+ + + + +
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/plotting/plotAdditionalInfo.html b/doc/plotting/plotAdditionalInfo.html new file mode 100644 index 000000000..5cd902259 --- /dev/null +++ b/doc/plotting/plotAdditionalInfo.html @@ -0,0 +1,189 @@ + + + + Description of plotAdditionalInfo + + + + + + + + + +
Home > plotting > plotAdditionalInfo.m
+ + + +

plotAdditionalInfo +

+ +

PURPOSE ^

+
plotAdditionalInfo
+ +

SYNOPSIS ^

+
function plotAdditionalInfo(handle, pathway, additionalText, exampleBoxText,maxChange, defaultColor, upColor, downColor)
+ +

DESCRIPTION ^

+
 plotAdditionalInfo
+    Plots some additional information in a figure.
+
+   handle              handle to the figure to plot the information on
+   pathway             pathway structure of the metabolic network
+   additionalText      array list with additional text to print (e.g.
+                       fluxes or constraints)
+   exampleBoxText      array list of text to put in an example box. The
+                       text should explain what is printed in the enzyme
+                       boxes
+   maxChange           the logfold increase or decrease that corresponds
+                       to full negative or full positive coloring. Must
+                       be a positive value (optional, default 1)
+   defaultColor        a color in Matlab format to be used if there are no
+                       changes between the fluxes. This color is also used to 
+                       calculate the transition between the colors for up and
+                       down regulated fluxes (optional, default [1 1 1])
+   upColor             a color in Matlab format to be used if the flux is 
+                       larger than the reference flux (optional, default [0 1 0])
+   downColor           a color in Matlab format to be used if the flux is 
+                       smaller than the reference flux (optional, default [1 0
+                       0])
+
+   NOTE: At the moment the positions of the text/figures are (semi-)hard
+           coded.
+
+ Usage:  errorFlag = plotAdditionalInfo(handle, additionalText, exampleBoxText,...
+               maxChange, defaultColor, upColor, downColor)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function plotAdditionalInfo(handle, pathway, additionalText, exampleBoxText,...
+0002     maxChange, defaultColor, upColor, downColor)
+0003 % plotAdditionalInfo
+0004 %    Plots some additional information in a figure.
+0005 %
+0006 %   handle              handle to the figure to plot the information on
+0007 %   pathway             pathway structure of the metabolic network
+0008 %   additionalText      array list with additional text to print (e.g.
+0009 %                       fluxes or constraints)
+0010 %   exampleBoxText      array list of text to put in an example box. The
+0011 %                       text should explain what is printed in the enzyme
+0012 %                       boxes
+0013 %   maxChange           the logfold increase or decrease that corresponds
+0014 %                       to full negative or full positive coloring. Must
+0015 %                       be a positive value (optional, default 1)
+0016 %   defaultColor        a color in Matlab format to be used if there are no
+0017 %                       changes between the fluxes. This color is also used to
+0018 %                       calculate the transition between the colors for up and
+0019 %                       down regulated fluxes (optional, default [1 1 1])
+0020 %   upColor             a color in Matlab format to be used if the flux is
+0021 %                       larger than the reference flux (optional, default [0 1 0])
+0022 %   downColor           a color in Matlab format to be used if the flux is
+0023 %                       smaller than the reference flux (optional, default [1 0
+0024 %                       0])
+0025 %
+0026 %   NOTE: At the moment the positions of the text/figures are (semi-)hard
+0027 %           coded.
+0028 %
+0029 % Usage:  errorFlag = plotAdditionalInfo(handle, additionalText, exampleBoxText,...
+0030 %               maxChange, defaultColor, upColor, downColor)
+0031 
+0032 if nargin<8
+0033     downColor=[1 0 0];
+0034 end
+0035 if nargin<7
+0036     upColor=[0 1 0];
+0037 end
+0038 if nargin<6
+0039     defaultColor=[1 1 1];
+0040 end
+0041 if nargin<5
+0042     maxChange=1;
+0043 end
+0044 
+0045 %Finds the the dimensions of the metabolic network. The additional
+0046 %information will be positioned relative to that object.
+0047 dimension=getPathwayDimensions(pathway);
+0048 
+0049 %Plots the example box
+0050 rectangle('edgecolor',[0 0 0], 'facecolor', defaultColor, 'linewidth', 1,...
+0051     'position', [dimension(1)+dimension(3)+100 100 700 320],'curvature', [0.1 0.1]);
+0052 handle=text(dimension(1)+dimension(3)+100+6, 100+0.5*320,...
+0053     exampleBoxText,'fontname','Small Fonts','fontsize',2,...
+0054     'interpreter', 'tex','verticalalignment','middle','HorizontalAlignment','left');
+0055 handle=text(dimension(1)+dimension(3)+300+126, 20,...
+0056     'EXAMPLE:','fontname','Small Fonts','fontsize',4,...
+0057     'interpreter', 'tex','HorizontalAlignment','center','verticalalignment','middle');
+0058 
+0059 %Calculates 10 colors between upColor and defaultColor The color is linear
+0060 %from the upColor to the defaultColor
+0061 colorValues=[];
+0062 for i=1:11
+0063     logvalue=maxChange-(i-1)*0.1*maxChange;
+0064     colorValues=[colorValues;...
+0065         [defaultColor(1)+(upColor(1)-defaultColor(1))*logvalue/(maxChange)...
+0066         defaultColor(2)+(upColor(2)-defaultColor(2))*logvalue/(maxChange)...
+0067         defaultColor(3)+(upColor(3)-defaultColor(3))*logvalue/(maxChange)]];
+0068 end
+0069 %The color is linear from the defaultColor to downColor
+0070 for i=1:10
+0071     logvalue=i*0.1*maxChange;
+0072     colorValues=[colorValues;...
+0073         [defaultColor(1)+(downColor(1)-defaultColor(1))*logvalue/(maxChange)...
+0074         defaultColor(2)+(downColor(2)-defaultColor(2))*logvalue/(maxChange)...
+0075         defaultColor(3)+(downColor(3)-defaultColor(3))*logvalue/(maxChange)]];
+0076 end
+0077 
+0078 %Draw lines that represent the different colors
+0079 handle=text(dimension(1)+dimension(3)+100, 560,...
+0080     'log10(|condition A|/|condition B|)','fontname','Small Fonts','fontsize',3,...
+0081     'interpreter', 'tex','HorizontalAlignment','left','verticalalignment','middle');
+0082 lengthLine=40;
+0083 startX=dimension(1)+dimension(3)+150;
+0084 
+0085 startY=650;
+0086 width=6;
+0087 for i=1:size(colorValues,1)
+0088     line([startX; startX],[startY+(i-1)*lengthLine; startY+i*lengthLine],'color',colorValues(i,:),'linewidth',width);
+0089 end
+0090 
+0091 handle=text(startX+3*width, startY,...
+0092     ['-  ' num2str(maxChange)],'fontname','Small Fonts','fontsize',3,...
+0093     'interpreter', 'tex','HorizontalAlignment','left','verticalalignment','middle');
+0094 
+0095 handle=text(startX+3*width, startY+5.5*lengthLine,...
+0096     ['-  ' num2str(maxChange/2)],'fontname','Small Fonts','fontsize',3,...
+0097     'interpreter', 'tex','HorizontalAlignment','left','verticalalignment','middle');
+0098 
+0099 handle=text(startX+3*width, startY+10.5*lengthLine,...
+0100     ['-  0'],'fontname','Small Fonts','fontsize',3,...
+0101     'interpreter', 'tex','HorizontalAlignment','left','verticalalignment','middle');
+0102 
+0103 handle=text(startX+3*width, startY+15.5*lengthLine,...
+0104     ['-  -' num2str(maxChange/2)],'fontname','Small Fonts','fontsize',3,...
+0105     'interpreter', 'tex','HorizontalAlignment','left','verticalalignment','middle');
+0106 
+0107 handle=text(startX+3*width, startY+20.5*lengthLine,...
+0108     ['-  -' num2str(maxChange)],'fontname','Small Fonts','fontsize',3,...
+0109     'interpreter', 'tex','HorizontalAlignment','left','verticalalignment','middle');
+0110 
+0111 %Plots the additional text
+0112 handle=text(dimension(1)+dimension(3)+100, 1800,...
+0113     additionalText,'fontname','Small Fonts','fontsize',3,...
+0114     'interpreter', 'none','verticalalignment','top','HorizontalAlignment','left');
+0115 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/plotting/plotLabels.html b/doc/plotting/plotLabels.html new file mode 100644 index 000000000..1d1334079 --- /dev/null +++ b/doc/plotting/plotLabels.html @@ -0,0 +1,76 @@ + + + + Description of plotLabels + + + + + + + + + +
Home > plotting > plotLabels.m
+ + + +

plotLabels +

+ +

PURPOSE ^

+
plotLabels
+ +

SYNOPSIS ^

+
function plotLabels(handle,pathway)
+ +

DESCRIPTION ^

+
 plotLabels
+   Plots labels on the pathway map.
+
+   handle      handle to the figure on which to print the labels
+   pathway     pathway structure of the metabolic network
+
+   NOTE: Since there is not dedicated shape for labels the PHENOTYPE
+           shape is used. The name of the PHENOTYPE object is used.
+
+ Usage: plotLabels(handle,pathway)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function plotLabels(handle,pathway)
+0002 % plotLabels
+0003 %   Plots labels on the pathway map.
+0004 %
+0005 %   handle      handle to the figure on which to print the labels
+0006 %   pathway     pathway structure of the metabolic network
+0007 %
+0008 %   NOTE: Since there is not dedicated shape for labels the PHENOTYPE
+0009 %           shape is used. The name of the PHENOTYPE object is used.
+0010 %
+0011 % Usage: plotLabels(handle,pathway)
+0012 
+0013 for i=1:numel(pathway.listOfSpecies)
+0014     if strcmp(pathway.listOfSpecies(i).type,'PHENOTYPE')
+0015         handle=text(pathway.listOfSpecies(i).x+pathway.listOfSpecies(i).w/2, pathway.listOfSpecies(i).y,...
+0016             pathway.listOfSpecies(i).name,'fontname','Small Fonts','fontsize',4,...
+0017             'interpreter', 'tex','HorizontalAlignment','center','verticalalignment','middle');
+0018     end
+0019 end
+0020 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/plotting/setColorToMapRxns.html b/doc/plotting/setColorToMapRxns.html new file mode 100644 index 000000000..be20ac415 --- /dev/null +++ b/doc/plotting/setColorToMapRxns.html @@ -0,0 +1,659 @@ + + + + Description of setColorToMapRxns + + + + + + + + + +
Home > plotting > setColorToMapRxns.m
+ + + +

setColorToMapRxns +

+ +

PURPOSE ^

+
USAGE:
+ +

SYNOPSIS ^

+
function [modifiedMap, xmlMap, model2] = setColorToMapRxns (mapFileName, model, v1, rxnsFluxTask, rxnLineWidth, rxnLineColor, molFillColor)
+ +

DESCRIPTION ^

+
 USAGE:
+ [modifiedMap, xmlMap, model2] =
+   setColorToMapRxns (mapFileName, model, v1, rxnsFluxTask, rxnLineWidth, rxnLineColor, molFillColor)
+
+ INPUTS:
+ mapFileName           relative path to XML map (e.g. 'yeastMap1.0.xml')
+ model                 model structure
+ v1                    vector of fluxes
+ rxnsFluxTask          1 = Flux
+                       2 = Flux essentiality; map reactions causing any
+                           effect on growth (i.e. obj function)
+                       3 = Flux essentiality; map reactions causing no
+                           growth(i.e. obj function) when deleted, i.e.
+                           essential reactions
+                       4 = Flux essentiality; map reactions with not any
+                           effect on growth (i.e. obj function) when
+                           deleted
+                       5 = Omics
+ ADDITIONAL INPUTS:
+ rxnLineWidth          reaction line width; default = 5
+ rxnLineColor          reaction line color; default = Pathways; write
+                       'Subsystems' to color five subsystems only (central,
+                       AA, lipids, cofactors, nuclotides and energy).
+                       'Subsystems' option is the deault option at task 5
+ molFillColor          molecule fill color; default = true (i.e. white)
+                       molecule fill color; true (i.e. like CellDesigner default)
+ OUTPUTS:
+ modifiedMap           map with MATLAB structure, and modified reactions' line color and width
+ xmlMap                xml structure of the original map obtained from mapFileName
+ model2                model with modified subsystems
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
  • colorSubsystem Modified from colorSubsystemCD as distributed through COBRA Toolbox
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function [modifiedMap, xmlMap, model2] = setColorToMapRxns (mapFileName, model, v1, rxnsFluxTask, rxnLineWidth, rxnLineColor, molFillColor)
+0002 % USAGE:
+0003 % [modifiedMap, xmlMap, model2] =
+0004 %   setColorToMapRxns (mapFileName, model, v1, rxnsFluxTask, rxnLineWidth, rxnLineColor, molFillColor)
+0005 %
+0006 % INPUTS:
+0007 % mapFileName           relative path to XML map (e.g. 'yeastMap1.0.xml')
+0008 % model                 model structure
+0009 % v1                    vector of fluxes
+0010 % rxnsFluxTask          1 = Flux
+0011 %                       2 = Flux essentiality; map reactions causing any
+0012 %                           effect on growth (i.e. obj function)
+0013 %                       3 = Flux essentiality; map reactions causing no
+0014 %                           growth(i.e. obj function) when deleted, i.e.
+0015 %                           essential reactions
+0016 %                       4 = Flux essentiality; map reactions with not any
+0017 %                           effect on growth (i.e. obj function) when
+0018 %                           deleted
+0019 %                       5 = Omics
+0020 % ADDITIONAL INPUTS:
+0021 % rxnLineWidth          reaction line width; default = 5
+0022 % rxnLineColor          reaction line color; default = Pathways; write
+0023 %                       'Subsystems' to color five subsystems only (central,
+0024 %                       AA, lipids, cofactors, nuclotides and energy).
+0025 %                       'Subsystems' option is the deault option at task 5
+0026 % molFillColor          molecule fill color; default = true (i.e. white)
+0027 %                       molecule fill color; true (i.e. like CellDesigner default)
+0028 % OUTPUTS:
+0029 % modifiedMap           map with MATLAB structure, and modified reactions' line color and width
+0030 % xmlMap                xml structure of the original map obtained from mapFileName
+0031 % model2                model with modified subsystems
+0032 
+0033 if ~(exist('transformXML2Map')==2)
+0034     error('COBRA Toolbox is required, go to https://opencobra.github.io/cobratoolbox/')
+0035 end
+0036 
+0037 if nargin < 5 || rxnLineWidth == 0
+0038     rxnLineWidth = 0;
+0039     rxnLineColor = '';
+0040     molFillColor = true;
+0041 elseif nargin < 6
+0042     rxnLineColor = '';
+0043     molFillColor = true;
+0044 elseif nargin < 7
+0045     molFillColor = true;
+0046 end
+0047 if rxnsFluxTask == 5
+0048     rxnLineColor = 'Subsystems';
+0049 end
+0050 
+0051 [xmlMap, mapMap] = transformXML2Map(mapFileName);
+0052 if molFillColor == true
+0053     modifiedMap = unifyMetabolicMapCD(mapMap); % molColor whrite and rxnColor = ligthgray
+0054 elseif molFillColor == false
+0055     modifiedMap = mapMap; % like CellDesigner default
+0056 end
+0057 
+0058 %%%%%%%% Gettin reactions line width with normalized fluxes %%%%%%%%%%%%%
+0059 model2 = model; % to not overwrite model
+0060 flxs(:, 1) = v1; % to not overwrite v1
+0061 absFlxs = abs(flxs);
+0062 rxnLineWidthInMap = absFlxs / max(absFlxs); %normalize fluxes line width
+0063 if rxnsFluxTask == 1 && rxnLineWidth == 0
+0064     rxnLineWidthInMap(rxnLineWidthInMap > 0.1 & rxnLineWidthInMap <=  1) = 50;
+0065     rxnLineWidthInMap(rxnLineWidthInMap > 0.01 & rxnLineWidthInMap <= 0.1) = 25;
+0066     rxnLineWidthInMap(rxnLineWidthInMap > 0.001 & rxnLineWidthInMap <= 0.01) = 16;
+0067     rxnLineWidthInMap(rxnLineWidthInMap > 0.0001 & rxnLineWidthInMap <= 0.001) = 10;
+0068     rxnLineWidthInMap(rxnLineWidthInMap > 0.00001 & rxnLineWidthInMap <= 0.0001) = 6;
+0069 elseif rxnsFluxTask == 2 && rxnLineWidth == 0
+0070     rxnLineWidthInMap(rxnLineWidthInMap > 0.90 & rxnLineWidthInMap <=  0.95) =  6;
+0071     rxnLineWidthInMap(rxnLineWidthInMap > 0.80 & rxnLineWidthInMap <= 0.90) =  8;
+0072     rxnLineWidthInMap(rxnLineWidthInMap > 0.50 & rxnLineWidthInMap <= 0.80) = 11;
+0073     rxnLineWidthInMap(rxnLineWidthInMap > 0.25 & rxnLineWidthInMap <= 0.50) = 15;
+0074     rxnLineWidthInMap(rxnLineWidthInMap >= 0.00 & rxnLineWidthInMap <= 0.25) = 20;
+0075 elseif rxnsFluxTask == 1 && rxnLineWidth ~= 0.0
+0076     rxnLineWidthInMap(rxnLineWidthInMap == 1.0) = rxnLineWidth;
+0077 elseif rxnsFluxTask == 2 && rxnLineWidth ~= 0.0
+0078     rxnLineWidthInMap(rxnLineWidthInMap < 0.95) = rxnLineWidth;
+0079 elseif rxnsFluxTask == 3 && rxnLineWidth == 0.0
+0080     rxnLineWidthInMap(rxnLineWidthInMap == 0.0) = 5;
+0081 elseif rxnsFluxTask == 3 && rxnLineWidth ~= 0.0
+0082     rxnLineWidthInMap(rxnLineWidthInMap == 0.0) = rxnLineWidth;
+0083 elseif rxnsFluxTask == 4 && rxnLineWidth == 0.0
+0084     rxnLineWidthInMap(rxnLineWidthInMap > 0.95 & rxnLineWidthInMap <= 1.0) = 5.0;
+0085 elseif rxnsFluxTask == 4 && rxnLineWidth ~= 0.0
+0086     rxnLineWidthInMap(rxnLineWidthInMap > 0.95 & rxnLineWidthInMap <= 1.0) = rxnLineWidth;
+0087 elseif rxnsFluxTask == 5 && rxnLineWidth == 0.0
+0088     cutValue = 2.0; % transcriptomics minimum cut value of log change
+0089     rxnLineWidthInMap = absFlxs;
+0090     rxnLineWidthInMap(rxnLineWidthInMap > 5.0) = 30;
+0091     rxnLineWidthInMap(rxnLineWidthInMap > 4.0 & rxnLineWidthInMap <= 5.0) = 25;
+0092     rxnLineWidthInMap(rxnLineWidthInMap > 3.0 & rxnLineWidthInMap <= 4.0) = 20;
+0093     rxnLineWidthInMap(rxnLineWidthInMap > 2.0 & rxnLineWidthInMap <= 3.0) = 15;
+0094     rxnLineWidthInMap(rxnLineWidthInMap > 1.0 & rxnLineWidthInMap <= 2.0) = 10;
+0095     rxnLineWidthInMap(rxnLineWidthInMap >= 0.5 & rxnLineWidthInMap <= 1.0) =  5;
+0096 end
+0097 for i = 1:length(modifiedMap.rxnName)
+0098     a = find(ismember(model2.rxns, modifiedMap.rxnName{i}));
+0099     if isempty(a)
+0100         modifiedMap.rxnWidth{i} = 1;
+0101     else
+0102         modifiedMap.rxnWidth{i} = rxnLineWidthInMap(a);
+0103     end
+0104 end
+0105 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+0106 
+0107 %%%%%%%%% Cofactors not included in the analyses %%%%%%%%%%%%%%%%%%%%%%%%
+0108 %%%%%%%%% Compartments included in the analyses %%%%%%%%%%%%%%%%%%%%%%%%%
+0109 
+0110 % propossed cofactors list for PART A
+0111 cofactorsListA ={'h'; 'h2o'; 'nad'; 'nadh'; 'nadp'; 'nadph';...
+0112     'fad'; 'fadh'; 'ppi'; 'adp'; 'gtp'; 'gdp'; 'gmp'; ...
+0113     'utp'; 'udp'; 'ump'; 'ctp'; 'cdp'; 'cmp'};
+0114 
+0115 % propossed cofactors list for PART B
+0116 cofactorsListB ={'h'; 'h2o'; 'co2'; 'coa'; 'accoa'; 'nad'; 'nadh'; 'nadp'; 'nadph';...
+0117     'fad'; 'fadh'; 'pi'; 'ppi'; 'atp'; 'adp'; 'amp'; 'gtp'; 'gdp'; 'gmp';...
+0118     'utp'; 'udp'; 'ump'; 'ctp'; 'cdp'; 'cmp'; 'gthox'; 'gthrd_c'; 'amet_c';...
+0119     'ahcys_c'; 'glu__L'; 'gln__L'; 'akg'; 'nh4'};
+0120 
+0121 % compartments list
+0122 compartmentsList = {'_e'; '_c'; '_m'; '_n'; '_x'; '_v'; '_r'; '_g'};
+0123 
+0124 % include compartment to cofactor lists A and B
+0125 cofactorsListWcompA = cell(length(cofactorsListA), 1);
+0126 c = 1; % general counter
+0127 for i = 1:length(cofactorsListA)
+0128     for j = 1:length(compartmentsList)
+0129         cofactorsListWcompA{c, 1} = horzcat(cofactorsListA{i},compartmentsList{j});
+0130         c = c + 1;
+0131     end
+0132 end
+0133 cofactorsListWcompB = cell(length(cofactorsListB), 1);
+0134 c = 1;
+0135 for i = 1:length(cofactorsListB)
+0136     for j = 1:length(compartmentsList)
+0137         cofactorsListWcompB{c, 1}= horzcat(cofactorsListB{i},compartmentsList{j});
+0138         c = c + 1;
+0139     end
+0140 end
+0141 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+0142 
+0143 
+0144 %%%%%%%%%%%%%%%%%%%%%%%%%%%% PART A %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+0145 
+0146 % getting transport reactions
+0147 [nrxns,~] = size(model2.rxns);
+0148 transRxns = cell(nrxns, 1);
+0149 for j = 1:size(model2.rxns)
+0150     if true(contains(model2.subSystems {j}, 'S_Transport'))
+0151         transRxns{j, 1} = model2.rxns{j};
+0152     end
+0153 end
+0154 transRxns = transRxns(~cellfun('isempty',transRxns));
+0155 
+0156 % getting subStystems without transport
+0157 SubSystems = (unique(getModelSubSystems(model2)));
+0158 [nSubSystems, ~] = size(SubSystems);
+0159 subSystemsNoTrans = cell(nSubSystems, 1);
+0160 for i = 1:nSubSystems
+0161     if ~contains(SubSystems{i,1},'S_Transport')&& ...
+0162             ~contains(SubSystems{i, 1},'Extracellular exchange') &&...
+0163             ~contains(SubSystems{i, 1},'S_tRNA_charging')
+0164         subSystemsNoTrans{i, 1} = SubSystems{i, 1};
+0165     else
+0166         subSystemsNoTrans{i, 1} = {};
+0167     end
+0168 end
+0169 subSystemsNoTrans = subSystemsNoTrans(~cellfun('isempty',subSystemsNoTrans));
+0170 
+0171 % defining subSystems of trasnport reactions to be colored, these
+0172 % transport reactions complete reaction conections in subSystems which
+0173 % require conexions among diferents compartments
+0174 [nTransRxns,~] = size(transRxns);
+0175 [nSubSystemsNoTrans, ~] = size (subSystemsNoTrans);
+0176 totalRxnsToIncludeA = cell(nTransRxns,1);
+0177 for i = 1:nSubSystemsNoTrans
+0178     subSystemRxns = findRxnsFromSubSystem(model2, subSystemsNoTrans(i));
+0179     metsSubSystemRxns = findMetsFromRxns(model2, subSystemRxns);
+0180     [nMetsSubSystemRxns, ~] = size (metsSubSystemRxns);
+0181     % getting unique compartments
+0182     metsCompartment = cell(nMetsSubSystemRxns,1);
+0183     for j = 1:nMetsSubSystemRxns
+0184         str = metsSubSystemRxns{j};
+0185         [~, s] = size(str);
+0186         metsCompartment{j,1} = str(s-1:s);
+0187     end
+0188     metsCompartment = (unique(metsCompartment));
+0189     [nUniqueMetsComp, ~] = size(metsCompartment);
+0190     
+0191     if nUniqueMetsComp > 1
+0192         % getting duplicated mets like 'pyr_c' and 'pyr_m' which are 'pyr'
+0193         % and pyr after erasing the compartment signature
+0194         metsFromSubSystemRxnsNoComp = cell(nMetsSubSystemRxns,1);
+0195         for j = 1:nMetsSubSystemRxns
+0196             str = metsSubSystemRxns{j};
+0197             [z, s] = size(str);
+0198             metsFromSubSystemRxnsNoComp{j, 1} = str(1:s-2); % erasing comp signature
+0199         end
+0200         [~, o, ~] = unique(metsFromSubSystemRxnsNoComp,'first');
+0201         indexToDupes = find(not(ismember(1:numel(metsFromSubSystemRxnsNoComp),o)));
+0202         [~, nIndexToDupes] = size(indexToDupes);
+0203         duplicatedMets = cell(nIndexToDupes,1);
+0204         for j = 1:nIndexToDupes
+0205             duplicatedMets(j, 1) = metsFromSubSystemRxnsNoComp (indexToDupes(1, j));
+0206         end
+0207         
+0208         % getting reactions from duplicated mets
+0209         dulicatedRxnMets = cell(nIndexToDupes * nUniqueMetsComp,1);
+0210         c = 1; % duplicatedRxnMets counter
+0211         for j = 1:nIndexToDupes
+0212             str = duplicatedMets{j, 1};
+0213             if ~ismember(str, cofactorsListA)
+0214                 for k = 1:nUniqueMetsComp
+0215                     str1 = metsCompartment{k};
+0216                     if ~ismember(str1, compartmentsList(2)) % compartment '_c'
+0217                         dulicatedRxnMets{c, 1} = {horzcat(str, '_c'), horzcat(str, str1)};
+0218                         c = c + 1;
+0219                     end
+0220                 end
+0221             end
+0222         end
+0223         dulicatedRxnMets = dulicatedRxnMets(~cellfun('isempty',dulicatedRxnMets));
+0224         [ndulicatedRxnMets, ~] = size(dulicatedRxnMets);
+0225         % from duplicated reactions, get reactions to subscribe a reactions
+0226         % subsystem from non transport subsystems
+0227         rxnsToInclude = cell(ndulicatedRxnMets, 1);
+0228         for j = 1:ndulicatedRxnMets
+0229             metsToFindInTrasnportRxns = dulicatedRxnMets{j, 1};
+0230             for k = 1:nTransRxns
+0231                 rxnFormula = printRxnFormula(model2, transRxns{k, 1}, false);
+0232                 if true(contains(string(rxnFormula), metsToFindInTrasnportRxns (1, 1)))
+0233                     if true(contains(rxnFormula, metsToFindInTrasnportRxns (1, 2)))
+0234                         rxnsToInclude{j, 1} = transRxns{k, 1};
+0235                     end
+0236                 end
+0237             end
+0238         end
+0239         rxnsToInclude = rxnsToInclude(~cellfun('isempty',rxnsToInclude));
+0240         rxnsToInclude = unique(rxnsToInclude);
+0241         [s, ~] = size(rxnsToInclude);
+0242         totalRxnsToIncludeA = [totalRxnsToIncludeA; rxnsToInclude];
+0243         
+0244         for j = 1:s
+0245             rxnID = findRxnIDs(model2, rxnsToInclude{j});
+0246             model2.subSystems(rxnID) = {subSystemsNoTrans(i)};
+0247         end
+0248         
+0249     end
+0250 end
+0251 totalRxnsToIncludeA = totalRxnsToIncludeA(~cellfun('isempty',totalRxnsToIncludeA));
+0252 totalRxnsToIncludeA = unique(totalRxnsToIncludeA);
+0253 
+0254 %%%%%%%%%%%%%%%%%%%%%%%%%%%% PART B %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+0255 
+0256 % Get subsystems category. This is based on the number of conexions that a
+0257 % subsystem includes in the genome scale metabolic model2
+0258 subsLength ={};
+0259 for i = 1:length(subSystemsNoTrans)
+0260     rxnsSubs = findRxnsFromSubSystem(model2,subSystemsNoTrans(i));
+0261     metsSubsRxns = findMetsFromRxns(model2, rxnsSubs);
+0262     metsSubsRxnsNoCof = {};
+0263     for j = 1:length(metsSubsRxns)
+0264         if ~ismember(metsSubsRxns(j),cofactorsListWcompB)
+0265             metsSubsRxnsNoCof{j,1} = char(metsSubsRxns(j));
+0266         end
+0267     end
+0268     metsSubsRxnsNoCof = metsSubsRxnsNoCof(~cellfun('isempty',metsSubsRxnsNoCof));
+0269     
+0270     metsRxns = findRxnsFromMets(model2, metsSubsRxnsNoCof);
+0271     metsRxnsSubs = {};
+0272     for j = 1:length(metsRxns)
+0273         rxnID = findRxnIDs(model2,metsRxns(j));
+0274         metsRxnsSubs{j,1} = string(model2.subSystems(rxnID));
+0275     end
+0276     metsRxnsSubs = unique(string(metsRxnsSubs));
+0277     subsLength{i,1} = length(metsRxnsSubs);
+0278     subsLength{i,2} = subSystemsNoTrans{i};
+0279 end
+0280 
+0281 % Get  remaining transport reacctions, namely, reactions not included in
+0282 % PART A
+0283 
+0284 [nTransRxns, ~] = size(transRxns);
+0285 remainingTransRxns = cell(nTransRxns, 1);
+0286 for i = 1:nTransRxns
+0287     if ~ismember(transRxns(i),totalRxnsToIncludeA)
+0288         remainingTransRxns{i,1} = transRxns{i, 1};
+0289     end
+0290 end
+0291 remainingTransRxns = remainingTransRxns(~cellfun('isempty',remainingTransRxns));
+0292 
+0293 % Assign remaining transport reactions
+0294 nonIncludSubs = {'S_tRNA_charging', 'S_Other',...
+0295     'Biomass and maintenance functions', };
+0296 totalRxnsToIncludeAB = totalRxnsToIncludeA;
+0297 remTransRxnsWnewSubs = {};
+0298 remTransRxnsSubs = {};
+0299 rxnsToInclude = cell(length(remainingTransRxns), 1);
+0300 subSToInclude = cell(length(remainingTransRxns), 1);
+0301 for i = 1:length(remainingTransRxns)
+0302     metsRemTransRxns = findMetsFromRxns(model2, remainingTransRxns(i));
+0303     metsRxns = {};
+0304     for j = 1:length(metsRemTransRxns)
+0305         if true(contains(metsRemTransRxns{j},'_c') &&...
+0306                 ~ismember(metsRemTransRxns(j), cofactorsListWcompB))
+0307             metsRxns = findRxnsFromMets(model2,metsRemTransRxns(j));
+0308         end
+0309     end
+0310     metsRxns = metsRxns(~cellfun('isempty',metsRxns));
+0311     
+0312     rxnSubs = {};
+0313     for j = 1:length(metsRxns)
+0314         rxnID = findRxnIDs(model2, metsRxns(j));
+0315         rxnSubs{j,1} = model2.subSystems{rxnID};
+0316     end
+0317     rxnSubs = rxnSubs(~cellfun('isempty',rxnSubs));
+0318     
+0319     r = [];
+0320     rankMax = 0;
+0321     subSToUseStr = cell(1,1);
+0322     for j = 1:length(rxnSubs)
+0323         if true(~ismember(string(metsRxns(j)),totalRxnsToIncludeA))
+0324             for k = 1:length(subsLength)
+0325                 if true(and(ismember(rxnSubs{j}, subsLength{k,2}),...
+0326                         ~ismember(rxnSubs{j}, nonIncludSubs)))
+0327                     r(k, 1) = subsLength{k, 1};
+0328                     subSToUseStr{1, 1} = string(subsLength(k,2));
+0329                     if k > 1
+0330                         if true(rankMax < r(k, 1))
+0331                             rankMax = r(k, 1);
+0332                             subSToUseStr{1, 1} = string(subsLength(k,2));
+0333                         end
+0334                     end
+0335                 end
+0336             end
+0337         end
+0338     end
+0339     if ~isempty(subSToUseStr(1,1))
+0340         rxnsToInclude{i} = remainingTransRxns{i};
+0341         subSToInclude{i} = char(subSToUseStr{1, 1});
+0342         remTransRxnsWnewSubs{i,1} = remainingTransRxns(i);
+0343         remTransRxnsSubs{i,1} = subSToUseStr(1, 1);
+0344         totalRxnsToIncludeAB = [totalRxnsToIncludeAB; rxnsToInclude];
+0345     end
+0346 end
+0347 totalRxnsToIncludeAB = totalRxnsToIncludeAB(~cellfun('isempty',totalRxnsToIncludeAB));
+0348 totalRxnsToIncludeAB = unique(totalRxnsToIncludeAB);
+0349 
+0350 for j = 1:length(rxnsToInclude)
+0351     rxnID = findRxnIDs(model2, rxnsToInclude{j});
+0352     model2.subSystems(rxnID) = {subSToInclude(j)};
+0353 end
+0354 
+0355 %%%%%%%%%%%%%%%%%%%%%%%% ASIGN SUBSYSTEMS' COLOR %%%%%%%%%%%%%%%%%%%%%%%%%%%
+0356 
+0357 % Selection of reactions to include in the map
+0358 if rxnsFluxTask == 1
+0359     for i = 1:length(model2.rxns)
+0360         if absFlxs(i)==0 % zero flux reactions are not included
+0361             model2.subSystems(i) = {{'NonIncluded'}};  % included at the end
+0362         end
+0363     end
+0364 elseif rxnsFluxTask == 2
+0365     for i = 1:length(model2.rxns)
+0366         if absFlxs(i) > 0.95 * max(absFlxs)% reactions causing growth (i.e. obj function) defect when deleting
+0367             model2.subSystems(i) = {{'NonIncluded'}};   % included at the end
+0368         end
+0369     end
+0370 elseif rxnsFluxTask == 3
+0371     for i = 1:length(model2.rxns)
+0372         if absFlxs(i) > 0.0 % zero flux reactions only, i.e. essential reations
+0373             model2.subSystems(i) = {{'NonIncluded'}};   % included at the end
+0374         end
+0375     end
+0376 elseif rxnsFluxTask == 4
+0377     for i = 1:length(model2.rxns)
+0378         if absFlxs(i) < 0.95 * max(absFlxs)% reactions fluxes causing no growth (i.e. obj function) defect when deleting
+0379             model2.subSystems(i) = {{'NonIncluded'}};   % included at the end
+0380         end
+0381     end
+0382 elseif rxnsFluxTask == 5
+0383     for i = 1:length(model2.rxns)
+0384         if absFlxs(i) < cutValue % zero flux reactions are not included
+0385             model2.subSystems(i) = {{'NonIncluded'}};  % included at the end
+0386         end
+0387     end
+0388 end
+0389 
+0390 %See colors letter-code at:
+0391 %la.mathworks.com/matlabcentral/mlc-downloads/downloads/submissions/24497/versions/2/screenshot.PNG
+0392 %[xmlMap, mapMap] = transformXML2Map('YeastMapUnified1.0b.xml');
+0393 centralPathsList = {'S_GlycolysisGluconeogenesis', 'S_Pentose_Phosphate_Pathway',...
+0394     'S_Pyruvate_Metabolism', 'S_Citric_Acid_Cycle', 'S_Taurine_Metabolism',...
+0395     'S_Starch_and_Sucrose_Metabolism', 'S_Xylose_Metabolism',...
+0396     'S_Fructose_and_Mannose_Metabolism', 'S_Galactose_metabolism',...
+0397     'S_Arabinose_Metabolism', 'S_Alternate_Carbon_Metabolism', 'S_Methane_Metabolism'};
+0398 aminoacPathsList = {'S_Glutamate_metabolism', 'S_Glutamine_Metabolism',...
+0399     'S_Alanine_and_Aspartate_Metabolism', 'S_Histidine_Metabolism',...
+0400     'S_Threonine_and_Lysine_Metabolism', 'S_Glycine_and_Serine_Metabolism',...
+0401     'S_Tyrosine__Tryptophan__and_Phenylalanine_Metabolism',...
+0402     'S_Arginine_and_Proline_Metabolism', 'S_Cysteine_Metabolism',...
+0403     'S_Methionine_Metabolism', 'S_Valine__Leucine__and_Isoleucine_Metabolism',...
+0404     'S_Other_Amino_Acid_Metabolism', 'S_Asparagine_metabolism', 'S_Nitrogen_Metabolism'};
+0405 cofactorsPathsList = {'S_NAD_Biosynthesis', 'S_Pantothenate_and_CoA_Biosynthesis',...
+0406     'S_Folate_Metabolism', 'S_Riboflavin_Metabolism', 'S_Quinone_Biosynthesis',...
+0407     'S_Porphyrin_and_Chlorophyll_Metabolism'};
+0408 lipidsPathsList = {'S_Fatty_Acid__Biosynthesis', 'S_Fatty_Acid_Degradation',...
+0409     'S_Fatty_Acid_Metabolism', 'S_Glycerolipid_Metabolism', 'S_Glycoprotein_Metabolism',...
+0410     'S_Phospholipid_Biosynthesis', 'S_Phospholipid_Metabolism',...
+0411     'S_Sphingolipid_Metabolism', 'S_Sterol_Metabolism'};
+0412 nucleotidsPathsList = {'S_Purine_and_Pyrimidine_Biosynthesis',...
+0413     'S_Nucleotide_Salvage_Pathway', 'S_Thiamine_Metabolism', 'S_Pyridoxine_Metabolism'};
+0414 enrgyPathsList = {'Biomass and maintenance functions', 'S_Anaplerotic_reactions',...
+0415     'S_Oxidative_Phosphorylation'};
+0416 colors = createColorsMap;
+0417 
+0418 if isempty(rxnLineColor)||rxnLineColor == "Pathways"
+0419     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_GlycolysisGluconeogenesis', 'DARKBLUE');
+0420     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Pentose_Phosphate_Pathway', 'STEELBLUE');
+0421     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Pyruvate_Metabolism', 'DODGERBLUE');
+0422     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Citric_Acid_Cycle', 'MEDIUMBLUE');
+0423     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Taurine_Metabolism', 'MEDIUMBLUE');
+0424     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Starch_and_Sucrose_Metabolism', 'BLUE');
+0425     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Xylose_Metabolism', 'STEELBLUE');
+0426     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Fructose_and_Mannose_Metabolism', 'DODGERBLUE');
+0427     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Galactose_metabolism', 'MEDIUMBLUE');
+0428     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Arabinose_Metabolism', 'BLUE');
+0429     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Alternate_Carbon_Metabolism', 'DARKBLUE');
+0430     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Methane_Metabolism', 'DARKBLUE');
+0431     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Taurine_Metabolism', 'DARKBLUE');
+0432     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Anaplerotic_reactions', 'CRIMSON');
+0433     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Complex_Alcohol_Metabolism', 'MAROON');
+0434     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Oxidative_Phosphorylation', 'RED');
+0435     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Purine_and_Pyrimidine_Biosynthesis', 'PINK');
+0436     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Nucleotide_Salvage_Pathway', 'HOTPINK');
+0437     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Thiamine_Metabolism', 'MAGENTA');
+0438     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Pyridoxine_Metabolism', 'PINK');
+0439     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_NAD_Biosynthesis', 'PLUM');
+0440     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Pantothenate_and_CoA_Biosynthesis', 'VIOLET');
+0441     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Folate_Metabolism', 'DARKORCHID');
+0442     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Riboflavin_Metabolism', 'PURPLE');
+0443     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Quinone_Biosynthesis', 'MEDIUMORCHID');
+0444     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Porphyrin_and_Chlorophyll_Metabolism', 'PLUM');
+0445     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Glutamate_metabolism', 'ORANGE');
+0446     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Glutamine_Metabolism', 'DARKORANGE');
+0447     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Alanine_and_Aspartate_Metabolism', 'CORAL');
+0448     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Histidine_Metabolism', 'GOLD');
+0449     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Threonine_and_Lysine_Metabolism', 'ORANGE');
+0450     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Glycine_and_Serine_Metabolism', 'DARKORANGE');
+0451     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Tyrosine__Tryptophan__and_Phenylalanine_Metabolism', 'CORAL');
+0452     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Arginine_and_Proline_Metabolism', 'GOLD');
+0453     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Cysteine_Metabolism', 'ORANGE');
+0454     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Methionine_Metabolism', 'DARKORANGE');
+0455     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Valine__Leucine__and_Isoleucine_Metabolism', 'CORAL');
+0456     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Other_Amino_Acid_Metabolism', 'GOLD');
+0457     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Asparagine_metabolism', 'ORANGE');
+0458     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Nitrogen_Metabolism', 'DARKORANGE');
+0459     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Fatty_Acid__Biosynthesis', 'FORESTGREEN');
+0460     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Fatty_Acid_Degradation', 'MEDIUMSEAGREEN');
+0461     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Fatty_Acid_Metabolism', 'DARKGREEN');
+0462     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Glycerolipid_Metabolism', 'SEAGREEN');
+0463     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Glycoprotein_Metabolism', 'FORESTGREEN');
+0464     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Phospholipid_Biosynthesis', 'MEDIUMSEAGREEN');
+0465     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Phospholipid_Metabolism', 'DARKGREEN');
+0466     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Sphingolipid_Metabolism', 'SEAGREEN');
+0467     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Sterol_Metabolism', 'FORESTGREEN');
+0468     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Other', 'BLACK');
+0469     modifiedMap = colorSubsystem(modifiedMap, model2, 'Biomass and maintenance functions', 'RED');
+0470 elseif rxnLineColor == "Subsystems"
+0471     modifiedMap = colorSubsystem(modifiedMap, model2, centralPathsList, 'BLUE'); %mapMap to fluxMap
+0472     modifiedMap = colorSubsystem(modifiedMap, model2, aminoacPathsList, 'ORANGE');
+0473     modifiedMap = colorSubsystem(modifiedMap, model2, cofactorsPathsList, 'ORCHID');
+0474     modifiedMap = colorSubsystem(modifiedMap, model2, lipidsPathsList, 'LIME');
+0475     modifiedMap = colorSubsystem(modifiedMap, model2, nucleotidsPathsList, 'MAGENTA');
+0476     modifiedMap = colorSubsystem(modifiedMap, model2, enrgyPathsList, 'RED');
+0477     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Complex_Alcohol_Metabolism', 'GOLDENROD');
+0478     modifiedMap = colorSubsystem(modifiedMap, model2, 'S_Other', 'GOLDENROD');
+0479 elseif ~(rxnLineColor == "Subsystems" || rxnLineColor == "Payhways" || isempty(rxnLineColor))
+0480     for i = 1:length(modifiedMap.rxnName)
+0481         a = find(ismember(model2.rxns, modifiedMap.rxnName{i}));
+0482         if ~isempty(a) & string(model2.subSystems(a)) ~= "NonIncluded"
+0483             modifiedMap.rxnColor(i, 1) = {colors(rxnLineColor)};
+0484         end
+0485     end
+0486 end
+0487 if rxnLineColor == "Subsystems" || rxnLineColor == "Payhways" || isempty(rxnLineColor)
+0488     h2o = {'H2Ot', 'H2Otm',    'H2Otn', 'H2Otv', 'H2Otp', 'H2Oter'};
+0489     for i = 1:length(modifiedMap.rxnName)
+0490         a = find(ismember(model2.rxns, modifiedMap.rxnName{i}));
+0491         for j = 1:length(h2o)
+0492             if ~isempty(a) & string(modifiedMap.rxnName{i}) == string(h2o(j))...
+0493                     & string(model2.subSystems(a)) ~= "NonIncluded"
+0494                 modifiedMap.rxnColor(i, 1) = {colors('CYAN')};
+0495             end
+0496         end
+0497     end
+0498     o2 = {'O2t', 'O2tm', 'O2ter', 'O2tp'};
+0499     for i = 1:length(modifiedMap.rxnName)
+0500         a = find(ismember(model2.rxns, modifiedMap.rxnName{i}));
+0501         for j = 1:length(o2)
+0502             if ~isempty(a) & string(modifiedMap.rxnName{i}) == string(o2(j))...
+0503                     & string(model2.subSystems(a)) ~= "NonIncluded"
+0504                 modifiedMap.rxnColor(i, 1) = {colors('CYAN')};
+0505             end
+0506         end
+0507     end
+0508     Pi = {'PIt2r', 'PIt2m', 'PIt5m', 'PIt2n', 'PIt2v', 'PIt2p', 'ATPtm_H', 'ATPtp_H', ...
+0509         'ATP2tp_H', 'ATPS3g', 'ATPS3v', 'UTPtm', 'CTPtm', 'GTPt2m', 'ATPS'};
+0510     for i = 1:length(modifiedMap.rxnName)
+0511         a = find(ismember(model2.rxns, modifiedMap.rxnName{i}));
+0512         for j = 1:length(Pi)
+0513             if ~isempty(a) & string(modifiedMap.rxnName{i}) == string(Pi(j))...
+0514                     & string(model2.subSystems(a)) ~= "NonIncluded"
+0515                 modifiedMap.rxnColor(i, 1) = {colors('RED')};
+0516             end
+0517         end
+0518     end
+0519     co2 = {'CO2t', 'CO2tg', 'CO2tm', 'CO2tn', 'HCO3tn', 'CO2tv', 'CO2tp'};
+0520     for i = 1:length(modifiedMap.rxnName)
+0521         a = find(ismember(model2.rxns, modifiedMap.rxnName{i}));
+0522         for j = 1:length(co2)
+0523             if ~isempty(a) & string(modifiedMap.rxnName{i}) == string(co2(j))...
+0524                     & string(model2.subSystems(a)) ~= "NonIncluded"
+0525                 modifiedMap.rxnColor(i, 1) = {colors('SLATEGRAY')};
+0526             end
+0527         end
+0528     end
+0529     aa = {'MMETt2', 'GLUt2r', 'GLNt2r', 'GLNt7', 'GLUt7', 'LCYSTintv', 'NH4t', 'TCHOLAabcv'};
+0530     for i = 1:length(modifiedMap.rxnName)
+0531         a = find(ismember(model2.rxns, modifiedMap.rxnName{i}));
+0532         for j = 1:length(aa)
+0533             if ~isempty(a) & string(modifiedMap.rxnName{i}) == string(aa(j))...
+0534                     & string(model2.subSystems(a)) ~= "NonIncluded"
+0535                 modifiedMap.rxnColor(i, 1) = {colors('ORANGE')};
+0536             end
+0537         end
+0538     end
+0539     cenMet = {'COAtim', 'NAt3_1', 'MALS'};
+0540     for i = 1:length(modifiedMap.rxnName)
+0541         a = find(ismember(model2.rxns, modifiedMap.rxnName{i}));
+0542         for j = 1:length(cenMet)
+0543             if ~isempty(a) & string(modifiedMap.rxnName{i}) == string(cenMet(j))...
+0544                     & string(model2.subSystems(a)) ~= "NonIncluded"
+0545                 modifiedMap.rxnColor(i, 1) = {colors('BLUE')};
+0546             end
+0547         end
+0548     end
+0549     lip = {'G3PIt'};
+0550     for i = 1:length(modifiedMap.rxnName)
+0551         a = find(ismember(model2.rxns, modifiedMap.rxnName{i}));
+0552         for j = 1:length(lip)
+0553             if ~isempty(a) & string(modifiedMap.rxnName{i}) == string(lip(j))...
+0554                     & string(model2.subSystems(a)) ~= "NonIncluded"
+0555                 modifiedMap.rxnColor(i, 1) = {colors('LIME')};
+0556             end
+0557         end
+0558     end
+0559 end
+0560 
+0561 if rxnsFluxTask == 5 % change color to dark-color in negative values
+0562     for i = 1:length(modifiedMap.rxnName)
+0563         valueskeys = values(colors)';
+0564         valueskeys (:,2) = keys(colors)';
+0565         a = find(ismember(valueskeys, modifiedMap.rxnColor{i, 1}));
+0566         b = find(ismember(model2.rxns, modifiedMap.rxnName{i}));
+0567         if ~isempty(b) & v1(b) < 0 & string(model2.subSystems(b)) ~= "NonIncluded"
+0568             if string(valueskeys (a,2)) == 'LIME'
+0569                 modifiedMap.rxnColor(i, 1) = {colors('GREEN')};
+0570             else
+0571                 rxnColor =strcat('DARK', char(valueskeys (a(1,1),2)));
+0572                 if string(rxnColor) == 'DARKAQUA'
+0573                     rxnColor = 'DARKCYAN';
+0574                 elseif string(rxnColor) == 'DARKFUCHSIA'
+0575                     rxnColor = 'DARKMAGENTA';
+0576                 end
+0577                 modifiedMap.rxnColor(i, 1) = {colors(rxnColor)};
+0578             end
+0579         end
+0580     end
+0581 end
+0582 
+0583 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/plotting/setOmicDataToRxns.html b/doc/plotting/setOmicDataToRxns.html new file mode 100644 index 000000000..7f65dc6c8 --- /dev/null +++ b/doc/plotting/setOmicDataToRxns.html @@ -0,0 +1,103 @@ + + + + Description of setOmicDataToRxns + + + + + + + + + +
Home > plotting > setOmicDataToRxns.m
+ + + +

setOmicDataToRxns +

+ +

PURPOSE ^

+
USAGE:
+ +

SYNOPSIS ^

+
function v1 = setOmicDataToRxns(omics, model)
+ +

DESCRIPTION ^

+
 USAGE:
+ v1 = setOmicDataToRxns(omics, model)
+ INPUTS:
+ omics     two column cell array with genes and log-fold expression changes
+ model     model structure
+ OUTPUTS:
+ v1       vector with expression changes in metabolic genes
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function v1 = setOmicDataToRxns(omics, model)
+0002 % USAGE:
+0003 % v1 = setOmicDataToRxns(omics, model)
+0004 % INPUTS:
+0005 % omics     two column cell array with genes and log-fold expression changes
+0006 % model     model structure
+0007 % OUTPUTS:
+0008 % v1       vector with expression changes in metabolic genes
+0009 
+0010 j = 1;
+0011 for i = 1:length(model.genes)
+0012     a = find(ismember(omics(:,1), model.genes{i}));
+0013     if ~isempty(a)
+0014         genesList{j,1} = omics{a,1};
+0015         genesList{j,2} = omics{a,2};
+0016         j = j + 1;
+0017     end
+0018 end
+0019 rxnsFromGenes = findRxnsFromGenes(model, genesList(:,1));
+0020 s = struct2cell(rxnsFromGenes);
+0021 k = 1;
+0022 for i = 1:length(s)
+0023     s1 = s{i};
+0024     [l,~]=size(s1);
+0025     for j = 1:l
+0026         s2=s1{j};
+0027         rxnsList{k,1}=s2;
+0028         k = k + 1;
+0029     end
+0030 end
+0031 rxnsList = (unique(rxnsList));
+0032 
+0033 for i = 1:length(rxnsList)
+0034     rxnsList {i,2} = findGenesFromRxns(model, rxnsList{i});
+0035 end
+0036 v1 = zeros(length(model.rxns),1);
+0037 for i = 1:length(rxnsList)
+0038     rxnGenes = rxnsList{i,2};
+0039     indRxnGene = rxnGenes{1,1};
+0040     c = 0.0;
+0041     for j = 1:length(indRxnGene)
+0042         a = find(ismember(genesList(:,1),indRxnGene{j,1}));
+0043         if ~isempty(a) && abs(cell2mat(genesList(a,2))) >= c
+0044             c = cell2mat(genesList(a,2));
+0045         end
+0046     end
+0047     rxnID = findRxnIDs(model,rxnsList{i,1});
+0048     v1(rxnID,1) = c;
+0049 end
+0050 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/plotting/setTitle.html b/doc/plotting/setTitle.html new file mode 100644 index 000000000..4b738c81a --- /dev/null +++ b/doc/plotting/setTitle.html @@ -0,0 +1,70 @@ + + + + Description of setTitle + + + + + + + + + +
Home > plotting > setTitle.m
+ + + +

setTitle +

+ +

PURPOSE ^

+
plotLabels
+ +

SYNOPSIS ^

+
function setTitle(handle, pathway, title)
+ +

DESCRIPTION ^

+
 plotLabels
+   Prints a title on on a map drawn by drawPathway.
+
+   handle      handle to the figure on which to print the labels
+   pathway     pathway structure representing the pathway to be drawn
+   title       the title
+
+ Usage: setTitle(handle, pathway, title)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function setTitle(handle, pathway, title)
+0002 % plotLabels
+0003 %   Prints a title on on a map drawn by drawPathway.
+0004 %
+0005 %   handle      handle to the figure on which to print the labels
+0006 %   pathway     pathway structure representing the pathway to be drawn
+0007 %   title       the title
+0008 %
+0009 % Usage: setTitle(handle, pathway, title)
+0010 
+0011 dimension=getPathwayDimensions(pathway);
+0012 
+0013 handle=text(dimension(1)+0.5*dimension(3), -150,...
+0014     title,'fontname','Small Fonts','fontsize',5,...
+0015     'interpreter', 'tex','HorizontalAlignment','center','verticalalignment','middle');
+0016 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/right.png b/doc/right.png new file mode 100644 index 0000000000000000000000000000000000000000..067c5baf250318b85ede9047ea56e394244a8712 GIT binary patch literal 136 zcmeAS@N?(olHy`uVBq!ia0vp^{2ujP)z zZ3@F642I+A(ex_uOz|q|-Q16CA~DKXHy!h#6nPc#A=(dzh_Dj}01(mYWlSQ*cu32| zbbY!^c%J9=dA@}A9sq8umob~|g)?E>&V+Ie#O(HQu@+QR?< N002ovPDHLkV1hx>d=3Br literal 0 HcmV?d00001 diff --git a/doc/simulinkicon.gif b/doc/simulinkicon.gif new file mode 100644 index 0000000000000000000000000000000000000000..1386ddd4ce654071015610e81fdea82461d8e28b GIT binary patch literal 977 zcmbu8u}_m>5XK)83^3Uu8;SX77?CI^3B-XItA?P13elB7PXr>Q5E~tEP-6{~F%D-K z)WpFqI=OT~2IKIO5C(b~XFmOKi{R_TBlgr&b_q*r5UY@)(Ha=TG0e=CHm)y-= z-NhXdrR2#xsVDJ-NLq3;H+2&?M6D)Qb5&PyMYKwCF&A|a7f{KO9Oh7mI2cfy($r!z zs}XbJSxTCcq=XpD$Sj#AlVk`ACe@N^Qb~${Vy##bO(ID^Mz$tcf+k1;r;?gtgeE1i znB!n-Q<_?AMl2LDpPGpoVn2>$q-rXrh;>Q9q^OCQfZG#_wFWhaf$Px^VzQfdaDPH@ zLsCc`!iKu|Sa$Qm|sSpKyq|-EjTr8*2+?H0- z4`Q;Lc94k+b3;;7jL_^P7CAVW+LT6|D5{xe%m-eKMsh!nWh97?BYe&89m)KJVRL?! zsLhQI*K_ZpHMb*1{#n2u&8oRKvdcS(-_QHDh{>=FJST?;-$*#_> zFWg+IF0Bn^lXvHav-8W#Szfc2RV!b=VRFa{1fJ1Bvn_=*1$x~u5G{^07%?ML0m zHxB3bGCb|+8kyh!`1T@vWbw!Thc`P>6y|3Oo@O9$!+|lO2pBq=~ z?6HkkzgKp4CuH{I*7l2^yRRR1_MTc?@7vp&8a;gcZ2H%?cU{-M_dgh2`cl7D{M1<} G;M_lk-mF{z literal 0 HcmV?d00001 diff --git a/doc/solaris.png b/doc/solaris.png new file mode 100644 index 0000000000000000000000000000000000000000..e31e8a2a48078233e65bf10502de055609469206 GIT binary patch literal 286 zcmV+(0pb3MP)LJX0GRn|87F~=qO=0d z$LTWTx~|80zJzI-0N{4DjI%Mk;moMpnNcohj7EB(iPVo~iqGKm_8{s|W(+hpPU=N2 zz2$E5rj(XtF(bOm8L*eKNAeVg;o46LO1s$e-HK3o_b;p)l_XJ5>4v`(0TG#bkaL)bhCi169@`rB kx1WB<=i4tMjP|#52ZwT~UP>&M!~g&Q07*qoM6N<$g3~#GJpcdz literal 0 HcmV?d00001 diff --git a/doc/solver/checkSolution.html b/doc/solver/checkSolution.html new file mode 100644 index 000000000..157e5b3e9 --- /dev/null +++ b/doc/solver/checkSolution.html @@ -0,0 +1,83 @@ + + + + Description of checkSolution + + + + + + + + + +
Home > solver > checkSolution.m
+ + + +

checkSolution +

+ +

PURPOSE ^

+
Checks if a solution from Mosek is feasible and optimal
+ +

SYNOPSIS ^

+
function [isFeasible, isOptimal]=checkSolution(res)
+ +

DESCRIPTION ^

+
   Checks if a solution from Mosek is feasible and optimal
+
+   res             the output structure from mosekopt
+
+   isFeasible      true if the solution is feasible
+   isoptimal       true if the solution is optimal
+
+   This function also throws an error if the license has expired.
+
+ Usage: [isFeasible, isOptimal]=checkSolution(res)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function [isFeasible, isOptimal]=checkSolution(res)
+0002 %   Checks if a solution from Mosek is feasible and optimal
+0003 %
+0004 %   res             the output structure from mosekopt
+0005 %
+0006 %   isFeasible      true if the solution is feasible
+0007 %   isoptimal       true if the solution is optimal
+0008 %
+0009 %   This function also throws an error if the license has expired.
+0010 %
+0011 % Usage: [isFeasible, isOptimal]=checkSolution(res)
+0012 
+0013 isFeasible=false;
+0014 isOptimal=false;
+0015 
+0016 switch res.stat
+0017     case 1
+0018         isOptimal=true;
+0019         isFeasible=true;
+0020     case 2
+0021         isOptimal=false;
+0022         isFeasible=true;
+0023     otherwise
+0024         isOptimal=false;
+0025         isFeasible=false;
+0026 end
+0027 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/solver/index.html b/doc/solver/index.html new file mode 100644 index 000000000..e42468a9a --- /dev/null +++ b/doc/solver/index.html @@ -0,0 +1,29 @@ + + + + Index for Directory solver + + + + + + + + + + +
< Master indexIndex for solver >
+ +

Index for solver

+ +

Matlab files in this directory:

+ +
 checkSolutionChecks if a solution from Mosek is feasible and optimal
 optimizeProboptimizeProb
 qMOMAqMOMA
 setRavenSolversetRavenSolver
 solveLPsolveLP
 solveQPsolveQP
+ + + + +
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/solver/optimizeProb.html b/doc/solver/optimizeProb.html new file mode 100644 index 000000000..a6ec84623 --- /dev/null +++ b/doc/solver/optimizeProb.html @@ -0,0 +1,344 @@ + + + + Description of optimizeProb + + + + + + + + + +
Home > solver > optimizeProb.m
+ + + +

optimizeProb +

+ +

PURPOSE ^

+
optimizeProb
+ +

SYNOPSIS ^

+
function res = optimizeProb(prob,params,verbose)
+ +

DESCRIPTION ^

+
 optimizeProb
+   Optimize an LP or MILP formulated in cobra terms.
+
+   prob    cobra style LP/MILP problem struct to be optimised
+   params    solver specific parameters (optional)
+   verbose if true MILP progress is shown (optional, default true)
+
+   res        the output structure from the selected solver RAVENSOLVER
+           (cobra style)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 function res = optimizeProb(prob,params,verbose)
+0002 % optimizeProb
+0003 %   Optimize an LP or MILP formulated in cobra terms.
+0004 %
+0005 %   prob    cobra style LP/MILP problem struct to be optimised
+0006 %   params    solver specific parameters (optional)
+0007 %   verbose if true MILP progress is shown (optional, default true)
+0008 %
+0009 %   res        the output structure from the selected solver RAVENSOLVER
+0010 %           (cobra style)
+0011 
+0012 if nargin<2 || isempty(params)
+0013     params=struct();
+0014 end
+0015 if nargin<3 || isempty(verbose)
+0016     verbose = true;
+0017 end
+0018 
+0019 %Set as global variable for speed improvement if optimizeProb is run many times
+0020 global RAVENSOLVER;
+0021 if isempty(RAVENSOLVER)
+0022     if(~ispref('RAVEN','solver'))
+0023         dispEM('RAVEN solver not defined or unknown. Try using setRavenSolver(''solver'').');
+0024     else
+0025         RAVENSOLVER = getpref('RAVEN','solver');
+0026     end
+0027 end
+0028 solver=RAVENSOLVER;
+0029 if ~all(lower(prob.vartype) == 'c')
+0030     milp=true;
+0031     errorText = 'glpk is not suitable for solving MILPs, ';
+0032     switch solver
+0033         case 'glpk'
+0034             error([errorText 'select a different solver with setRavenSolver().'])
+0035         case 'cobra'
+0036             if strcmp(CBT_MILP_SOLVER,'glpk')
+0037                 error([errorText 'select a different solver with changeCobraSolver() or setRavenSolver().'])
+0038             end
+0039     end
+0040 else
+0041     milp=false;
+0042 end
+0043 
+0044 %% Define default parameters, which will then be used to make solver-
+0045 % specific solverparams structures
+0046 defaultparams.feasTol        = 1e-9;
+0047 defaultparams.optTol         = 1e-9;
+0048 defaultparams.objTol         = 1e-6;
+0049 defaultparams.timeLimit      = 1000;
+0050 %defaultparams.iterationLimit = 1000;
+0051 defaultparams.intTol         = 1e-12;
+0052 defaultparams.relMipGapTol   = 1e-12;
+0053 defaultparams.absMipGapTol   = 1e-12;
+0054 if milp
+0055     defaultparams.MIPGap     = 1e-12;
+0056     defaultparams.Seed       = 1;
+0057 end
+0058 res.obj=[];
+0059 switch solver
+0060     %% Use whatever solver is set by COBRA Toolbox changeCobraSolver
+0061     case 'cobra'
+0062         if milp
+0063             cparams=struct('timeLimit',1e9,'printLevel',0,'intTol',1e-6,'relMipGapTol',1e-9);
+0064             cparams=structUpdate(cparams,params);
+0065             res=solveCobraMILP(prob,cparams);
+0066         else
+0067             res=solveCobraLP(prob);
+0068         end
+0069         if isfield(res,{'dual','rcost'})
+0070             res.dual=res.dual;
+0071             res.rcost=res.rcost;
+0072         end
+0073 
+0074         %% Use Gurobi in a MATLAB environment
+0075     case 'gurobi'
+0076         if milp
+0077             if verbose
+0078                 solverparams.OutputFlag = 1;
+0079             else
+0080                 solverparams.OutputFlag = 0;
+0081             end
+0082             solverparams.IntFeasTol = 10^-9; %min val for gurobi
+0083             solverparams.MIPGap = defaultparams.MIPGap;
+0084             solverparams.Seed = defaultparams.Seed;
+0085         else
+0086             solverparams.OutputFlag = 0;
+0087         end
+0088         solverparams.DisplayInterval= 1; % Level of verbosity
+0089         solverparams.TimeLimit      = defaultparams.timeLimit;
+0090         solverparams.FeasibilityTol = defaultparams.feasTol;
+0091         solverparams.OptimalityTol  = defaultparams.optTol;
+0092         solverparams.Presolve       = 2;
+0093         % If run in parallel, then one thread per gurobi. getCurrentTask
+0094         % requires the Parallel Computing Toolbox.
+0095         try
+0096             inParallel = ~isempty(getCurrentTask);
+0097         catch
+0098             inParallel = false;
+0099         end
+0100         if inParallel
+0101             solverparams.Threads=1;
+0102         end
+0103         solverparams = structUpdate(solverparams,params);
+0104 
+0105         % Restructering problem according to gurobi format
+0106         if isfield(prob, 'csense')
+0107             prob.sense = renameparams(prob.csense, {'L','G','E'}, {'<','>','='});
+0108             prob = rmfield(prob, {'csense'});
+0109         end
+0110         if isfield(prob, 'osense')
+0111             osense = prob.osense;
+0112             prob.modelsense = renameparams(num2str(prob.osense), {'1','-1'}, {'min','max'});
+0113             prob = rmfield(prob, {'osense'});
+0114         end
+0115         [prob.obj, prob.rhs, prob.vtype] = deal(prob.c, prob.b, prob.vartype);
+0116         prob = rmfield(prob, {'c','b','vartype'});
+0117 
+0118         resG = gurobi(prob,solverparams);
+0119 
+0120         try
+0121             % Name output fields the same as COBRA does
+0122             res.full     = resG.x;
+0123             res.obj      = resG.objval;
+0124             res.origStat = resG.status;
+0125             if isfield(resG,{'pi','rc'})
+0126                 res.dual     = -resG.pi*osense;
+0127                 res.rcost    = -resG.rc*osense;
+0128             end
+0129             if milp && strcmp(resG.status, 'TIME_LIMIT')
+0130                 % If res has the objval field, it succeeded, regardless of
+0131                 % time_limit status
+0132                 resG.status = 'OPTIMAL';
+0133             end
+0134             switch resG.status
+0135                 case 'OPTIMAL'
+0136                     res.stat = 1;
+0137                 case 'UNBOUNDED'
+0138                     res.stat = 2;
+0139                 otherwise
+0140                     res.stat = 0;
+0141             end
+0142             if ~milp
+0143                 res.vbasis = resG.vbasis;
+0144                 res.cbasis = resG.cbasis;
+0145             else
+0146                 res.mipgap = resG.mipgap;
+0147             end
+0148         catch
+0149             res.stat = 0;
+0150             res.origStat = resG.status;  % useful information to have
+0151         end
+0152         %% Use GLPK using RAVEN-provided binary
+0153     case 'glpk'
+0154         solverparams.scale   = 1; % Auto scaling
+0155         %solverparams.tmlim   = defaultparams.timeLimit;
+0156         solverparams.tolbnd  = defaultparams.feasTol;
+0157         solverparams.toldj   = defaultparams.optTol;
+0158         solverparams.tolint  = defaultparams.intTol;
+0159         solverparams.tolobj  = defaultparams.objTol;
+0160         solverparams.msglev  = 0; % Level of verbosity
+0161         solverparams = structUpdate(solverparams,params);
+0162 
+0163         prob.csense = renameparams(prob.csense, {'L','G','E'}, {'U','L','S'});
+0164 
+0165         if milp
+0166             solverparams.tmlim   = solverparams.tmlim*10;
+0167             solverparams.msglev  = 1; % Level of verbosity
+0168             disp('Issues have been observed when using GLPK for MILP solving. Be advised to carefully observe the results, or us another solver.')
+0169         end
+0170 
+0171         % Ensure that RAVEN glpk binary is used, return to original
+0172         % directory afterwards
+0173         [ravenDir,currDir]=findRAVENroot();
+0174         cd(fullfile(ravenDir,'software','GLPKmex'))
+0175         [xopt, fmin, errnum, extra] = glpk(prob.c, prob.A, prob.b, prob.lb, prob.ub, prob.csense, prob.vartype, prob.osense, solverparams);
+0176         cd(currDir)
+0177 
+0178         switch errnum % 1 = undefined; 2 = feasible; 3 = infeasible; 4 = no feasible solution; 5 = optimal; 6 = no unbounded solution
+0179             case 5
+0180                 res.stat = 1; % Optimal
+0181             case 2
+0182                 res.stat = 2; % Feasible, but not optimal
+0183             otherwise
+0184                 res.stat = 0;
+0185         end
+0186         res.origStat = errnum;
+0187         res.full     = xopt;
+0188         res.obj      = fmin;
+0189         res.dual     = -extra.lambda*prob.osense;
+0190         res.rcost    = -extra.redcosts*prob.osense;
+0191         %% Use scip
+0192     case {'soplex','scip'} % Old 'soplex' option also allowed
+0193         [xopt,fval,exitflag] = scip([], prob.c, prob.A,-prob.b, prob.b, prob.lb, prob.ub, prob.vartype);
+0194 
+0195         %   [x,fval,exitflag,stats] = scip(H, f, A, rl, ru, lb, ub, xtype, sos, qc, nl, x0, opts)
+0196         %
+0197         %   Input arguments*:
+0198         %       H - quadratic objective matrix (sparse, optional [NOT TRIL / TRIU])
+0199         %       f - linear objective vector
+0200         %       A - linear constraint matrix (sparse)
+0201         %       rl - linear constraint lhs
+0202         %       ru - linear constraint rhs
+0203         %       lb - decision variable lower bounds
+0204         %       ub - decision variable upper bounds
+0205         %       xtype - string of variable integrality ('c' continuous, 'i' integer, 'b' binary)
+0206         %       sos - SOS structure with fields type, index and weight (see below)
+0207         %       qc - Quadratic Constraints structure with fields Q, l, qrl and qru (see below)
+0208         %       nl - Nonlinear Objective and Constraints structure (see below)
+0209         %       x0 - primal solution
+0210         %       opts - solver options (see below)
+0211         %
+0212         %   Return arguments:
+0213         %       x - solution vector
+0214         %       fval - objective value at the solution
+0215         %       exitflag - exit status (see below)
+0216         %       stats - statistics structure
+0217         %
+0218         %   Option Fields (all optional, see also optiset for a list):
+0219         %       solverOpts - specific SCIP options (list of pairs of parameter names and values)
+0220         %       maxiter - maximum LP solver iterations
+0221         %       maxnodes - maximum nodes to explore
+0222         %       maxtime - maximum execution time [s]
+0223         %       tolrfun - primal feasibility tolerance
+0224         %       display - solver display level [0-5]
+0225         %       probfile - write problem to given file
+0226         %       presolvedfile - write presolved problem to file
+0227         %
+0228         %   Return Status:
+0229         %       0 - Unknown
+0230         %       1 - User Interrupted
+0231         %       2 - Node Limit Reached
+0232         %       3 - Total Node Limit Reached
+0233         %       4 - Stall Node Limit Reached
+0234         %       5 - Time Limit Reached
+0235         %       6 - Memory Limit Reached
+0236         %       7 - Gap Limit Reached
+0237         %       8 - Solution Limit Reached
+0238         %       9 - Solution Improvement Limit Reached
+0239         %      10 - Restart Limit Reached
+0240         %      11 - Problem Solved to Optimality
+0241         %      12 - Problem is Infeasible
+0242         %      13 - Problem is Unbounded
+0243         %      14 - Problem is Either Infeasible or Unbounded
+0244         
+0245         res.origStat = exitflag;
+0246         res.full = xopt;
+0247         res.obj  = fval;
+0248 
+0249         switch exitflag
+0250             case 11
+0251                 res.stat = 1;
+0252             case {1, 5, 6, 7, 8, 9, 10, 13} % If user-interrupted, not sure if optimal
+0253                 res.stat = 2;
+0254             otherwise
+0255                 res.stat = 0;
+0256         end
+0257     otherwise
+0258         error('RAVEN solver not defined or unknown. Try using setRavenSolver(''solver'').');
+0259 end
+0260 if res.stat>0
+0261     res.full=res.full(1:size(prob.a,2));
+0262 end
+0263 end
+0264 
+0265 function s_merged=structUpdate(s_old,s_new)
+0266 %Remove overlapping fields from first struct;
+0267 %Obtain all unique names of remaining fields;
+0268 %Merge both structs
+0269 s_merged = rmfield(s_old, intersect(fieldnames(s_old), fieldnames(s_new)));
+0270 names = [fieldnames(s_merged); fieldnames(s_new)];
+0271 s_merged = cell2struct([struct2cell(s_merged); struct2cell(s_new)], names, 1);
+0272 end
+0273 
+0274 function paramlist = renameparams(paramlist,old,new)
+0275 if ~iscell(paramlist)
+0276     wasNoCell = true;
+0277     paramlist={paramlist};
+0278 else
+0279     wasNoCell = false;
+0280 end
+0281 for i=1:numel(old)
+0282     paramlist = regexprep(paramlist,old{i},new{i});
+0283 end
+0284 if wasNoCell
+0285     paramlist=paramlist{1};
+0286 end
+0287 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/solver/qMOMA.html b/doc/solver/qMOMA.html new file mode 100644 index 000000000..8308a3365 --- /dev/null +++ b/doc/solver/qMOMA.html @@ -0,0 +1,150 @@ + + + + Description of qMOMA + + + + + + + + + +
Home > solver > qMOMA.m
+ + + +

qMOMA +

+ +

PURPOSE ^

+
qMOMA
+ +

SYNOPSIS ^

+
function [fluxA,fluxB, flag]=qMOMA(modelA,modelB,fluxMinWeight)
+ +

DESCRIPTION ^

+
 qMOMA
+   Uses quadratic programming to minimize the sum((fluxAi - fluxBi)^2)
+
+   modelA        a model structure for the test case. This model must be a
+                 subset of modelB (no reactions that are not in modelB)
+   modelB        a model structure for the reference case
+   fluxMinWeight a double >=1 that determines whether minimization of the
+                 sum of fluxes should also be taken into account in the
+                 optimization. A value of 2.0 means that sum(fluxAi)^2 +
+                 sum(fluxBi)^2 has equal weight as sum((fluxAi - fluxBi)^2).
+                 Values of around 1.01 should be enough to get rid of loops
+                 (optional, default 1)
+
+   fluxA         the resulting flux distribution in the test model
+   fluxB         the resulting flux distribution in the reference model
+   flag          1 if the optimization terminated successfully
+
+ Usage: [fluxA,fluxB, flag]=qMOMA(modelA,modelB,fluxMinWeight)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function [fluxA,fluxB, flag]=qMOMA(modelA,modelB,fluxMinWeight)
+0002 % qMOMA
+0003 %   Uses quadratic programming to minimize the sum((fluxAi - fluxBi)^2)
+0004 %
+0005 %   modelA        a model structure for the test case. This model must be a
+0006 %                 subset of modelB (no reactions that are not in modelB)
+0007 %   modelB        a model structure for the reference case
+0008 %   fluxMinWeight a double >=1 that determines whether minimization of the
+0009 %                 sum of fluxes should also be taken into account in the
+0010 %                 optimization. A value of 2.0 means that sum(fluxAi)^2 +
+0011 %                 sum(fluxBi)^2 has equal weight as sum((fluxAi - fluxBi)^2).
+0012 %                 Values of around 1.01 should be enough to get rid of loops
+0013 %                 (optional, default 1)
+0014 %
+0015 %   fluxA         the resulting flux distribution in the test model
+0016 %   fluxB         the resulting flux distribution in the reference model
+0017 %   flag          1 if the optimization terminated successfully
+0018 %
+0019 % Usage: [fluxA,fluxB, flag]=qMOMA(modelA,modelB,fluxMinWeight)
+0020 
+0021 if nargin<3
+0022     fluxMinWeight=1;
+0023 end
+0024 
+0025 %Match the reactions and metabolites in the small model (modelA) to the
+0026 %larger model
+0027 [rxnExists,mapRxns]=ismember(modelA.rxns,modelB.rxns);
+0028 
+0029 %Check that the smaller model is a subset of the larger one
+0030 if any(~rxnExists)
+0031     dispEM('All reactions in the test model must exist in the reference model');
+0032 end
+0033 
+0034 %In order to make the calculations a little easier to formulate I reshape
+0035 %modelA.S so that it is the same dimension as modelB.S
+0036 S=modelA.S;
+0037 lb=modelA.lb;
+0038 ub=modelA.ub;
+0039 c=modelA.c;
+0040 modelA.S=sparse(numel(modelA.mets),numel(modelB.rxns));
+0041 modelA.lb=zeros(numel(modelB.rxns),1);
+0042 modelA.ub=modelA.lb;
+0043 modelA.c=modelA.lb;
+0044 modelA.S(:,mapRxns)=S;
+0045 modelA.lb(mapRxns)=lb;
+0046 modelA.ub(mapRxns)=ub;
+0047 modelA.c(mapRxns)=c;
+0048 
+0049 %Create the H matrix for the quadratic problem. Note that there are no
+0050 %linear terms in the equation
+0051 
+0052 %Equation to solve is:(xA1 - xB1)^2 + (xA2 - xB2)^2 ....
+0053 %Is equal to xA1^2 - xA1*xB1 - xB1*xA1 + xB1^2 + xA2^2 - xA2*xB2 - xB2*xA2 + xB2^2...
+0054 
+0055 %For three fluxes this would give the following H matrix (first three rows
+0056 %for A and last three rows for B)
+0057 
+0058 %   A1 A2 A3 B1 B2 B3
+0059 %A1 1  0  0  -1  0  0
+0060 %A2 0  1  0  0  -1  0
+0061 %A3 0  0  1  0  0  -1
+0062 %B1 -1  0  0  1  0  0
+0063 %B2 0  -1  0  0  1  0
+0064 %B3 0  0  -1  0  0  1
+0065 
+0066 %Create stoichiometric matrix and bounds that contain both models
+0067 fullS=[modelA.S sparse(size(modelA.S,1),size(modelA.S,2));sparse(size(modelB.S,1),size(modelB.S,2)) modelB.S];
+0068 fullLB=[modelA.lb;modelB.lb];
+0069 fullUB=[modelA.ub;modelB.ub];
+0070 fullB=zeros(size(modelA.S,1)+size(modelB.S,1),1);
+0071 
+0072 H=[eye(size(fullS,2)/2)*fluxMinWeight eye(size(fullS,2)/2)*-1;eye(size(fullS,2)/2)*-1 eye(size(fullS,2)/2)*fluxMinWeight];
+0073 
+0074 x=quadprog(H,zeros(size(H,1),1),[],[],fullS,fullB,fullLB,fullUB);
+0075 
+0076 if any(x)
+0077     fluxA=x(1:numel(modelB.rxns));
+0078     fluxA=fluxA(mapRxns);
+0079     fluxB=x(numel(modelB.rxns)+1:end);
+0080     flag=1; %Since it never converges good enough
+0081 else
+0082     fluxA=zeros(numel(modelA.rxns),1); %Still the old number
+0083     fluxB=zeros(numel(modelB.rxns),1);
+0084     flag=-1;
+0085 end
+0086 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/solver/setRavenSolver.html b/doc/solver/setRavenSolver.html new file mode 100644 index 000000000..b81747549 --- /dev/null +++ b/doc/solver/setRavenSolver.html @@ -0,0 +1,119 @@ + + + + Description of setRavenSolver + + + + + + + + + +
Home > solver > setRavenSolver.m
+ + + +

setRavenSolver +

+ +

PURPOSE ^

+
setRavenSolver
+ +

SYNOPSIS ^

+
function setRavenSolver(solver)
+ +

DESCRIPTION ^

+
 setRavenSolver
+   Sets the solver for RAVEN and optionally saves a default value
+    to MATLAB startup.
+
+   solver  string with solver name. The following options are available:
+           glpk    uses RAVEN-provided binaries
+           gurobi  requires a working Gurobi installation
+           cobra   requires a working COBRA Toolbox installation. RAVEN
+                   parses the problem to COBRA and uses the solver that is
+                   set by changeCobraSolver.
+
+ Usage: setRavenSolver(solver)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function setRavenSolver(solver)
+0002 % setRavenSolver
+0003 %   Sets the solver for RAVEN and optionally saves a default value
+0004 %    to MATLAB startup.
+0005 %
+0006 %   solver  string with solver name. The following options are available:
+0007 %           glpk    uses RAVEN-provided binaries
+0008 %           gurobi  requires a working Gurobi installation
+0009 %           cobra   requires a working COBRA Toolbox installation. RAVEN
+0010 %                   parses the problem to COBRA and uses the solver that is
+0011 %                   set by changeCobraSolver.
+0012 %
+0013 % Usage: setRavenSolver(solver)
+0014 solver=char(solver);
+0015 switch solver
+0016     case 'cobra'
+0017         global CBT_LP_SOLVER;
+0018         if isempty(CBT_LP_SOLVER)
+0019             error('COBRA toolbox is not initialized, run ''initCobraToolbox()''')
+0020         else
+0021             setpref('RAVEN','solver','cobra');
+0022         end
+0023     case 'mosek'
+0024         error('MOSEK support has been discontinued since RAVEN 2.3.0.')
+0025     case {'glpk','gurobi'}
+0026         setpref('RAVEN','solver',solver)
+0027     case 'soplex'
+0028         error('The ''soplex'' solver is replaced by ''scip''.')
+0029     case 'scip'
+0030         if ~ispc
+0031             try
+0032                 scip; % The user might have installed SCIP manually
+0033                 setpref('RAVEN','solver','scip')
+0034             catch
+0035                 error('SCIP not found. RAVEN only provides the precompiled SCIP MEX binary for Windows. Instructions on how to compile the SCIP MEX file are found at https://github.com/scipopt/MatlabSCIPInterface')
+0036             end
+0037         else
+0038             ravenDir = findRAVENroot();
+0039             if ~exist(fullfile(ravenDir,'software','scip','scip.mexw64'),'file')
+0040                 try
+0041                     disp('Downloading and installing RAVEN-provided SCIP MEX binary...')
+0042                     websave(fullfile(ravenDir,'software','scip_mex_win.zip'),'https://github.com/SysBioChalmers/RAVEN/releases/download/v2.8.6/scip_mex_win.zip'); % Should be updated to release with SCIP functionality
+0043                 catch
+0044                     error('Unable to download SCIP MEX binary from the RAVEN GitHub page.')
+0045                 end
+0046                 unzip(fullfile(ravenDir,'software','scip_mex_win.zip'),fullfile(ravenDir,'software','scip'));
+0047                 delete(fullfile(ravenDir,'software','scip_mex_win.zip'));
+0048             end
+0049             try
+0050                 scip; % The pre-compiled MEX file might fail
+0051                 setpref('RAVEN','solver','scip')
+0052             catch
+0053                 error('Unable to use the RAVEN-provided precompiled SCIP MEX binary. Instructions on how to compile the SCIP MEX file are found at https://github.com/scipopt/MatlabSCIPInterface')
+0054             end
+0055         end
+0056     otherwise
+0057         error('Invalid solver defined')
+0058 end
+0059 global RAVENSOLVER
+0060 RAVENSOLVER = solver;
+0061 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/solver/solveLP.html b/doc/solver/solveLP.html new file mode 100644 index 000000000..9cec93be7 --- /dev/null +++ b/doc/solver/solveLP.html @@ -0,0 +1,310 @@ + + + + Description of solveLP + + + + + + + + + +
Home > solver > solveLP.m
+ + + +

solveLP +

+ +

PURPOSE ^

+
solveLP
+ +

SYNOPSIS ^

+
function [solution, hsSolOut]=solveLP(model,minFlux,params,hsSol)
+ +

DESCRIPTION ^

+
 solveLP
+   Solves a linear programming problem
+
+ Input:
+   model         a model structure
+   minFlux       determines if a second optimization should be performed
+                 in order to get rid of loops in the flux distribution
+                 0:    no such optimization is performed
+                 1:    the sum of abs(fluxes) is minimized. This is the
+                       fastest way of getting rid of loops
+                 2:    *option is deprecated*
+                 3:    the number of fluxes is minimized. This can result
+                       in the flux distributions that are the easiest to
+                       interpret. Note that this optimization can be very
+                       slow
+                 (optional, default 0)
+   params        *obsolete option*
+   hsSol         hot-start solution for the LP solver. This can
+                 significantly speed up the process if many similar
+                 optimization problems are solved iteratively. Only used
+                 if minFlux is 0 or 1 (optional)
+
+ Output:
+   solution
+         f       objective value
+         x       primal (flux distribution)
+         stat    exit flag
+                 1: the optimization terminated successfully
+                 0: the solution is feasible, but not necessarily optimal
+                -1: no feasible solution found
+                -2: solution found, but flux minimization failed
+         msg     string describing the status of the optimization
+         sPrice  shadow price (only reported if minFlux was 0)
+         rCost   reduced cost (only reported if minFlux was 0)
+   hsSolOut      solution to be used as hot-start solution (see the input
+                 parameters). Only used if minFlux is 0 or 1
+
+ Usage: [solution, hsSolOut] = solveLP(model, minFlux, params, hsSol)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: + + + + + +

SOURCE CODE ^

+
0001 function [solution, hsSolOut]=solveLP(model,minFlux,params,hsSol)
+0002 % solveLP
+0003 %   Solves a linear programming problem
+0004 %
+0005 % Input:
+0006 %   model         a model structure
+0007 %   minFlux       determines if a second optimization should be performed
+0008 %                 in order to get rid of loops in the flux distribution
+0009 %                 0:    no such optimization is performed
+0010 %                 1:    the sum of abs(fluxes) is minimized. This is the
+0011 %                       fastest way of getting rid of loops
+0012 %                 2:    *option is deprecated*
+0013 %                 3:    the number of fluxes is minimized. This can result
+0014 %                       in the flux distributions that are the easiest to
+0015 %                       interpret. Note that this optimization can be very
+0016 %                       slow
+0017 %                 (optional, default 0)
+0018 %   params        *obsolete option*
+0019 %   hsSol         hot-start solution for the LP solver. This can
+0020 %                 significantly speed up the process if many similar
+0021 %                 optimization problems are solved iteratively. Only used
+0022 %                 if minFlux is 0 or 1 (optional)
+0023 %
+0024 % Output:
+0025 %   solution
+0026 %         f       objective value
+0027 %         x       primal (flux distribution)
+0028 %         stat    exit flag
+0029 %                 1: the optimization terminated successfully
+0030 %                 0: the solution is feasible, but not necessarily optimal
+0031 %                -1: no feasible solution found
+0032 %                -2: solution found, but flux minimization failed
+0033 %         msg     string describing the status of the optimization
+0034 %         sPrice  shadow price (only reported if minFlux was 0)
+0035 %         rCost   reduced cost (only reported if minFlux was 0)
+0036 %   hsSolOut      solution to be used as hot-start solution (see the input
+0037 %                 parameters). Only used if minFlux is 0 or 1
+0038 %
+0039 % Usage: [solution, hsSolOut] = solveLP(model, minFlux, params, hsSol)
+0040 
+0041 if nargin<2
+0042     minFlux=0;
+0043 end
+0044 if nargin<3
+0045     params.relGap=0.4;
+0046 end
+0047 if nargin<4
+0048     hsSol=[];
+0049 end
+0050 
+0051 %Default return values
+0052 hsSolOut=[];
+0053 solution.x=[];
+0054 solution.f=[];
+0055 solution.stat=-1;
+0056 
+0057 %Check for valid lb and ub
+0058 if ~isnumeric([model.lb,model.ub])
+0059     invalidBound = true(numel(model.lb),1);
+0060 else
+0061     invalidBound = false(numel(model.lb),1);
+0062 end
+0063 invalidBound = invalidBound | model.lb>model.ub;
+0064 invalidBound = invalidBound | logical(sum(isnan([model.lb,model.ub]),2));
+0065 if any(invalidBound)
+0066     error(['Invalid set of bounds for reaction(s): ', strjoin(model.rxns(invalidBound),', '), '.'])
+0067 end
+0068 %Check for valid objective
+0069 if ~isnumeric(model.c) || any(isnan(model.c))
+0070     error('Invalid defintion of objective function in model.c.')
+0071 end
+0072 %Check for valid S-matrix
+0073 if ~allfinite(model.S)
+0074     invalidS = ~isfinite(model.S);
+0075     error(['Invalid coefficients defined for reaction(s): ', strjoin(model.rxns(any(invalidS)),', '), '.'])
+0076 end
+0077 
+0078 %Ignore the hot-start if the previous solution wasn't feasible
+0079 if isfield(hsSol,'stat')
+0080     if hsSol.stat<1
+0081         hsSol=[];
+0082     end
+0083 end
+0084 
+0085 % Setup the linear problem for glpk
+0086 prob        = [];
+0087 prob.c      = [model.c*-1;zeros(size(model.S,1),1)];
+0088 prob.b      = zeros(size(model.S,1), 1);
+0089 prob.lb     = [model.lb; model.b(:,1)];
+0090 prob.ub     = [model.ub; model.b(:,min(size(model.b,2),2))];
+0091 prob.csense = repmat('E', 1, length(prob.b)); % Equality constraints
+0092 prob.osense = 1; 
+0093 prob.vartype = repmat('C', 1, length(prob.c)); % Fluxes are continuous values
+0094 prob.A = [model.S -speye(size(model.S,1))];
+0095 prob.a = model.S;
+0096 
+0097 %If hot-start should be used
+0098 if ~isempty(hsSol)
+0099     prob.vbasis=hsSol.vbasis;
+0100     prob.cbasis=hsSol.cbasis;
+0101 end
+0102 
+0103 % Parse the problem to the LP solver
+0104 res = optimizeProb(prob,params);
+0105 % Swap the sign of the obj-value
+0106 res.obj = -res.obj;
+0107 
+0108 %Check if the problem was feasible and that the solution was optimal
+0109 [isFeasible, isOptimal]=checkSolution(res);
+0110 
+0111 %If the problem was infeasible using hot-start it is often possible to
+0112 %re-solve it without hot-start and get a feasible solution
+0113 if ~isFeasible && ~isempty(hsSol)
+0114     prob=rmfield(prob,{'vbasis','cbasis'});
+0115     res=optimizeProb(prob,params);
+0116     [isFeasible, isOptimal]=checkSolution(res);
+0117 end
+0118 
+0119 %Return without solution if the problem was infeasible
+0120 if ~isFeasible
+0121     solution.msg='The problem is infeasible';
+0122     return;
+0123 end
+0124 if ~isOptimal
+0125     solution.msg='The problem is feasible, but not necessarily optimal';
+0126     solution.stat=0;
+0127 else
+0128     %All is well
+0129     solution.stat=1;
+0130     solution.msg='Optimal solution found';
+0131 end
+0132 
+0133 %Construct the output structure
+0134 if isfield(res,'full')
+0135     solution.x=res.full;
+0136     if minFlux<=1
+0137         if(isfield(res,'vbasis')) % gurobi uses vbasis and cbasis as hotstart
+0138             hsSolOut.vbasis=res.vbasis;
+0139             hsSolOut.cbasis=res.cbasis;
+0140         end
+0141     end
+0142     solution.f=res.obj;
+0143 if isfield(res,'dual')
+0144     solution.sPrice=res.dual;
+0145 else
+0146     solution.sPrice=[];
+0147 end
+0148 if isfield(res,'rcost')
+0149     solution.rCost=res.rcost(1:numel(model.rxns));
+0150 else
+0151     solution.rCost=[];
+0152 end
+0153 
+0154 %If either the square, the number, or the sum of fluxes should be minimized
+0155 %then the objective function value should be fixed before another
+0156 %optimization. It is not correct to fix the reactions which participate in
+0157 %the objective function to their values in solution.x, as there can be
+0158 %multiple solutions with the same objective function value. In addition,
+0159 %this approach could result in numerical issues when several fluxes are
+0160 %fixed. Instead a new "fake metabolite" is added to the problem. This
+0161 %metabolite is produced by each reaction with the stoichiometry that
+0162 %reaction has in the objective function. The equality constraint of that
+0163 %"fake metabolite" is then set to be at least as good as the objective
+0164 %function value.
+0165 if minFlux~=0
+0166     model.S=[model.S;model.c'];
+0167     model.mets=[model.mets;'TEMP'];
+0168     
+0169     %If the constraint on the objective function value is exact there is a
+0170     %larger risk of numerical errors. However for the quadratic fitting
+0171     %intervals are not allowed
+0172     if minFlux~=2
+0173         if size(model.b,2)==1
+0174             model.b=[model.b model.b];
+0175         end
+0176         if solution.f>0
+0177             model.b=[model.b;[solution.f*0.999999 inf]];
+0178         else
+0179             model.b=[model.b;[solution.f*1.000001 inf]];
+0180         end
+0181     else
+0182         model.b=[model.b;ones(1,size(model.b,2))*solution.f];
+0183     end
+0184     
+0185     switch minFlux
+0186         %The sum of fluxes should be minimized
+0187         case 1
+0188             %Convert the model to the irreversible format
+0189             revRxns=find(model.rev);
+0190             if ~isempty(revRxns)
+0191                 iModel=convertToIrrev(model);
+0192             else
+0193                 iModel=model;
+0194             end
+0195             %Minimize all fluxes
+0196             iModel.c(:)=-1;
+0197             sol=solveLP(iModel,0,params);
+0198             
+0199             %Map back to reversible fluxes
+0200             if sol.stat>=0
+0201                 solution.x=sol.x(1:numel(model.c));
+0202                 solution.x(revRxns)=solution.x(revRxns)-sol.x(numel(model.c)+1:end);
+0203             else
+0204                 EM='Could not solve the problem of minimizing the sum of fluxes. Uses output from original problem';
+0205                 dispEM(EM,false);
+0206                 solution.stat=-2;
+0207             end
+0208             
+0209         case 2
+0210             error('%Minimization of square of fluxes is deprecated')
+0211             
+0212             %The number of fluxes should be minimized
+0213         case 3
+0214             [qx,I]=getMinNrFluxes(model,model.rxns,params);
+0215             qx(~I)=0;
+0216             if any(I)
+0217                 solution.x=qx;
+0218             else
+0219                 EM='Could not solve the problem of minimizing the number of fluxes. Uses output from linear program';
+0220                 dispEM(EM,false);
+0221                 solution.stat=-2;
+0222             end
+0223     end
+0224     solution=rmfield(solution,{'sPrice','rCost'});
+0225 end
+0226 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/solver/solveQP.html b/doc/solver/solveQP.html new file mode 100644 index 000000000..53efd240b --- /dev/null +++ b/doc/solver/solveQP.html @@ -0,0 +1,127 @@ + + + + Description of solveQP + + + + + + + + + +
Home > solver > solveQP.m
+ + + +

solveQP +

+ +

PURPOSE ^

+
solveQP
+ +

SYNOPSIS ^

+
function solution=solveQP(model,rxns,values,maxIter, restartIter)
+ +

DESCRIPTION ^

+
 solveQP
+   Solves a quadratic fitting problem.
+
+   model         a model structure
+   rxns          either a cell array of reaction IDs, a logical vector 
+                 with the same number of elements as reactions in the model,
+                 of a vector of indexes to fit to
+   values        the values to fit the fluxes to
+   maxIter       maximal number of iterations (optional, default 1000)
+   restartIter   run the fitting up to this many times in case it does
+                 not converge (optional, default 1)
+
+   solution
+         f       Objective value
+         x       Primal
+         stat    Exit flag
+
+ Usage: solution=solveQP(model,rxns,values,maxIter, restartIter)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function solution=solveQP(model,rxns,values,maxIter, restartIter)
+0002 % solveQP
+0003 %   Solves a quadratic fitting problem.
+0004 %
+0005 %   model         a model structure
+0006 %   rxns          either a cell array of reaction IDs, a logical vector
+0007 %                 with the same number of elements as reactions in the model,
+0008 %                 of a vector of indexes to fit to
+0009 %   values        the values to fit the fluxes to
+0010 %   maxIter       maximal number of iterations (optional, default 1000)
+0011 %   restartIter   run the fitting up to this many times in case it does
+0012 %                 not converge (optional, default 1)
+0013 %
+0014 %   solution
+0015 %         f       Objective value
+0016 %         x       Primal
+0017 %         stat    Exit flag
+0018 %
+0019 % Usage: solution=solveQP(model,rxns,values,maxIter, restartIter)
+0020 rxns=char(rxns);
+0021 
+0022 if nargin<4
+0023     maxIter=1000;
+0024 end
+0025 
+0026 if nargin<5
+0027     restartIter=1;
+0028 end
+0029 
+0030 %Check that it's feasible
+0031 solution=solveLP(model);
+0032 if isempty(solution.x)
+0033     return;
+0034 end
+0035 
+0036 %Get the indexes of the fluxes to fit
+0037 allIndexes=getIndexes(model,rxns,'rxns');
+0038 
+0039 f=zeros(numel(model.rxns),1);
+0040 H=zeros(numel(model.rxns));
+0041 
+0042 %Get the fitIndexes for the experiment
+0043 for j=1:numel(allIndexes) %Not that neat
+0044     H(allIndexes(j),allIndexes(j))=2;
+0045 end
+0046 
+0047 f(allIndexes)=values.*-2;
+0048 
+0049 %For a badly formulated problem it can occur that the solver stalls. This
+0050 %can sometimes be fixed by trying to solve the problem again
+0051 options=optimset('MaxIter',maxIter);
+0052 for j=1:restartIter
+0053     [x,fval,flag] = ...
+0054         quadprog(H,f,[],[],model.S,model.b,model.lb,model.ub,[],options);
+0055     if flag>0
+0056         break;
+0057     end
+0058 end
+0059 
+0060 solution.f=fval;
+0061 solution.x=x;
+0062 solution.stat=flag;
+0063 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/struct_conversion/addIdentifierPrefix.html b/doc/struct_conversion/addIdentifierPrefix.html new file mode 100644 index 000000000..de10d34d8 --- /dev/null +++ b/doc/struct_conversion/addIdentifierPrefix.html @@ -0,0 +1,128 @@ + + + + Description of addIdentifierPrefix + + + + + + + + + +
Home > struct_conversion > addIdentifierPrefix.m
+ + + +

addIdentifierPrefix +

+ +

PURPOSE ^

+
addIdentifierPrefix
+ +

SYNOPSIS ^

+
function [model, hasChanged]=addIdentifierPrefix(model,fields)
+ +

DESCRIPTION ^

+
 addIdentifierPrefix
+   If reaction, metabolite, compartment, gene or model identifiers do not
+   start with a letter or _, which conflicts with SBML specifications,
+   prefixes are added for all identifiers in the respective model field.
+   The prefixes are:
+       "R_" for model.rxns,
+       "M_" for model.mets,
+       "C_" for model.comps;
+       "G_" for model.genes (and also represented in model.grRules)
+
+ Input:
+   model           model whose identifiers should be modified
+   fields          cell array with model field names that should be
+                   checked if prefixes should be added, possible values: 
+                   'rxns', 'mets', 'comps', 'genes', 'id'. (optional, by
+                   default all listed model fields will be checked).
+
+ Output:
+   model           modified model
+   hasChanged      cell array with fields and prefixes that are added
+
+ Usage: [model, hasChanged]=addIdentifierPrefix(model,fields)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function [model, hasChanged]=addIdentifierPrefix(model,fields)
+0002 % addIdentifierPrefix
+0003 %   If reaction, metabolite, compartment, gene or model identifiers do not
+0004 %   start with a letter or _, which conflicts with SBML specifications,
+0005 %   prefixes are added for all identifiers in the respective model field.
+0006 %   The prefixes are:
+0007 %       "R_" for model.rxns,
+0008 %       "M_" for model.mets,
+0009 %       "C_" for model.comps;
+0010 %       "G_" for model.genes (and also represented in model.grRules)
+0011 %
+0012 % Input:
+0013 %   model           model whose identifiers should be modified
+0014 %   fields          cell array with model field names that should be
+0015 %                   checked if prefixes should be added, possible values:
+0016 %                   'rxns', 'mets', 'comps', 'genes', 'id'. (optional, by
+0017 %                   default all listed model fields will be checked).
+0018 %
+0019 % Output:
+0020 %   model           modified model
+0021 %   hasChanged      cell array with fields and prefixes that are added
+0022 %
+0023 % Usage: [model, hasChanged]=addIdentifierPrefix(model,fields)
+0024 
+0025 if nargin<2 || isempty(fields)
+0026     fields = {'rxns','mets','comps','genes','id'};
+0027 end
+0028 
+0029 modelFields = {'rxns','R_';
+0030                'mets','M_';
+0031                'comps','C_';
+0032                'genes','G_';
+0033                'id','M_'};
+0034 
+0035 toChangeIdx = find(ismember(modelFields(:,1),fields));
+0036 hasChanged  = false(numel(modelFields(:,1)),1);
+0037 for i=1:numel(toChangeIdx)
+0038     currName    = modelFields{toChangeIdx(i),1};
+0039     currPrefix  = modelFields{toChangeIdx(i),2};
+0040     if isfield(model,currName)
+0041         currField   = model.(currName);
+0042     else
+0043         continue;
+0044     end
+0045     if ~all(startsWith(currField,regexpPattern('^[a-zA-Z_]')))
+0046         currField = strcat(currPrefix, currField);
+0047         hasChanged(toChangeIdx(i)) = true;
+0048 
+0049         if strcmp(currName,'genes')
+0050                 model.grRules = regexprep(model.grRules, '(\<[0-9_a-zA-Z])', 'G_$1');
+0051                 model.grRules = regexprep(model.grRules, ' G_or ', ' or ');
+0052                 model.grRules = regexprep(model.grRules, ' G_and ', ' and ');
+0053         end
+0054         model.(currName) = currField;
+0055     end
+0056 end
+0057 
+0058 hasChanged = modelFields(hasChanged,:);
+0059 hasChanged = append('model.', hasChanged(:,1), ' (', hasChanged(:,2), ' prefix)');
+0060 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/struct_conversion/editMiriam.html b/doc/struct_conversion/editMiriam.html new file mode 100644 index 000000000..95cde3fb1 --- /dev/null +++ b/doc/struct_conversion/editMiriam.html @@ -0,0 +1,200 @@ + + + + Description of editMiriam + + + + + + + + + +
Home > struct_conversion > editMiriam.m
+ + + +

editMiriam +

+ +

PURPOSE ^

+
editMiriam
+ +

SYNOPSIS ^

+
function model=editMiriam(model,type,object,miriamName,miriams,keep)
+ +

DESCRIPTION ^

+
 editMiriam
+   Change MIRIAM annotation fields, one annotation type at the same time.
+
+   Input:
+       model       model structure
+       type        'met', 'rxn', 'gene' or 'comp' dependent on which
+                   objects the annotations should be assigned to
+       object      either a cell array of IDs, a logical vector with the
+                   same number of elements as the type (see above) in the
+                   model, a vector of indexes, or 'all'
+       miriamName  string specifying the namespace of the identifier, for
+                   instance 'bigg.metabolite'. Should be a valid prefix
+                   from identifiers.org (e.g.
+                   https://registry.identifiers.org/registry/bigg.metabolite)
+       miriam      string or cell array of strings with annotation
+                   identifiers, e.g. '12dgr161'
+       keep        one of the following strings, specifying what should be
+                   done if an object already has an existing MIRIAM
+                   annotations with the same miriamName:
+                   'replace'   discard all existing annotations, all will
+                               be overwritten, even if the new annotation
+                               is an empty field. Should only be used if
+                               you do not want to keep any of the old
+                               annotation with the same miriamName
+                   'fill'      only add annotations to those objects that
+                               did not yet have an annotation with that
+                               miriamName. Otherwise, the existing
+                               annotation is kept, even if it is different
+                               from the suggested new annotation
+                   'add'       keep all existing annotations, and add any
+                               new annotations, after removing duplicates
+                   
+   Ouput:
+       model       model structure with updated MIRIAM annotation field
+   
+ Usage: model=editMiriam(model,type,object,miriamName,miriams,keep)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function model=editMiriam(model,type,object,miriamName,miriams,keep)
+0002 % editMiriam
+0003 %   Change MIRIAM annotation fields, one annotation type at the same time.
+0004 %
+0005 %   Input:
+0006 %       model       model structure
+0007 %       type        'met', 'rxn', 'gene' or 'comp' dependent on which
+0008 %                   objects the annotations should be assigned to
+0009 %       object      either a cell array of IDs, a logical vector with the
+0010 %                   same number of elements as the type (see above) in the
+0011 %                   model, a vector of indexes, or 'all'
+0012 %       miriamName  string specifying the namespace of the identifier, for
+0013 %                   instance 'bigg.metabolite'. Should be a valid prefix
+0014 %                   from identifiers.org (e.g.
+0015 %                   https://registry.identifiers.org/registry/bigg.metabolite)
+0016 %       miriam      string or cell array of strings with annotation
+0017 %                   identifiers, e.g. '12dgr161'
+0018 %       keep        one of the following strings, specifying what should be
+0019 %                   done if an object already has an existing MIRIAM
+0020 %                   annotations with the same miriamName:
+0021 %                   'replace'   discard all existing annotations, all will
+0022 %                               be overwritten, even if the new annotation
+0023 %                               is an empty field. Should only be used if
+0024 %                               you do not want to keep any of the old
+0025 %                               annotation with the same miriamName
+0026 %                   'fill'      only add annotations to those objects that
+0027 %                               did not yet have an annotation with that
+0028 %                               miriamName. Otherwise, the existing
+0029 %                               annotation is kept, even if it is different
+0030 %                               from the suggested new annotation
+0031 %                   'add'       keep all existing annotations, and add any
+0032 %                               new annotations, after removing duplicates
+0033 %
+0034 %   Ouput:
+0035 %       model       model structure with updated MIRIAM annotation field
+0036 %
+0037 % Usage: model=editMiriam(model,type,object,miriamName,miriams,keep)
+0038 miriamName=char(miriamName);
+0039 miriams=convertCharArray(miriams);
+0040 
+0041 %Check 'keep' input
+0042 keep=char(keep);
+0043 if ~any(strcmp(keep,{'replace','fill','add'}))
+0044     error('Invalid ''keep'', should be ''replace'',''fill'',''add''.')
+0045 end
+0046 %Check 'type' input
+0047 type=char(type);
+0048 if ~any(strcmp(type,{'met','gene','rxn','comp'}))
+0049     error('Invalid ''type'', should be ''met'', ''gene'', ''rxn'' or ''comp''.')
+0050 end
+0051 %Check 'object' input
+0052 if islogical(object)
+0053     idxInModel=find(object);
+0054 elseif isnumeric(object)
+0055     idxInModel=object;
+0056 else
+0057     object=convertCharArray(object);
+0058     if numel(object)==1 && strcmp(object{1},'all')
+0059         idxInModel=1:numel(model.([type,'s']));
+0060     else
+0061         idxInModel=getIndexes(model,object,[type,'s']);
+0062         if ~all(idxInModel)
+0063             dispEM('The following objects cannot be found in the model: ',true,object(~idxInModel))
+0064         end
+0065     end
+0066 end
+0067 %Check 'miriams' input
+0068 if numel(miriams)==1 && numel(idxInModel)~=1
+0069     miriams=repmat(miriams,numel(idxInModel),1);
+0070 elseif numel(miriams)~=numel(idxInModel)
+0071     error('The number of annotations does not match the number of objects.')
+0072 end
+0073 
+0074 miriamFieldName=[type,'Miriams'];
+0075 
+0076 if isfield(model,miriamFieldName)
+0077     [extractedMiriams,extractedMiriamNames]=extractMiriam(model.(miriamFieldName)(idxInModel),'all');
+0078 else
+0079     extractedMiriams=cell(numel(idxInModel),1);
+0080     extractedMiriamNames={miriamName};
+0081 end
+0082 
+0083 [~, midx]=ismember(miriamName,extractedMiriamNames);
+0084 if midx==0
+0085     midx=numel(extractedMiriamNames)+1;
+0086     extractedMiriamNames(end+1)={miriamName};
+0087     extractedMiriams(:,end+1)=miriams;
+0088 elseif strcmp(keep,'replace')
+0089     extractedMiriams(:,midx)=miriams;
+0090 else
+0091     noMiriam=cellfun(@isempty,extractedMiriams(:,midx));
+0092     extractedMiriams(noMiriam,midx)=miriams(noMiriam);
+0093     if strcmp(keep,'add') % Skipped when only filling empty entries
+0094         existingMiriams=[split(extractedMiriams(~noMiriam,midx),'; '), miriams(~noMiriam)];
+0095         uniqueMiriams=cell(size(existingMiriams,1),1);
+0096         for i=1:size(existingMiriams,1)
+0097             uniqueMiriams{i,1}=strjoin(unique(existingMiriams(i,:)), {'; '});
+0098         end
+0099         extractedMiriams(~noMiriam,midx)=uniqueMiriams;
+0100     end
+0101 end
+0102 
+0103 % Make Miriam field again
+0104 for i=1:numel(idxInModel)
+0105     miriam.name=cell(1,1);
+0106     miriam.value=cell(1,1);
+0107     for j=1:numel(extractedMiriamNames)
+0108         if ~isempty(extractedMiriams{i,j})
+0109             values=strsplit(extractedMiriams{i,j},'; ');
+0110             miriam.name(end+1:end+numel(values),1)=extractedMiriamNames(j);
+0111             miriam.value(end+1:end+numel(values),1)=values;
+0112         end
+0113     end
+0114     miriam.name(1)=[];
+0115     miriam.value(1)=[];
+0116     model.(miriamFieldName){idxInModel(i),1}=miriam;
+0117 end
+0118 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/struct_conversion/extractMiriam.html b/doc/struct_conversion/extractMiriam.html new file mode 100644 index 000000000..8bb0ae1ee --- /dev/null +++ b/doc/struct_conversion/extractMiriam.html @@ -0,0 +1,156 @@ + + + + Description of extractMiriam + + + + + + + + + +
Home > struct_conversion > extractMiriam.m
+ + + +

extractMiriam +

+ +

PURPOSE ^

+
extractMiriam
+ +

SYNOPSIS ^

+
function [miriams,extractedMiriamNames]=extractMiriam(modelMiriams,miriamNames)
+ +

DESCRIPTION ^

+
 extractMiriam
+   This function unpacks the information kept in metMiriams, rxnMiriams,
+   geneMiriams or compMiriams to make the annotation more
+   human-readable. The obtained cell array looks the same like in Excel
+   format, just the columns are split to have particular miriam name in
+   corresponding column
+
+   modelMiriams                a miriam structure (e.g. model.metMiriams)
+                               for one or multiple metabolites
+   miriamNames                 cell array with miriam names to be
+                               extracted (optional, default 'all', meaning
+                               that annotation for all miriam names found
+                               in modelMiriams will be extracted)
+
+   miriams                     a cell array with extracted miriams. if
+                               several miriam names are requested, the
+                               corresponding information is saved in
+                               different columns. if there are several ids
+                               available for the same entity (metabolite,
+                               gene, reaction or compartment), they are
+                               concatenated into one column. the total
+                               number of column represent the number of
+                               unique miriam names per entity
+   extractedMiriamNames        cell array with extracted miriam names
+
+ Usage: miriam=extractMiriam(modelMiriams,miriamName)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 function [miriams,extractedMiriamNames]=extractMiriam(modelMiriams,miriamNames)
+0002 % extractMiriam
+0003 %   This function unpacks the information kept in metMiriams, rxnMiriams,
+0004 %   geneMiriams or compMiriams to make the annotation more
+0005 %   human-readable. The obtained cell array looks the same like in Excel
+0006 %   format, just the columns are split to have particular miriam name in
+0007 %   corresponding column
+0008 %
+0009 %   modelMiriams                a miriam structure (e.g. model.metMiriams)
+0010 %                               for one or multiple metabolites
+0011 %   miriamNames                 cell array with miriam names to be
+0012 %                               extracted (optional, default 'all', meaning
+0013 %                               that annotation for all miriam names found
+0014 %                               in modelMiriams will be extracted)
+0015 %
+0016 %   miriams                     a cell array with extracted miriams. if
+0017 %                               several miriam names are requested, the
+0018 %                               corresponding information is saved in
+0019 %                               different columns. if there are several ids
+0020 %                               available for the same entity (metabolite,
+0021 %                               gene, reaction or compartment), they are
+0022 %                               concatenated into one column. the total
+0023 %                               number of column represent the number of
+0024 %                               unique miriam names per entity
+0025 %   extractedMiriamNames        cell array with extracted miriam names
+0026 %
+0027 % Usage: miriam=extractMiriam(modelMiriams,miriamName)
+0028 
+0029 if nargin<2 || (ischar(miriamNames) && strcmp(miriamNames,'all'))
+0030     extractAllTypes=true;
+0031 else
+0032     extractAllTypes=false;
+0033     miriamNames=convertCharArray(miriamNames);
+0034 end
+0035 
+0036 %The annotation for all miriam names should be extracted
+0037 if extractAllTypes
+0038     miriamNames={''};
+0039     for i=1:numel(modelMiriams)
+0040         if ~isempty(modelMiriams{i,1})
+0041             for j=1:numel(modelMiriams{i,1}.name)
+0042                 miriamNames{numel(miriamNames)+1,1}=modelMiriams{i,1}.name{j};
+0043             end
+0044         end
+0045     end
+0046     miriamNames=sort(unique(miriamNames));
+0047 end
+0048 
+0049 %Aggregate the final cell array table with extracted miriam information
+0050 miriams=cell(numel(modelMiriams),0);
+0051 for i=1:numel(miriamNames)
+0052     miriams=[miriams, extractMiriamType(modelMiriams,miriamNames{i})];
+0053 end
+0054 extractedMiriamNames=miriamNames;
+0055 
+0056 end
+0057 
+0058 function miriams=extractMiriamType(modelMiriams,miriamName)
+0059 %Create an empty cell array for ids vector
+0060 tempMiriams = cell([size(modelMiriams,1) 1]);
+0061 %Firstly obtain the list of relevant miriam ids. Several entries may have
+0062 %several miriam ids, such ids are kept in additional columns
+0063 for i=1:numel(modelMiriams)
+0064     if (~isempty(modelMiriams{i,1})) && any(strcmp(modelMiriams{i,1}.name,miriamName))
+0065         for j=1:numel(modelMiriams{i,1}.name)
+0066             if strcmp(modelMiriams{i,1}.name(j),miriamName)
+0067                 tempMiriams(i,j) = modelMiriams{i,1}.value(j);
+0068             end
+0069         end
+0070     else
+0071         modelMiriams{i,1} = '';
+0072     end
+0073 end
+0074 
+0075 %Concatenate multiple ids per miriam name in one column with semicolon as
+0076 %separator
+0077 miriams = cell([size(tempMiriams,1) 1]);
+0078 notEmpty=~cellfun(@isempty,tempMiriams);
+0079 for i=1:size(miriams,1)
+0080     miriams{i}=strjoin(tempMiriams(i,notEmpty(i,:)),{'; '});
+0081 end
+0082 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/struct_conversion/index.html b/doc/struct_conversion/index.html new file mode 100644 index 000000000..aa35ccd6b --- /dev/null +++ b/doc/struct_conversion/index.html @@ -0,0 +1,29 @@ + + + + Index for Directory struct_conversion + + + + + + + + + + +
< Master indexIndex for struct_conversion >
+ +

Index for struct_conversion

+ +

Matlab files in this directory:

+ +
 addIdentifierPrefixaddIdentifierPrefix
 editMiriameditMiriam
 extractMiriamextractMiriam
 ravenCobraWrapperravenCobraWrapper
 removeIdentifierPrefixremoveIdentifierPrefix
 standardizeModelFieldOrderstandardizeModelFieldOrder
+ + + + +
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/struct_conversion/ravenCobraWrapper.html b/doc/struct_conversion/ravenCobraWrapper.html new file mode 100644 index 000000000..fdbcf58db --- /dev/null +++ b/doc/struct_conversion/ravenCobraWrapper.html @@ -0,0 +1,528 @@ + + + + Description of ravenCobraWrapper + + + + + + + + + +
Home > struct_conversion > ravenCobraWrapper.m
+ + + +

ravenCobraWrapper +

+ +

PURPOSE ^

+
ravenCobraWrapper
+ +

SYNOPSIS ^

+
function newModel=ravenCobraWrapper(model)
+ +

DESCRIPTION ^

+
 ravenCobraWrapper
+   Converts between RAVEN and COBRA structures
+
+   Input: model          a RAVEN/COBRA-compatible model structure
+
+   Ouput: newModel       a COBRA/RAVEN-compatible model structure
+   
+   This function is a bidirectional tool to convert between RAVEN and
+   COBRA structures. It recognises COBRA structure by checking field
+   'rules' existense, which is only found in COBRA Toolbox structure. If
+   the COBRA model also has a grRules field, then this will be used
+   instead of parsing the rules field.
+
+   NOTE: During RAVEN -> COBRA -> RAVEN conversion cycle the following
+   fields are lost: annotation, compOutside, compMiriams, rxnComps,
+   geneComps, unconstrained. Boundary metabolites are lost, because COBRA
+   structure does not involve boundary metabolites, so they are removed
+   using simplifyModel before RAVEN -> COBRA conversion. The field 'rev'
+   is also partially lost, but during COBRA -> RAVEN conversion it's
+   reconstructed based on lower bound reaction values
+
+   NOTE: During COBRA -> RAVEN -> COBRA conversion cycle the following
+   fields are lost: geneEntrezID, modelVersion, proteins
+
+   NOTE: The information about mandatory RAVEN fields was taken from
+   checkModelStruct function, whereas the corresponding information about
+   COBRA fields was fetched from verifyModel function
+
+ Usage: newModel=ravenCobraWrapper(model)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: + +This function is called by: +
    +
+ + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 function newModel=ravenCobraWrapper(model)
+0002 % ravenCobraWrapper
+0003 %   Converts between RAVEN and COBRA structures
+0004 %
+0005 %   Input: model          a RAVEN/COBRA-compatible model structure
+0006 %
+0007 %   Ouput: newModel       a COBRA/RAVEN-compatible model structure
+0008 %
+0009 %   This function is a bidirectional tool to convert between RAVEN and
+0010 %   COBRA structures. It recognises COBRA structure by checking field
+0011 %   'rules' existense, which is only found in COBRA Toolbox structure. If
+0012 %   the COBRA model also has a grRules field, then this will be used
+0013 %   instead of parsing the rules field.
+0014 %
+0015 %   NOTE: During RAVEN -> COBRA -> RAVEN conversion cycle the following
+0016 %   fields are lost: annotation, compOutside, compMiriams, rxnComps,
+0017 %   geneComps, unconstrained. Boundary metabolites are lost, because COBRA
+0018 %   structure does not involve boundary metabolites, so they are removed
+0019 %   using simplifyModel before RAVEN -> COBRA conversion. The field 'rev'
+0020 %   is also partially lost, but during COBRA -> RAVEN conversion it's
+0021 %   reconstructed based on lower bound reaction values
+0022 %
+0023 %   NOTE: During COBRA -> RAVEN -> COBRA conversion cycle the following
+0024 %   fields are lost: geneEntrezID, modelVersion, proteins
+0025 %
+0026 %   NOTE: The information about mandatory RAVEN fields was taken from
+0027 %   checkModelStruct function, whereas the corresponding information about
+0028 %   COBRA fields was fetched from verifyModel function
+0029 %
+0030 % Usage: newModel=ravenCobraWrapper(model)
+0031 
+0032 if isfield(model,'rules')
+0033     isRaven=false;
+0034 else
+0035     isRaven=true;
+0036 end
+0037 
+0038 ravenPath=findRAVENroot();
+0039 
+0040 % Load COBRA field information
+0041 fid             = fopen(fullfile(ravenPath,'struct_conversion','COBRA_structure_fields.csv')); % Taken from https://github.com/opencobra/cobratoolbox/blob/develop/src/base/io/definitions/COBRA_structure_fields.csv
+0042 fieldFile       = textscan(fid,repmat('%s',1,15),'Delimiter','\t','HeaderLines',1);
+0043 dbFields        = ~cellfun(@isempty,fieldFile{5}); % Only keep fields with database annotations that should be translated to xxxMiriams
+0044 dbFields        = dbFields & ~contains(fieldFile{1},{'metInChIString','metKEGGID','metPubChemID','rxnECNumbers'});
+0045 COBRAnamespace  = fieldFile{5}(dbFields);
+0046 COBRAnamespace  = regexprep(COBRAnamespace,';.*',''); % Only keep first suggested namespace
+0047 COBRAfields     = fieldFile{1}(dbFields);
+0048 fclose(fid);
+0049 
+0050 % Load conversion between additional COBRA fields and namespaces:
+0051 fid             = fopen(fullfile(ravenPath,'struct_conversion','cobraNamespaces.csv'));
+0052 fieldFile       = textscan(fid,'%s %s','Delimiter',',','HeaderLines',0);
+0053 COBRAfields     = [COBRAfields; fieldFile{1}];
+0054 COBRAnamespace  = [COBRAnamespace; fieldFile{2}];
+0055 rxnCOBRAfields  = COBRAfields(startsWith(COBRAfields,'rxn'));
+0056 rxnNamespaces   = COBRAnamespace(startsWith(COBRAfields,'rxn'));
+0057 metCOBRAfields  = COBRAfields(startsWith(COBRAfields,'met'));
+0058 metNamespaces   = COBRAnamespace(startsWith(COBRAfields,'met'));
+0059 geneCOBRAfields = COBRAfields(startsWith(COBRAfields,'gene'));
+0060 geneNamespaces  = COBRAnamespace(startsWith(COBRAfields,'gene'));
+0061 fclose(fid);
+0062 
+0063 if isRaven
+0064     %Firstly remove boundary metabolites
+0065     model=simplifyModel(model);
+0066 end
+0067 
+0068 % Keep fields that have identical names and content
+0069 newModel.S=model.S;
+0070 newModel.lb=model.lb;
+0071 newModel.ub=model.ub;
+0072 if isfield(model,'c')
+0073     newModel.c=model.c;
+0074 else
+0075     newModel.c=zeros(numel(model.rxns),1);
+0076 end
+0077 newModel.rxns=model.rxns;
+0078 optFields = {'rxnNames','rxnNotes','rxnConfidenceScores','rxnDeltaG',...
+0079     'rxnGeneMat','rev','subSystems','comps','compNames','metCharges',...
+0080     'metDeltaG','metFormulas','metNotes','metSmiles','genes','proteins'};
+0081 for i=1:length(optFields)
+0082     if isfield(model,optFields{i})
+0083         newModel.(optFields{i})=model.(optFields{i});
+0084     end
+0085 end
+0086     
+0087 % Convert unique fields
+0088 if isRaven
+0089     fprintf('Converting RAVEN structure to COBRA..\n');
+0090     %Convert from RAVEN to COBRA structure
+0091     
+0092     %Mandatory COBRA fields
+0093     newModel.rxns=model.rxns;
+0094     if all(~cellfun(@isempty,regexp(model.mets,'\[[^\]]+\]$')))
+0095         newModel.mets=model.mets;
+0096     else
+0097         %Check if model has compartment info as "met_c" suffix in all metabolites:
+0098         BiGGformat = false(size(model.mets));
+0099         for i=1:numel(model.comps)
+0100             compPos=model.metComps==i;
+0101             BiGGformat(compPos)=~cellfun(@isempty,regexp(model.mets(compPos),['_' model.comps{i} '$']));
+0102         end
+0103         if all(BiGGformat)
+0104             newModel.mets=model.mets;
+0105             for i=1:numel(model.comps)
+0106                 newModel.mets=regexprep(newModel.mets,['_' model.comps{i} '$'],['[' model.comps{i} ']']);
+0107             end
+0108         else
+0109             newModel.mets=strcat(model.mets,'[',model.comps(model.metComps),']');
+0110         end
+0111     end
+0112 
+0113     %b, csense, osenseStr, genes, rules are also mandatory, but defined
+0114     %later to match the order of fields
+0115     
+0116     %Optional COBRA fields
+0117     if isfield(model,'id')
+0118         newModel.modelID=model.id;
+0119     end
+0120     if isfield(model,'name')
+0121         newModel.modelName=model.name;
+0122     end
+0123     if isfield(model,'eccodes')
+0124         newModel.rxnECNumbers=model.eccodes;
+0125     end
+0126     if isfield(model,'rxnMiriams')
+0127         [miriams,extractedMiriamNames]=extractMiriam(model.rxnMiriams);
+0128         for i = 1:length(rxnCOBRAfields)
+0129             j=ismember(extractedMiriamNames,rxnNamespaces{i});
+0130             if any(j)
+0131                 eval(['newModel.' rxnCOBRAfields{i} ' = miriams(:,j);'])
+0132             end
+0133         end
+0134     end
+0135     if isfield(model,'rxnReferences') % Concatenate model.rxnReferences to those extracted from model.rxnMiriams
+0136         if isfield(newModel,'rxnReferences')
+0137             newModel.rxnReferences = strcat(newModel.rxnReferences,{'; '},model.rxnReferences);
+0138             newModel.rxnReferences = regexprep(newModel.rxnReferences,'^; $','');
+0139         else
+0140             newModel.rxnReferences = model.rxnReferences;
+0141         end
+0142     end
+0143     if isfield(model,'metNames')
+0144         newModel.metNames=strcat(model.metNames,' [',model.compNames(model.metComps),']');
+0145     end
+0146     if isfield(model,'metMiriams')
+0147         [miriams,extractedMiriamNames]=extractMiriam(model.metMiriams);
+0148         %Shorten miriam names for KEGG and PubChem. These shorter names
+0149         %will be used later to concatenate KEGG COMPOUND/GLYCAN and PubChem
+0150         %Compound/Substance, into corresponding COBRA model fields
+0151         extractedMiriamNames=regexprep(extractedMiriamNames,'^kegg\..+','kegg');
+0152         extractedMiriamNames=regexprep(extractedMiriamNames,'^pubchem\..+','pubchem');
+0153         i=ismember(extractedMiriamNames,'kegg');
+0154         if any(i) % Combine KEGG compounds and glycans
+0155             for j=1:length(i)
+0156                 if i(j) && isfield(newModel,'metKEGGID')~=1
+0157                     newModel.metKEGGID=miriams(:,j);
+0158                 elseif i(j)
+0159                     newModel.metKEGGID=strcat(newModel.metKEGGID,';',miriams(:,j));
+0160                 end
+0161             end
+0162             newModel.metKEGGID=regexprep(newModel.metKEGGID,'^;|;$','');
+0163         end
+0164         i=ismember(extractedMiriamNames,'pubchem');
+0165         if any(i) % Combine Pubchem compounds and substances
+0166             for j=1:length(i)
+0167                 if i(j) && isfield(newModel,'metPubChemID')~=1
+0168                     newModel.metPubChemID=miriams(:,j);
+0169                 elseif i(j)
+0170                     newModel.metPubChemID=strcat(newModel.metPubChemID,';',miriams(:,j));
+0171                 end
+0172             end
+0173             newModel.metPubChemID=regexprep(newModel.metPubChemID,'^;|;$','');
+0174         end
+0175         %All other Miriams can be directly parsed with no modifications:
+0176         for i = 1:length(metCOBRAfields)
+0177             j=ismember(extractedMiriamNames,metNamespaces{i});
+0178             if any(j)
+0179                 eval(['newModel.' metCOBRAfields{i} ' = miriams(:,j);'])
+0180             end
+0181         end
+0182     end
+0183     if isfield(model,'inchis')
+0184         newModel.metInChIString=regexprep(strcat('InChI=', model.inchis),'^InChI=$','');
+0185     end
+0186     newModel.b=zeros(numel(model.mets),1);
+0187     newModel.csense=repmat('E',size(model.mets));
+0188     if isfield(model,'geneMiriams')
+0189         [~,extractedMiriamNames]=extractMiriam(model.geneMiriams);
+0190         for i = 1:length(geneCOBRAfields)
+0191             j=ismember(extractedMiriamNames,geneNamespaces{i});
+0192             if any(j)
+0193                 eval(['newModel.' geneCOBRAfields{i} ' = miriams(:,j);'])
+0194             end
+0195         end
+0196     end
+0197     if isfield(model,'geneShortNames')
+0198         newModel.geneNames=model.geneShortNames;
+0199     end
+0200     if isfield(model,'genes')
+0201         newModel.rules=grrulesToRules(model);
+0202     else
+0203         fprintf('WARNING: no genes detected. The model therefore may not be exportable to SBML file with writeCbModel\n');
+0204     end
+0205     % If needed, normalise subSystems to cell-of-cells format
+0206     if isfield(newModel,'subSystems') && ~isempty(newModel.subSystems)
+0207         if ~iscell(newModel.subSystems{1})
+0208             newModel.subSystems = cellfun(@(x) {x}, newModel.subSystems, 'UniformOutput', false);
+0209         end
+0210     end
+0211 else
+0212     fprintf('Converting COBRA structure to RAVEN..\n');
+0213     %Convert from COBRA to RAVEN structure
+0214 
+0215     %Mandatory RAVEN fields
+0216     newModel.mets=model.mets;
+0217     if ~isfield(model,'comps')
+0218         %Since 'comps' field is not mandatory in COBRA, it may be required
+0219         %to obtain the non-redundant list of comps from metabolite ids, if
+0220         %'comps' field is not available
+0221         newModel.comps = unique(regexprep(model.mets,'.*\[([^\]]+)\]$','$1'));
+0222         newModel.compNames = newModel.comps;
+0223     end
+0224     for i=1:numel(newModel.comps)
+0225         newModel.mets=regexprep(newModel.mets,['\[', newModel.comps{i}, '\]$'],'');
+0226         newModel.mets=regexprep(newModel.mets,['\[', newModel.compNames{i}, '\]$'],'');
+0227     end
+0228     
+0229     %In some cases (e.g. any model that uses BiGG ids as main ids), there
+0230     %may be overlapping mets due to removal of compartment info. To avoid
+0231     %this, we change compartments from e.g. [c] into _c
+0232     if numel(unique(newModel.mets))~=numel(model.mets)
+0233         newModel.mets=model.mets;
+0234         for i=1:numel(newModel.comps)
+0235             newModel.mets=regexprep(newModel.mets,['\[' newModel.comps{i} '\]$'],['_' newModel.comps{i}]);
+0236         end
+0237     end
+0238     %Since COBRA no longer contains rev field it is assumed that rxn is
+0239     %reversible if its lower bound is set below zero
+0240     if ~isfield(model,'rev')
+0241         for i=1:numel(model.rxns)
+0242             if model.lb(i)<0
+0243                 newModel.rev(i,1)=1;
+0244             else
+0245                 newModel.rev(i,1)=0;
+0246             end
+0247         end
+0248     end
+0249     newModel.b=zeros(numel(model.mets),1);
+0250    
+0251     %metComps is also mandatory, but defined later to match the order of
+0252     %fields
+0253     
+0254     %Fields 'name' and 'id' are also considered as mandatory, but
+0255     %these are added to the model during exportModel/exportToExcelFormat
+0256     %anyway, so there is no point to add this information here
+0257     
+0258     %Optional RAVEN fields
+0259     if isfield(model,'modelID')
+0260         newModel.id=model.modelID;
+0261     end
+0262     if isfield(model,'modelName')
+0263         newModel.name=model.modelName;
+0264     end
+0265     if isfield(model,'rules') && ~isfield(model,'grRules')
+0266         model.grRules        = rulesTogrrules(model);
+0267     end
+0268     if isfield(model,'grRules')
+0269         [grRules,rxnGeneMat] = standardizeGrRules(model,true);
+0270         newModel.grRules     = grRules;
+0271         newModel.rxnGeneMat  = rxnGeneMat;
+0272     end
+0273     if isfield(model,'rxnECNumbers')
+0274         newModel.eccodes=regexprep(model.rxnECNumbers,'EC|EC:','');
+0275     end
+0276     if any(isfield(model,rxnCOBRAfields))
+0277         for i=1:numel(model.rxns)
+0278             counter=1;
+0279             newModel.rxnMiriams{i,1}=[];
+0280             if isfield(model,'rxnReferences')
+0281                 if ~isempty(model.rxnReferences{i})
+0282                     pmids = model.rxnReferences{i};
+0283                     pmids = strsplit(pmids,'; ');
+0284                     nonPmids = cellfun(@isempty,regexp(pmids,'^\d+$','match','once'));
+0285                     if any(nonPmids) %Not a pubmed id, keep in rxnReferences instead
+0286                         newModel.rxnReferences{i,1} = strjoin(pmids(nonPmids),', ');
+0287                         pmids(nonPmids)=[];
+0288                     end
+0289                     for j = 1:length(pmids)
+0290                         newModel.rxnMiriams{i,1}.name{counter,1} = 'pubmed';
+0291                         newModel.rxnMiriams{i,1}.value{counter,1} = pmids{j};
+0292                         counter=counter+1;
+0293                     end
+0294                 end
+0295             end
+0296             for j = 2:length(rxnCOBRAfields) %Start from 2, as 1 is rxnReferences
+0297                 if isfield(model,rxnCOBRAfields{j})
+0298                     rxnAnnotation = eval(['model.' rxnCOBRAfields{j} '{i}']);
+0299                     if ~isempty(rxnAnnotation)
+0300                         rxnAnnotation = strtrim(strsplit(rxnAnnotation,';'));
+0301                         for a=1:length(rxnAnnotation)
+0302                             newModel.rxnMiriams{i,1}.name{counter,1} = rxnNamespaces{j};
+0303                             newModel.rxnMiriams{i,1}.value{counter,1} = rxnAnnotation{a};
+0304                             counter=counter+1;
+0305                         end
+0306                     end
+0307                 end
+0308             end
+0309         end
+0310     end
+0311     if isfield(newModel,'rxnReferences')
+0312         emptyEntry = cellfun(@isempty,newModel.rxnReferences);
+0313         newModel.rxnReferences(emptyEntry)={''};
+0314         diffNumel = numel(newModel.rxns) - numel(newModel.rxnReferences);
+0315         if diffNumel > 0
+0316             newModel.rxnReferences(end+1:end+diffNumel) = {''};
+0317         end
+0318     end
+0319     if any(isfield(model,geneCOBRAfields))
+0320         for i=1:numel(model.genes)
+0321             counter=1;
+0322             newModel.geneMiriams{i,1}=[];
+0323             for j = 1:length(geneCOBRAfields)
+0324                 if isfield(model,geneCOBRAfields{j})
+0325                     geneAnnotation = eval(['model.' geneCOBRAfields{j} '{i}']);
+0326                     if ~isempty(geneAnnotation)
+0327                         geneAnnotation = strtrim(strsplit(geneAnnotation,';'));
+0328                         for a=1:length(geneAnnotation)
+0329                             newModel.geneMiriams{i,1}.name{counter,1} = geneNamespaces{j};
+0330                             newModel.geneMiriams{i,1}.value{counter,1} = geneAnnotation{a};
+0331                             counter=counter+1;
+0332                         end
+0333                     end
+0334                 end
+0335             end
+0336         end
+0337     end
+0338     if isfield(model,'geneNames')
+0339         newModel.geneShortNames=model.geneNames;
+0340     end
+0341     newModel.metNames=model.metNames;
+0342     for i=1:numel(newModel.comps)
+0343         newModel.metNames=regexprep(newModel.metNames,['\[', newModel.comps{i}, '\]$'],'');
+0344         newModel.metNames=regexprep(newModel.metNames,['\[', newModel.compNames{i}, '\]$'],'');
+0345     end
+0346     newModel.metNames=deblank(newModel.metNames);
+0347     newModel.metComps=regexprep(model.mets,'^.+\[','');
+0348     newModel.metComps=regexprep(newModel.metComps,'\]$','');
+0349     [~, newModel.metComps]=ismember(newModel.metComps,newModel.comps);
+0350     if isfield(model,'metInChIString')
+0351         newModel.inchis=regexprep(model.metInChIString,'^InChI=','');
+0352     end
+0353     printWarning=false;
+0354     if any(isfield(model,[metCOBRAfields;'metKEGGID';'metPubChemID']))
+0355         for i=1:numel(model.mets)
+0356             counter=1;
+0357             newModel.metMiriams{i,1}=[];
+0358             if isfield(model,'metKEGGID')
+0359                 if ~isempty(model.metKEGGID{i})
+0360                     if strcmp(model.metKEGGID{i}(1),'C')
+0361                         newModel.metMiriams{i,1}.name{counter,1} = 'kegg.compound';
+0362                         newModel.metMiriams{i,1}.value{counter,1} = model.metKEGGID{i};
+0363                         counter=counter+1;
+0364                     elseif strcmp(model.metKEGGID{i}(1),'G')
+0365                         newModel.metMiriams{i,1}.name{counter,1} = 'kegg.glycan';
+0366                         newModel.metMiriams{i,1}.value{counter,1} = model.metKEGGID{i};
+0367                         counter=counter+1;
+0368                     end
+0369                 end
+0370             end
+0371             if isfield(model,'metPubChemID')
+0372                 if ~isempty(model.metPubChemID{i})
+0373                     if length(model.metPubChemID{i})>3 && strcmp(model.metPubChemID{i}(1:4),'CID:')
+0374                         newModel.metMiriams{i,1}.name{counter,1} = 'pubchem.compound';
+0375                         newModel.metMiriams{i,1}.value{counter,1} = model.metPubChemID{i};
+0376                         counter=counter+1;
+0377                     elseif length(model.metPubChemID{i})>3 && strcmp(model.metPubChemID{i}(1:4),'SID:')
+0378                         newModel.metMiriams{i,1}.name{counter,1} = 'pubchem.substance';
+0379                         newModel.metMiriams{i,1}.value{counter,1} = model.metPubChemID{i};
+0380                         counter=counter+1;
+0381                     else
+0382                         newModel.metMiriams{i,1}.name{counter,1} = 'pubchem.compound';
+0383                         newModel.metMiriams{i,1}.value{counter,1} = model.metPubChemID{i};
+0384                         counter=counter+1;
+0385                         printWarning=true;
+0386                     end
+0387                 end
+0388             end            
+0389             for j = 1:length(metCOBRAfields)
+0390                 if isfield(model,metCOBRAfields{j})
+0391                     metAnnotation = eval(['model.' metCOBRAfields{j} '{i}']);
+0392                     if ~isempty(metAnnotation)
+0393                         metAnnotation = strtrim(strsplit(metAnnotation,';'));
+0394                         for a=1:length(metAnnotation)
+0395                             newModel.metMiriams{i,1}.name{counter,1} = metNamespaces{j};
+0396                             newModel.metMiriams{i,1}.value{counter,1} = metAnnotation{a};
+0397                             counter=counter+1;
+0398                         end
+0399                     end
+0400                 end
+0401             end
+0402         end
+0403     end
+0404     % Flatten subSystems if every reaction has exactly one subsystem.
+0405     if isfield(newModel,'subSystems') && ~isempty(newModel.subSystems)
+0406         if all(cellfun(@(x) iscell(x) && isscalar(x), newModel.subSystems))
+0407             newModel.subSystems = transpose([newModel.subSystems{:}]);
+0408         end
+0409     end
+0410     if printWarning
+0411         fprintf('Could not determine whether PubChemIDs are compounds (CID)\n or substances (SID). All annotated PubChemIDs will therefore \n be assigned as compounds (CID).\n');
+0412     end
+0413 end
+0414 
+0415 % Order fields
+0416 newModel=standardizeModelFieldOrder(newModel); % Corrects for both RAVEN and COBRA models
+0417 end
+0418 
+0419 function rules=grrulesToRules(model)
+0420 %This function just takes grRules, changes all gene names to
+0421 %'x(geneNumber)' and also changes 'or' and 'and' relations to corresponding
+0422 %symbols
+0423 replacingGenes=cell([size(model.genes,1) 1]);
+0424 for i=1:numel(replacingGenes)
+0425     replacingGenes{i}=strcat('x(',num2str(i),')');
+0426 end
+0427 rules = strcat({' '},model.grRules,{' '});
+0428 for i=1:length(model.genes)
+0429     rules=regexprep(rules,[' ' model.genes{i} ' '],[' ' replacingGenes{i} ' ']);
+0430     rules=regexprep(rules,['(' model.genes{i} ' '],['(' replacingGenes{i} ' ']);
+0431     rules=regexprep(rules,[' ' model.genes{i} ')'],[' ' replacingGenes{i} ')']);
+0432 end
+0433 rules=regexprep(rules,' and ',' & ');
+0434 rules=regexprep(rules,' or ',' | ');
+0435 rules=strtrim(rules);
+0436 end
+0437 
+0438 function grRules=rulesTogrrules(model)
+0439 %This function takes rules, replaces &/| for and/or, replaces the x(i)
+0440 %format with the actual gene ID, and takes out extra whitespace and
+0441 %redundant parenthesis introduced by COBRA, to create grRules.
+0442 grRules = strrep(model.rules,'&','and');
+0443 grRules = strrep(grRules,'|','or');
+0444 for i = 1:length(model.genes)
+0445     grRules = strrep(grRules,['x(' num2str(i) ')'],model.genes{i});
+0446 end
+0447 grRules = strrep(grRules,'( ','(');
+0448 grRules = strrep(grRules,' )',')');
+0449 grRules = regexprep(grRules,'^(',''); %rules that start with a "("
+0450 grRules = regexprep(grRules,')$',''); %rules that end with a ")"
+0451 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/struct_conversion/removeIdentifierPrefix.html b/doc/struct_conversion/removeIdentifierPrefix.html new file mode 100644 index 000000000..3fae6a6c2 --- /dev/null +++ b/doc/struct_conversion/removeIdentifierPrefix.html @@ -0,0 +1,143 @@ + + + + Description of removeIdentifierPrefix + + + + + + + + + +
Home > struct_conversion > removeIdentifierPrefix.m
+ + + +

removeIdentifierPrefix +

+ +

PURPOSE ^

+
removeIdentifierPrefix
+ +

SYNOPSIS ^

+
function [model, hasChanged]=removeIdentifierPrefix(model,fields,forceRemove)
+ +

DESCRIPTION ^

+
 removeIdentifierPrefix
+   This function removes identifier prefixes:
+       "R_" for model.rxns, model.rxnNames and model.id,
+       "M_" for model.mets and model.metNames,
+       "C_" for model.comps;
+       "G_" for model.genes (and also represented in model.grRules).
+   By default, the prefixes are only removed if all entries in a
+   particular field has the prefix. The prefixes might have been present
+   because one or more identifiers do not start with a letter or _, which
+   conflicts with SBML specifications.
+
+ Input:
+   model           model whose identifiers should be modified
+   fields          cell array with model field names from which the
+                   identifiers should be removed, possible values: 
+                   'rxns', 'mets', 'comps', 'genes', 'metNames', 
+                   'rxnNames', 'id'. (optional, by default all listed
+                   model fields will be checked).
+   forceRemove     if prefixes should be removed even if not all entries
+                   in a model field have the prefix (optional, default
+                   false)
+
+ Output:
+   model           modified model
+   hasChanged      cell array with fields and prefixes that are removed
+
+ Usage: model=removeIdentifierPrefix(model,fields,forceRemove)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function [model, hasChanged]=removeIdentifierPrefix(model,fields,forceRemove)
+0002 % removeIdentifierPrefix
+0003 %   This function removes identifier prefixes:
+0004 %       "R_" for model.rxns, model.rxnNames and model.id,
+0005 %       "M_" for model.mets and model.metNames,
+0006 %       "C_" for model.comps;
+0007 %       "G_" for model.genes (and also represented in model.grRules).
+0008 %   By default, the prefixes are only removed if all entries in a
+0009 %   particular field has the prefix. The prefixes might have been present
+0010 %   because one or more identifiers do not start with a letter or _, which
+0011 %   conflicts with SBML specifications.
+0012 %
+0013 % Input:
+0014 %   model           model whose identifiers should be modified
+0015 %   fields          cell array with model field names from which the
+0016 %                   identifiers should be removed, possible values:
+0017 %                   'rxns', 'mets', 'comps', 'genes', 'metNames',
+0018 %                   'rxnNames', 'id'. (optional, by default all listed
+0019 %                   model fields will be checked).
+0020 %   forceRemove     if prefixes should be removed even if not all entries
+0021 %                   in a model field have the prefix (optional, default
+0022 %                   false)
+0023 %
+0024 % Output:
+0025 %   model           modified model
+0026 %   hasChanged      cell array with fields and prefixes that are removed
+0027 %
+0028 % Usage: model=removeIdentifierPrefix(model,fields,forceRemove)
+0029 
+0030 if nargin<2 || isempty(fields)
+0031     fields = {'rxns','mets','comps','genes','metNames','rxnNames','id'};
+0032 end
+0033 if nargin<3 || isempty(forceRemove)
+0034     forceRemove = false;
+0035 end
+0036 
+0037 modelFields = {'rxns',      'R_';
+0038     'mets',      'M_';
+0039     'comps',     'C_';
+0040     'genes',     'G_';
+0041     'metNames',  'M_';
+0042     'rxnNames',  'R_';
+0043     'id',        'M_'};
+0044 
+0045 toChangeIdx = find(ismember(modelFields(:,1),fields));
+0046 hasChanged  = false(numel(modelFields(:,1)),1);
+0047 for i=1:numel(toChangeIdx)
+0048     currName    = modelFields{toChangeIdx(i),1};
+0049     currPrefix  = modelFields{toChangeIdx(i),2};
+0050     currField   = model.(currName);
+0051 
+0052     if forceRemove && any(startsWith(currField,currPrefix))
+0053         hasPrefix = true;
+0054     else
+0055         hasPrefix = all(startsWith(currField,currPrefix));
+0056     end
+0057     if hasPrefix
+0058         currField = regexprep(currField,['^' currPrefix],'');
+0059         hasChanged(toChangeIdx(i)) = true;
+0060         if strcmp(currName,'genes')
+0061             model.grRules=regexprep(model.grRules,'^G_','');
+0062             model.grRules=regexprep(model.grRules,'\(G_','(');
+0063             model.grRules=regexprep(model.grRules,' G_',' ');
+0064         end
+0065     end
+0066     model.(currName) = currField;
+0067 end
+0068 hasChanged = modelFields(hasChanged,:);
+0069 hasChanged = append('model.', hasChanged(:,1), ' (', hasChanged(:,2), ' prefix)');
+0070 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/struct_conversion/standardizeModelFieldOrder.html b/doc/struct_conversion/standardizeModelFieldOrder.html new file mode 100644 index 000000000..8810543a0 --- /dev/null +++ b/doc/struct_conversion/standardizeModelFieldOrder.html @@ -0,0 +1,123 @@ + + + + Description of standardizeModelFieldOrder + + + + + + + + + +
Home > struct_conversion > standardizeModelFieldOrder.m
+ + + +

standardizeModelFieldOrder +

+ +

PURPOSE ^

+
standardizeModelFieldOrder
+ +

SYNOPSIS ^

+
function orderedModel=standardizeModelFieldOrder(model)
+ +

DESCRIPTION ^

+
 standardizeModelFieldOrder
+   Orders fields of RAVEN model structure as specified at
+   https://github.com/SysBioChalmers/RAVEN/wiki/RAVEN-Model-Structure
+
+   Input: model           model structure, either RAVEN or COBRA format
+
+   Output: orderedModel   model structure with ordered fields
+
+   The model fields themselves are not changed, only the order is
+   modified. For changing model fields between RAVEN and COBRA format, use
+   ravenCobraWrapper().
+
+ Usage: orderedModel=standardizeModelFieldOrder(model)
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: + + + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 function orderedModel=standardizeModelFieldOrder(model)
+0002 % standardizeModelFieldOrder
+0003 %   Orders fields of RAVEN model structure as specified at
+0004 %   https://github.com/SysBioChalmers/RAVEN/wiki/RAVEN-Model-Structure
+0005 %
+0006 %   Input: model           model structure, either RAVEN or COBRA format
+0007 %
+0008 %   Output: orderedModel   model structure with ordered fields
+0009 %
+0010 %   The model fields themselves are not changed, only the order is
+0011 %   modified. For changing model fields between RAVEN and COBRA format, use
+0012 %   ravenCobraWrapper().
+0013 %
+0014 % Usage: orderedModel=standardizeModelFieldOrder(model)
+0015 
+0016 ravenPath=findRAVENroot();
+0017 
+0018 if ~isfield(model,'rules') % Check if model is RAVEN
+0019     fid = fopen(fullfile(ravenPath,'struct_conversion','orderRavenFields.csv'));
+0020     fields = textscan(fid,'%s','Delimiter',',','HeaderLines',0);
+0021     fields = fields{1};
+0022     fclose(fid);
+0023 else % If model is COBRA
+0024     fid = fopen(fullfile(ravenPath,'struct_conversion','COBRA_structure_fields.csv')); % Taken from https://github.com/opencobra/cobratoolbox/blob/develop/src/base/io/definitions/COBRA_structure_fields.csv
+0025     fields = textscan(fid,repmat('%s',1,15),'Delimiter','\t','HeaderLines',1);
+0026     fields = fields{1};
+0027     fclose(fid);
+0028 end
+0029 
+0030 modelfields = fieldnames(model);
+0031 order = fields(ismember(fields(:,1),modelfields));
+0032 remainingOrder = sort(setdiff(modelfields,order));
+0033 overallOrder = [columnVector(order);columnVector(remainingOrder)];
+0034 orderedModel = orderfields(model,overallOrder);
+0035 end
+0036 
+0037 function vecT = columnVector(vec)
+0038 % Converts a vector to a column vector
+0039 %
+0040 % USAGE:
+0041 %
+0042 %   vecT = columnVector(vec)
+0043 %
+0044 % INPUT:
+0045 %   vec:     a vector
+0046 %
+0047 % OUTPUT:
+0048 %   vecT:    a column vector
+0049 %
+0050 % .. Authors:
+0051 %     - Original file: Markus Herrgard
+0052 %     - Minor changes: Laurent Heirendt January 2017
+0053 %     - Copied from COBRA Toolbox May 2022
+0054 
+0055 [n, m] = size(vec);
+0056 
+0057 if (m ~= 1 && n < m) || n == 1
+0058     vecT = vec';
+0059 else
+0060     vecT = vec;
+0061 end
+0062 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/testing/manual_tests/ManualINITTests.html b/doc/testing/manual_tests/ManualINITTests.html new file mode 100644 index 000000000..7b0776026 --- /dev/null +++ b/doc/testing/manual_tests/ManualINITTests.html @@ -0,0 +1,170 @@ + + + + Description of ManualINITTests + + + + + + + + + +
Home > testing > manual_tests > ManualINITTests.m
+ + + +

ManualINITTests +

+ +

PURPOSE ^

+
These tests are using the Human-GEM model.
+ +

SYNOPSIS ^

+
This is a script file.
+ +

DESCRIPTION ^

+
These tests are using the Human-GEM model.
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 %These tests are using the Human-GEM model.
+0002 
+0003 %%%%%%%%%%%%%%%%%%%%%%%%%%
+0004 % TC0901 - Test that all reactions in the minimal model to be
+0005 %          used by the MILP can carry flux > 0.1
+0006 %%%%%%%%%%%%%%%%%%%%%%%%%%
+0007 
+0008 %In the MILP, the flux of reactions with negative rxn scores cannot exceed 100
+0009 %At the same time, the flux of positive reactions need to be >= 0.1 to be able
+0010 %to turn them on. Likewise, we force the flux on essential reactions to be >= 0.1.
+0011 %Therefore, it is important that all reactions can get a flux > 0.1, while all
+0012 %reactions are limited to a flux <= 100. We can test this in a similar way to the
+0013 %haveFlux function in RAVEN, so that code is copied here and modified.
+0014 
+0015 %This code is partly copied from the function haveFlux
+0016 %The prepData takes a couple of hours to generate. If you have it somewhere,
+0017 %better to load it
+0018 %cd C:\Work\MatlabCode\components\human-GEM\Human-GEMftINIT\Human-GEM %replace this with the root of the Human-GEM repo.
+0019 %ihuman = importYaml('model/Human-GEM.yml');
+0020 %save('model/Human-GEM.mat', 'ihuman');
+0021 %load('model/Human-GEM.mat')
+0022 %prepData = prepHumanModelForftINIT(ihuman, false);
+0023 prepData2 = load('model/PrepData2.mat').prepData;
+0024 
+0025 upperLimit = 100;
+0026 lowerLimit = 0.1;
+0027 
+0028 model = prepData2.minModel;
+0029 model = prepData.minModel;
+0030 
+0031 
+0032 
+0033 
+0034 model.lb(model.lb==-inf)=-upperLimit;
+0035 model.ub(model.ub==inf)=upperLimit;
+0036 model.lb(model.lb==-1000)=-upperLimit;
+0037 model.ub(model.ub==1000)=upperLimit;
+0038 
+0039 %check
+0040 unique(model.lb) %ok, only 0 and -100
+0041 unique(model.ub) %ok, only 100
+0042 
+0043 %First make a loop where we optimize for all
+0044 onFwd = false(numel(model.rxns,1));
+0045 onRev = false(numel(model.rxns,1));
+0046 
+0047 iter = 1;
+0048 while true
+0049     disp([num2str(iter) ': ' num2str(sum(onFwd))])
+0050     model.c=ones(numel(model.c),1);
+0051     model.c(onFwd) = 0; %don't include the ones already verified
+0052     
+0053     sol=solveLP(model);
+0054     if isempty(sol.x)
+0055         disp('Failed');
+0056         break;
+0057     end
+0058     
+0059     currRes = sol.x > lowerLimit;
+0060     if sum(currRes & ~onFwd) == 0
+0061         break;%we didn't turn any more rxns on
+0062     end
+0063     
+0064     onFwd = onFwd | currRes;
+0065     iter = iter + 1;
+0066 end
+0067 
+0068 sum(~onFwd)%zero, perfect
+0069 
+0070 %Now the other direction (reversible):
+0071 onRev = false(numel(model.rxns,1));
+0072 
+0073 iter = 1;
+0074 while true
+0075     disp([num2str(iter) ': ' num2str(sum(onRev))])
+0076     model.c=-ones(numel(model.c),1);
+0077     model.c(~model.rev) = 0;
+0078     model.c(onRev) = 0; %don't include the ones already verified
+0079     
+0080     sol=solveLP(model);
+0081     if isempty(sol.x)
+0082         disp('Failed');
+0083         break;
+0084     end
+0085     
+0086     currRes = sol.x < -lowerLimit;
+0087     if sum(currRes & ~onRev) == 0
+0088         break;%we didn't turn any more rxns on
+0089     end
+0090     
+0091     onRev = onRev | currRes;
+0092     iter = iter + 1;
+0093 end
+0094 
+0095 sum(~onRev(model.rev == 1))%
+0096 
+0097 onRev = false(numel(model.rxns,1));
+0098 
+0099 indLeft = find(model.rev == 1 & ~onRev);
+0100 
+0101 constructEquations(model, model.rxns(indLeft))%no scaling here...
+0102 
+0103 %go trough the last one by one
+0104 for i = 1:numel(indLeft)
+0105     model.c=zeros(numel(model.c),1);
+0106     model.c(indLeft(i)) = -1;
+0107     
+0108     sol=solveLP(model);
+0109     if isempty(sol.x)
+0110         disp('Failed');
+0111         break;
+0112     end
+0113     
+0114     currRes = sol.x(indLeft(i)) < -lowerLimit;
+0115     disp([num2str(indLeft(i)) ': ' num2str(currRes)])
+0116     onRev(indLeft(i)) = currRes;
+0117     onRev = onRev | currRes;
+0118     iter = iter + 1;
+0119 end
+0120 
+0121 sum(~onRev(model.rev == 1))%0, perfect. This means that we can use the limits 0.1 and 100 in the MILP!
+0122 
+0123
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/testing/manual_tests/index.html b/doc/testing/manual_tests/index.html new file mode 100644 index 000000000..8e8945518 --- /dev/null +++ b/doc/testing/manual_tests/index.html @@ -0,0 +1,29 @@ + + + + Index for Directory testing\manual_tests + + + + + + + + + + +
< Master indexIndex for testing\manual_tests >
+ +

Index for testing\manual_tests

+ +

Matlab files in this directory:

+ +
 ManualINITTestsThese tests are using the Human-GEM model.
+ + + + +
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/testing/unit_tests/blastPlusTests.html b/doc/testing/unit_tests/blastPlusTests.html new file mode 100644 index 000000000..2b0ba05b1 --- /dev/null +++ b/doc/testing/unit_tests/blastPlusTests.html @@ -0,0 +1,108 @@ + + + + Description of blastPlusTests + + + + + + + + + +
Home > testing > unit_tests > blastPlusTests.m
+ + + +

blastPlusTests +

+ +

PURPOSE ^

+
run this test case with the command
+ +

SYNOPSIS ^

+
function tests = blastPlusTests
+ +

DESCRIPTION ^

+
run this test case with the command
+results = runtests('blastPlusTests.m')
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 %run this test case with the command
+0002 %results = runtests('blastPlusTests.m')
+0003 function tests = blastPlusTests
+0004 tests = functiontests(localfunctions);
+0005 end
+0006 
+0007 function testBlastPlus(testCase)
+0008 %This unit test comprises several functionality tests for BLAST+ in RAVEN:
+0009 % 1. MD5 checksum check for BLAST database files. This check is applied for
+0010 %    "phr", "pot", "psq" and "pto" files. The remaining files (i.e. "pdb",
+0011 %    "pin" and "ptf") are not compared as these seem to be
+0012 %    machine-specific.
+0013 % 2. Non-parsed text check for BLAST result files. Although the content of
+0014 %    the files is exactly the same, their MD5 hashes are somehow different
+0015 %    between the operating systems.
+0016 % 3. Check of resulting blastStructure against the expected one. This is
+0017 %    done to test BLAST results parsing in RAVEN.
+0018 
+0019 %%
+0020 %Get the directory for RAVEN Toolbox
+0021 [ST, I]=dbstack('-completenames');
+0022 ravenPath=fileparts(fileparts(fileparts(ST(I).file)));
+0023 
+0024 %Import structures that contain expected MD5 hashes and BLAST results
+0025 sourceDir = fileparts(which(mfilename));
+0026 load([sourceDir,'/test_data/expBlastResults.mat'],'expBlastStructure','expBlastReport');
+0027 
+0028 organismID='sce';
+0029 fastaFile=fullfile(ravenPath,'testing','unit_tests','test_data','yeast_galactosidases.fa');
+0030 modelIDs={'hsa' 'afv'};
+0031 refFastaFiles={fullfile(ravenPath,'testing','unit_tests','test_data','human_galactosidases.fa') fullfile(ravenPath,'testing','unit_tests','test_data','aflavus_galactosidases.fa')};
+0032 
+0033 %%
+0034 %Run BLAST
+0035 [actBlastStructure,actBlastReport]=getBlast(organismID,fastaFile,modelIDs,refFastaFiles,true,true);
+0036 
+0037 %%
+0038 %Test 1a: Check if MD5 checksums for BLAST database files are the same
+0039 verifyEqual(testCase,actBlastReport.dbHashes,expBlastReport.dbHashes);
+0040 
+0041 %Test 1b: Change one of the MD5 checksums and check if test fails
+0042 actBlastReport.dbHashes.phr{1,1}=actBlastReport.dbHashes.phr{1,2};
+0043 verifyNotEqual(testCase,actBlastReport.dbHashes,expBlastReport.dbHashes);
+0044 
+0045 %Test 2a: Check if BLAST result files are the same
+0046 verifyEqual(testCase,actBlastReport.blastTxtOutput,expBlastReport.blastTxtOutput);
+0047 
+0048 %Test 2b: Change actual BLAST result file and check if test fails
+0049 actBlastReport.blastTxtOutput='empty';
+0050 verifyNotEqual(testCase,actBlastReport.blastTxtOutput,expBlastReport.blastTxtOutput);
+0051 
+0052 %Test 3a: Check if BLAST structures are the same
+0053 verifyEqual(testCase,actBlastStructure,expBlastStructure);
+0054 
+0055 %Test 3b: Modify actual BLAST structure and check if test fails
+0056 actBlastStructure(1,1).toId=actBlastStructure(1,1).fromId;
+0057 verifyNotEqual(testCase,actBlastStructure,expBlastStructure);
+0058 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/testing/unit_tests/cdhitTests.html b/doc/testing/unit_tests/cdhitTests.html new file mode 100644 index 000000000..31c2880e9 --- /dev/null +++ b/doc/testing/unit_tests/cdhitTests.html @@ -0,0 +1,129 @@ + + + + Description of cdhitTests + + + + + + + + + +
Home > testing > unit_tests > cdhitTests.m
+ + + +

cdhitTests +

+ +

PURPOSE ^

+
run this test case with the command
+ +

SYNOPSIS ^

+
function tests = cdhitTests
+ +

DESCRIPTION ^

+
run this test case with the command
+results = runtests('cdhitTests.m')
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 %run this test case with the command
+0002 %results = runtests('cdhitTests.m')
+0003 function tests = cdhitTests
+0004 tests = functiontests(localfunctions);
+0005 end
+0006 
+0007 function testCdhit(testCase)
+0008 %This unit test comprises the functionality test for CD-HIT in RAVEN:
+0009 % 1. Check for resulting file against the expected one.
+0010 
+0011 %%
+0012 %Get the directory for RAVEN Toolbox
+0013 [ST, I]=dbstack('-completenames');
+0014 ravenPath=fileparts(fileparts(fileparts(ST(I).file)));
+0015 
+0016 %Identify the operating system
+0017 if isunix
+0018     if ismac
+0019         binEnd='.mac';
+0020     else
+0021         binEnd='';
+0022     end
+0023 elseif ispc
+0024     binEnd='.exe';
+0025 else
+0026     dispEM('Unknown OS, exiting.')
+0027     return
+0028 end
+0029 
+0030 %Import structure that contains expected MAFFT results
+0031 sourceDir = fileparts(which(mfilename));
+0032 load([sourceDir,'/test_data/expCdhitMafftOutput.mat'],'expCdhitMafftOutput');
+0033 
+0034 %Generate temporary names for working directory and outFile
+0035 tmpDIR=tempname;
+0036 outFile=tempname;
+0037 
+0038 %Run CD-HIT multi-threaded to use all logical cores assigned to MATLAB
+0039 cores = evalc('feature(''numcores'')');
+0040 cores = strsplit(cores, 'MATLAB was assigned: ');
+0041 cores = regexp(cores{2},'^\d*','match');
+0042 cores = cores{1};
+0043 
+0044 %Create a temporary folder and copy multi-FASTA file there
+0045 [~, ~]=system(['mkdir "' tmpDIR '"']);
+0046 
+0047 sourceDir = fileparts(which(mfilename));
+0048 copyfile(fullfile(sourceDir,'test_data','yeast_galactosidases.fa'),tmpDIR);
+0049 
+0050 %%
+0051 %Run protein clustering with CD-HIT
+0052 if ispc
+0053     % Define WSL paths
+0054     wslPath.fastaFile=getWSLpath([tmpDIR filesep 'yeast_galactosidases.fa']);
+0055     wslPath.outFile=getWSLpath(outFile);
+0056     wslPath.cdhit=getWSLpath(fullfile(ravenPath,'software','cd-hit','cd-hit'));
+0057     [~, ~]=system(['wsl "' wslPath.cdhit '" -T "' num2str(cores) '" -i "' wslPath.fastaFile '" -o "' wslPath.outFile '" -c 1.0 -n 5 -M 2000']);
+0058 else
+0059     [~, ~]=system(['"' fullfile(ravenPath,'software','cd-hit',['cd-hit' binEnd]) '" -T "' num2str(cores) '" -i "' fullfile(tmpDIR, 'yeast_galactosidases.fa') '" -o "' outFile '" -c 1.0 -n 5 -M 2000']);
+0060 end
+0061 
+0062 %%
+0063 %Open actual cdhit results file
+0064 actCdhitOutput=importdata(fullfile(outFile));
+0065 
+0066 %Remove the old tempfiles
+0067 delete([outFile '*']);
+0068 
+0069 %Remove temporary folder, since testing is finished
+0070 [~, ~]=system(['rm "' tmpDIR '" -r']);
+0071 
+0072 %%
+0073 %Check 1a: Check if files for CD-HIT results are the same
+0074 verifyEqual(testCase,actCdhitOutput,expCdhitMafftOutput);
+0075 
+0076 %Check 1b: Change actual CD-HIT results file and check if test fails
+0077 actCdhitOutput='abc';
+0078 verifyNotEqual(testCase,actCdhitOutput,expCdhitMafftOutput);
+0079 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/testing/unit_tests/checkTasksTests.html b/doc/testing/unit_tests/checkTasksTests.html new file mode 100644 index 000000000..2887066ce --- /dev/null +++ b/doc/testing/unit_tests/checkTasksTests.html @@ -0,0 +1,138 @@ + + + + Description of checkTasksTests + + + + + + + + + +
Home > testing > unit_tests > checkTasksTests.m
+ + + +

checkTasksTests +

+ +

PURPOSE ^

+
run this test case with the command
+ +

SYNOPSIS ^

+
function tests = checkTasksTests
+ +

DESCRIPTION ^

+
run this test case with the command
+results = runtests('checkTasksTests.m')
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 %run this test case with the command
+0002 %results = runtests('checkTasksTests.m')
+0003 function tests = checkTasksTests
+0004     tests = functiontests(localfunctions);
+0005 end
+0006 
+0007 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+0008 % testModel
+0009 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+0010 
+0011 function testModel = getTaskTstModel()
+0012     testModel = struct();
+0013     testModel.id = 'testModel';
+0014     testModel.rxns = {};
+0015     testModel.S=[];
+0016     testModel.rev=[];
+0017     testModel.mets = {'as';'ac';'bc';'cc';'dc';'ec';'es';'fc'};
+0018     testModel.metNames = {'a';'a';'b';'c';'d';'e';'e';'f'};
+0019     testModel.comps = {'s';'c'};
+0020     testModel.compNames = testModel.comps;
+0021     testModel.metComps = [1;2;2;2;2;2;1;2];
+0022     testModel.genes = {'G1';'G2';'G3';'G4';'G5';'G6';'G7';'G8';'G9';'G10'};
+0023     testModel.grRules = {};
+0024     testModel.rxnGeneMat = [];
+0025 
+0026     rxnsToAdd = struct();
+0027     rxnsToAdd.rxns = {'R1';'R2';'R3';'R4';'R5';'R6';'R7';'R8';'R9';'R10'};
+0028     rxnsToAdd.equations = {'=> a[s]';...
+0029                            'a[s] <=> a[c]';...
+0030                            'a[c] <=> b[c] + c[c]';...
+0031                            'a[c] <=> 2 d[c]';...
+0032                            'b[c] + c[c] => e[c]';...
+0033                            '2 d[c] => e[c]';...
+0034                            'e[c] => e[s]';...
+0035                            'e[s] =>';...
+0036                            'a[c] <=> f[c]';...
+0037                            'f[c] <=> e[c]'};
+0038     rxnsToAdd.grRules = {'';'';'G3';'G4';'G5';'G6';'G7';'';'G9';'G10'};
+0039     testModel = addRxns(testModel,rxnsToAdd, 3);
+0040     testModel.c = [0;0;0;0;0;0;0;1;0;0];%optimize for output flux, if this is used, not sure
+0041     testModel.ub = repmat(1000,10,1);
+0042     testModel.lb = [0;-1000;-1000;-1000;0;0;0;0;-1000;-1000];
+0043     testModel.rxnNames = testModel.rxns;
+0044     testModel.b = repmat(0,8,1);
+0045 end
+0046 
+0047 function testModelTasks = getTaskTstModelTasks()
+0048     testModelTasks = struct();
+0049     testModelTasks.id = 'Gen e[s] from a[s]';
+0050     testModelTasks.description = 'Gen e[s] from a[s]';
+0051     testModelTasks.shouldFail = false;
+0052     testModelTasks.printFluxes = false;
+0053     testModelTasks.comments = '';
+0054     testModelTasks.inputs = {'a[s]'};
+0055     testModelTasks.LBin = 0;
+0056     testModelTasks.UBin = inf;
+0057     testModelTasks.outputs = {'e[s]'};
+0058     testModelTasks.LBout = 1;
+0059     testModelTasks.UBout = 1;
+0060     testModelTasks.equations = {};
+0061     testModelTasks.LBequ = [];
+0062     testModelTasks.UBequ = [];
+0063     testModelTasks.changed = {};
+0064     testModelTasks.LBrxn = {};
+0065     testModelTasks.UBrxn = {};
+0066 end
+0067 
+0068 
+0069 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+0070 %TXXXX: checkTasks
+0071 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+0072 function testcheckTasks(testCase)
+0073 
+0074     testModel = getTaskTstModel();
+0075     testModel = closeModel(testModel);
+0076     testModelTasks = getTaskTstModelTasks();
+0077     
+0078     %the task should work with the full model
+0079     [~,taskReport] = evalc("checkTasks(testModel,[],true,false,false,testModelTasks);");
+0080     verifyTrue(testCase, taskReport.ok == 1)
+0081     
+0082     %now remove R2, then it should fail
+0083     testModel2 = removeReactions(testModel, {'R2'});
+0084     [~, taskReport2] = evalc("checkTasks(testModel2,[],true,false,false,testModelTasks);");
+0085     verifyTrue(testCase, taskReport2.ok == 0)
+0086 end
+0087 
+0088
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/testing/unit_tests/diamondTests.html b/doc/testing/unit_tests/diamondTests.html new file mode 100644 index 000000000..5af96de46 --- /dev/null +++ b/doc/testing/unit_tests/diamondTests.html @@ -0,0 +1,107 @@ + + + + Description of diamondTests + + + + + + + + + +
Home > testing > unit_tests > diamondTests.m
+ + + +

diamondTests +

+ +

PURPOSE ^

+
run this test case with the command
+ +

SYNOPSIS ^

+
function tests = diamondTests
+ +

DESCRIPTION ^

+
run this test case with the command
+results = runtests('diamondTests.m')
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 %run this test case with the command
+0002 %results = runtests('diamondTests.m')
+0003 function tests = diamondTests
+0004 tests = functiontests(localfunctions);
+0005 end
+0006 
+0007 function testDiamond(testCase)
+0008 %This unit test comprises several functionality tests for DIAMOND blastp in
+0009 %RAVEN:
+0010 % 1. MD5 checksum check for DIAMOND database files.
+0011 % 2. Non-parsed text check for DIAMOND result files. Although the content
+0012 %    of the files is exactly the same, their MD5 hashes are somehow
+0013 %    different between the operating systems.
+0014 % 3. Check of resulting blastStructure against the expected one. This is
+0015 %    done to test DIAMOND blastp results parsing in RAVEN.
+0016 
+0017 %%
+0018 %Get the directory for RAVEN Toolbox
+0019 [ST, I]=dbstack('-completenames');
+0020 ravenPath=fileparts(fileparts(fileparts(ST(I).file)));
+0021 
+0022 %Import structures that contain expected MD5 hashes and DIAMOND blastp
+0023 %results
+0024 sourceDir = fileparts(which(mfilename));
+0025 load([sourceDir,'/test_data/expDiamondResults.mat'],'expBlastStructure','expDiamondReport');
+0026 
+0027 organismID='sce';
+0028 fastaFile=fullfile(ravenPath,'testing','unit_tests','test_data','yeast_galactosidases.fa');
+0029 modelIDs={'hsa' 'afv'};
+0030 refFastaFiles={fullfile(ravenPath,'testing','unit_tests','test_data','human_galactosidases.fa') fullfile(ravenPath,'testing','unit_tests','test_data','aflavus_galactosidases.fa')};
+0031 
+0032 %%
+0033 %Run DIAMOND blastp
+0034 [actBlastStructure,actDiamondReport]=getDiamond(organismID,fastaFile,modelIDs,refFastaFiles,true,true);
+0035 
+0036 %%
+0037 %Test 1a: Check if MD5 checksums for DIAMOND blastp database files are the same
+0038 verifyEqual(testCase,actDiamondReport.dbHashes,expDiamondReport.dbHashes);
+0039 
+0040 %Test 1b: Change one of the MD5 checksums and check if test fails
+0041 actDiamondReport.dbHashes{1,1}=actDiamondReport.dbHashes{1,2};
+0042 verifyNotEqual(testCase,actDiamondReport.dbHashes,expDiamondReport.dbHashes);
+0043 
+0044 %Test 2a: Check if DIAMOND blastp result files are the same
+0045 verifyEqual(testCase,actDiamondReport.diamondTxtOutput,expDiamondReport.diamondTxtOutput);
+0046 
+0047 %Test 2b: Change actual DIAMOND blastp result file and check if test fails
+0048 actDiamondReport.diamondTxtOutput='empty';
+0049 verifyNotEqual(testCase,actDiamondReport.diamondTxtOutput,expDiamondReport.diamondTxtOutput);
+0050 
+0051 %Test 3a: Check if DIAMOND blastp structures are the same
+0052 verifyEqual(testCase,actBlastStructure,expBlastStructure);
+0053 
+0054 %Test 3b: Modify actual DIAMOND blastp structure and check if test fails
+0055 actBlastStructure(1,1).toId=actBlastStructure(1,1).fromId;
+0056 verifyNotEqual(testCase,actBlastStructure,expBlastStructure);
+0057 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/testing/unit_tests/fillGapsLargeTests.html b/doc/testing/unit_tests/fillGapsLargeTests.html new file mode 100644 index 000000000..9b44640b5 --- /dev/null +++ b/doc/testing/unit_tests/fillGapsLargeTests.html @@ -0,0 +1,146 @@ + + + + Description of fillGapsLargeTests + + + + + + + + + +
Home > testing > unit_tests > fillGapsLargeTests.m
+ + + +

fillGapsLargeTests +

+ +

PURPOSE ^

+
run this test case with the command
+ +

SYNOPSIS ^

+
function tests = fillGapsLargeTests
+ +

DESCRIPTION ^

+
run this test case with the command
+results = runtests('fillGapsLargeTests.m')
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 %run this test case with the command
+0002 %results = runtests('fillGapsLargeTests.m')
+0003 function tests = fillGapsLargeTests
+0004 tests = functiontests(localfunctions);
+0005 testGurobi = exist('gurobi','file')==3;
+0006 if testGurobi
+0007     try
+0008         gurobi_read('solverTests.m');
+0009     catch ME
+0010         if ~startsWith(ME.message,{'Gurobi error 10012','Gurobi error 10003'}) % Expected error codes, others may indicate problems with license
+0011            testGurobi = false;
+0012         end
+0013     end
+0014 end
+0015 if ~testGurobi
+0016     disp('Gurobi not installed or not functional, some fillGapsLargeTests skipped.')
+0017     skipTests = contains({tests.Name},'gurobi','IgnoreCase',true);
+0018     tests(skipTests) = [];
+0019 end
+0020 if exist('scip','file')~=3
+0021     disp('SCIP MEX binary not installed or not functional, some fillGapsLargeTests skipped.')
+0022     skipTests = contains({tests.Name},'scip','IgnoreCase',true);
+0023     tests(skipTests) = [];
+0024 end
+0025 end
+0026 
+0027 function testLargeGurobi(testCase)
+0028 sourceDir = fileparts(fileparts(fileparts(which(mfilename))));
+0029 evalc('model=importModel(fullfile(sourceDir,''tutorial'',''iAL1006 v1.00.xml''))');
+0030 model.c(1484)=1;
+0031 modelDB=model; % Keep as database with reactions
+0032 try
+0033     oldSolver=getpref('RAVEN','solver');
+0034 catch
+0035 end
+0036 setRavenSolver('gurobi');
+0037 
+0038 %Remove first 10 reactions
+0039 model=removeReactions(modelDB,(1:10));
+0040 modelDB.id='DB';
+0041 try
+0042     evalc('[newConnected,cannotConnect,addedRxns,model,exitFlag]=fillGaps(model,modelDB,false,false)');
+0043 catch
+0044     try
+0045         setRavenSolver(oldSolver);
+0046     catch
+0047         rmpref('RAVEN','solver');
+0048     end
+0049     error('Solver not working')
+0050 end
+0051 sol=solveLP(model);
+0052 try
+0053     setRavenSolver(oldSolver);
+0054 catch
+0055     rmpref('RAVEN','solver');
+0056 end
+0057 %Expect at least 5% of the original growth
+0058 verifyTrue(testCase,sol.f>0);
+0059 end
+0060 
+0061 function testLargeSCIP(testCase)
+0062 sourceDir = fileparts(fileparts(fileparts(which(mfilename))));
+0063 evalc('model=importModel(fullfile(sourceDir,''tutorial'',''iAL1006 v1.00.xml''))');
+0064 model.c(1484)=1;
+0065 modelDB=model; % Keep as database with reactions
+0066 % Force growth in gapped model
+0067 sol=solveLP(model);
+0068 model.lb(1484)=sol.f*0.1;
+0069 try
+0070     oldSolver=getpref('RAVEN','solver');
+0071 catch
+0072 end
+0073 setRavenSolver('scip');
+0074 
+0075 %Remove first 10 reactions
+0076 model=removeReactions(model,(1:10));
+0077 modelDB.id='DB';
+0078 try
+0079     evalc('[newConnected,cannotConnect,addedRxns,model,exitFlag]=fillGaps(model,modelDB,false,true)');
+0080 catch
+0081     try
+0082         setRavenSolver(oldSolver);
+0083     catch
+0084         rmpref('RAVEN','solver');
+0085     end
+0086     error('Solver not working')
+0087 end
+0088 sol=solveLP(model);
+0089 try
+0090     setRavenSolver(oldSolver);
+0091 catch
+0092     rmpref('RAVEN','solver');
+0093 end
+0094 %Expect at least 5% of the original growth
+0095 verifyTrue(testCase,sol.f>0);
+0096 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/testing/unit_tests/fillGapsSmallTests.html b/doc/testing/unit_tests/fillGapsSmallTests.html new file mode 100644 index 000000000..3e5fa374c --- /dev/null +++ b/doc/testing/unit_tests/fillGapsSmallTests.html @@ -0,0 +1,144 @@ + + + + Description of fillGapsSmallTests + + + + + + + + + +
Home > testing > unit_tests > fillGapsSmallTests.m
+ + + +

fillGapsSmallTests +

+ +

PURPOSE ^

+
run this test case with the command
+ +

SYNOPSIS ^

+
function tests = fillGapsSmallTests
+ +

DESCRIPTION ^

+
run this test case with the command
+results = runtests('fillGapsSmallTests.m')
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 %run this test case with the command
+0002 %results = runtests('fillGapsSmallTests.m')
+0003 function tests = fillGapsSmallTests
+0004 tests = functiontests(localfunctions);
+0005 testGurobi = exist('gurobi','file')==3;
+0006 if testGurobi
+0007     try
+0008         gurobi_read('solverTests.m');
+0009     catch ME
+0010         if ~startsWith(ME.message,'Gurobi error 10012') % Expected error code, others may indicate problems with license
+0011            testGurobi = false;
+0012         end
+0013     end
+0014 end
+0015 if ~testGurobi
+0016     disp('Gurobi not installed or not functional, some fillGapsSmallTests skipped.')
+0017     skipTests = contains({tests.Name},'gurobi','IgnoreCase',true);
+0018     tests(skipTests) = [];
+0019 end
+0020 if exist('scip','file')~=3
+0021     disp('SCIP MEX binary not installed or not functional, some fillGapsSmallTests skipped.')
+0022     skipTests = contains({tests.Name},'scip','IgnoreCase',true);
+0023     tests(skipTests) = [];
+0024 end
+0025 end
+0026 
+0027 function testSmallSCIP(testCase)
+0028 %Test using small model
+0029 sourceDir = fileparts(which(mfilename));
+0030 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
+0031 modelDB=model; % Keep as database with reactions
+0032 try
+0033     oldSolver=getpref('RAVEN','solver');
+0034 catch
+0035 end
+0036 setRavenSolver('scip');
+0037 
+0038 %Remove first 10 reactions
+0039 model=removeReactions(modelDB,(1:10));
+0040 modelDB.id='DB';
+0041 try
+0042     evalc('[newConnected,cannotConnect,addedRxns,model,exitFlag]=fillGaps(model,modelDB)');
+0043 catch
+0044     try
+0045         setRavenSolver(oldSolver);
+0046     catch
+0047         rmpref('RAVEN','solver');
+0048     end
+0049     error('Solver not working')
+0050 end
+0051 sol=solveLP(model);
+0052 try
+0053     setRavenSolver(oldSolver);
+0054 catch
+0055     rmpref('RAVEN','solver');
+0056 end
+0057 %Should give non-zero flux
+0058 verifyTrue(testCase,sol.f>0);
+0059 end
+0060 
+0061 function testSmallGurobi(testCase)
+0062 %Test using small model
+0063 sourceDir = fileparts(which(mfilename));
+0064 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
+0065 modelDB=model; % Keep as database with reactions
+0066 try
+0067     oldSolver=getpref('RAVEN','solver');
+0068 catch
+0069 end
+0070 setRavenSolver('gurobi');
+0071 
+0072 %Remove first 10 reactions
+0073 model=removeReactions(modelDB,(1:10));
+0074 
+0075 modelDB.id='DB';
+0076 try
+0077     evalc('[newConnected,cannotConnect,addedRxns,model,exitFlag]=fillGaps(model,modelDB)');
+0078 catch
+0079     try
+0080         setRavenSolver(oldSolver);
+0081     catch
+0082         rmpref('RAVEN','solver');
+0083     end
+0084     error('Solver not working')
+0085 end
+0086 sol=solveLP(model);
+0087 try
+0088     setRavenSolver(oldSolver);
+0089 catch
+0090     rmpref('RAVEN','solver');
+0091 end
+0092 %Expect at least 5% of the original growth
+0093 verifyTrue(testCase,sol.f>0);
+0094 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/testing/unit_tests/hmmerTests.html b/doc/testing/unit_tests/hmmerTests.html new file mode 100644 index 000000000..121a6d331 --- /dev/null +++ b/doc/testing/unit_tests/hmmerTests.html @@ -0,0 +1,203 @@ + + + + Description of hmmerTests + + + + + + + + + +
Home > testing > unit_tests > hmmerTests.m
+ + + +

hmmerTests +

+ +

PURPOSE ^

+
run this test case with the command
+ +

SYNOPSIS ^

+
function tests = hmmerTests
+ +

DESCRIPTION ^

+
run this test case with the command
+results = runtests('hmmerTests.m')
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 %run this test case with the command
+0002 %results = runtests('hmmerTests.m')
+0003 function tests = hmmerTests
+0004 tests = functiontests(localfunctions);
+0005 end
+0006 
+0007 function testHmmer(testCase)
+0008 %This unit test comprises the functionality test for HMMER in RAVEN:
+0009 % 1. Check of parsed HMMER results against the expected.
+0010 %
+0011 % NOTE: as hmm and HMMER results files are time-specific, no checks for
+0012 % these files existence are done. Also, due to the way HMMER is utilized in
+0013 % getKEGGModelForOrganism (HMMER result files can be parsed only once all
+0014 % required hmm files are generated), the code segment involving HMMER
+0015 % results parsing is pasted in this test function. Should the parsing problems
+0016 % occur in the results processing, the code modifications shall be done in
+0017 % this function and getKEGGModelForOrganism respectively.
+0018 
+0019 %%
+0020 %Get the directory for RAVEN Toolbox
+0021 [ST, I]=dbstack('-completenames');
+0022 ravenPath=fileparts(fileparts(fileparts(ST(I).file)));
+0023 
+0024 %Generate temporary names for working directory and outFile
+0025 tmpDIR=tempname;
+0026 outFile=tempname;
+0027 
+0028 %Create a temporary folder and copy multi-FASTA file there
+0029 [~, ~]=system(['mkdir "' tmpDIR '"']);
+0030 
+0031 sourceDir = fileparts(which(mfilename));
+0032 copyfile(fullfile(sourceDir,'test_data','yeast_galactosidases.fa'),tmpDIR);
+0033 copyfile(fullfile(sourceDir,'test_data','human_galactosidases.fa'),tmpDIR);
+0034 
+0035 
+0036 %Identify the operating system
+0037 if isunix
+0038     if ismac
+0039         binEnd='.mac';
+0040     else
+0041         binEnd='';
+0042     end
+0043 elseif ispc
+0044     wslPath.tmpDIR    = getWSLpath(tmpDIR);
+0045     wslPath.hmmbuild  = getWSLpath(fullfile(ravenPath,'software','hmmer','hmmbuild'));
+0046     wslPath.hmmsearch = getWSLpath(fullfile(ravenPath,'software','hmmer','hmmsearch'));
+0047     filesep='/';
+0048 else
+0049     dispEM('Unknown OS, exiting.')
+0050     return
+0051 end
+0052 
+0053 %Create empty structures needed for HMMER results
+0054 actHmmResult.genes = {};
+0055 actHmmResult.scores = [];
+0056 
+0057 %Create structures that contain expected HMMER results
+0058 expHmmResult.genes = {'sp|P41947|MEL6_YEASX','sp|P41946|MEL5_YEASX', 'sp|P41945|MEL2_YEASX', 'sp|P04824|MEL1_YEASX'};
+0059 expHmmResult.scores = [10^-250, 10^-250, 10^-250, 10^-250];
+0060 
+0061 %Run HMMER multi-threaded to use all logical cores assigned to MATLAB
+0062 cores = evalc('feature(''numcores'')');
+0063 cores = strsplit(cores, 'MATLAB was assigned: ');
+0064 cores = regexp(cores{2},'^\d*','match');
+0065 cores = cores{1};
+0066 
+0067 %%
+0068 %Train a hidden Markov model
+0069 if ismac || isunix
+0070     [~, ~]=system(['"' fullfile(ravenPath,'software','hmmer',['hmmbuild' binEnd]) '" --cpu "' num2str(cores) '" "' fullfile(tmpDIR,'human_galactosidases.hmm') '" "' fullfile(tmpDIR,'yeast_galactosidases.fa') '"']);
+0071 else
+0072     [~, ~]=system(['wsl "' wslPath.hmmbuild '" --cpu "' num2str(cores) '" "' wslPath.tmpDIR '/human_galactosidases.hmm" "' wslPath.tmpDIR '/yeast_galactosidases.fa"']);
+0073 end
+0074 
+0075 %Run a homology search against the newly-trained HMM
+0076 if ismac || isunix
+0077     [~, output]=system(['"' fullfile(ravenPath,'software','hmmer',['hmmsearch' binEnd]) '" --cpu "' num2str(cores) '" "' fullfile(tmpDIR,'human_galactosidases.hmm') '" "' fullfile(tmpDIR,'yeast_galactosidases.fa') '"']);
+0078 else
+0079     [~, output]=system(['wsl "' wslPath.hmmsearch '" --cpu "' num2str(cores) '" "' wslPath.tmpDIR '/human_galactosidases.hmm" "' wslPath.tmpDIR '/yeast_galactosidases.fa"']);
+0080 end
+0081 
+0082 %Save the output to a file
+0083 fid=fopen(outFile,'w');
+0084 fwrite(fid,output);
+0085 fclose(fid);
+0086 
+0087 %%
+0088 %Parse the results
+0089 geneCounter=0;
+0090 fid=fopen(outFile,'r');
+0091 beginMatches=false;
+0092 while 1
+0093     %Get the next line
+0094     tline = fgetl(fid);
+0095     
+0096     %Abort at end of file
+0097     if ~ischar(tline)
+0098         break;
+0099     end
+0100     
+0101     if and(beginMatches,strcmp(tline,'  ------ inclusion threshold ------'))
+0102         break;
+0103     end
+0104     
+0105     if beginMatches==false
+0106         %This is how the listing of matches begins
+0107         if any(strfind(tline,'E-value '))
+0108             %Read one more line that is only padding
+0109             tline = fgetl(fid);
+0110             beginMatches=true;
+0111         end
+0112     else
+0113         %If matches should be read
+0114         if ~strcmp(tline,'   [No hits detected that satisfy reporting thresholds]') && ~isempty(tline)
+0115             elements=regexp(tline,' ','split');
+0116             elements=elements(cellfun(@any,elements));
+0117             
+0118             %Check if the match is below the treshhold
+0119             score=str2double(elements{1});
+0120             gene=elements{9};
+0121             if score<=10^-50
+0122                 %If the score is exactly 0, change it to a very
+0123                 %small value to avoid NaN
+0124                 if score==0
+0125                     score=10^-250;
+0126                 end
+0127                 %Check if the gene is added already and, is so, get
+0128                 %the best score for it
+0129                 geneCounter=geneCounter+1;
+0130                 actHmmResult.genes{geneCounter}=gene;
+0131                 actHmmResult.scores(geneCounter)=score;
+0132             end
+0133         else
+0134             break;
+0135         end
+0136     end
+0137 end
+0138 fclose(fid);
+0139 
+0140 %Remove the old tempfiles
+0141 delete([outFile '*']);
+0142 
+0143 %Remove temporary folder, since testing is finished
+0144 [~, ~]=system(['rm "' tmpDIR '" -r']);
+0145 
+0146 %%
+0147 %Test 1a: Check if HMMER results match the expected ones
+0148 verifyEqual(testCase,actHmmResult,expHmmResult);
+0149 
+0150 %Test 1b: Modify actual HMMER results structure and check if test fails
+0151 actHmmResult.score(2)=1;
+0152 verifyNotEqual(testCase,actHmmResult,expHmmResult);
+0153 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/testing/unit_tests/importExportTests.html b/doc/testing/unit_tests/importExportTests.html new file mode 100644 index 000000000..00201adb1 --- /dev/null +++ b/doc/testing/unit_tests/importExportTests.html @@ -0,0 +1,153 @@ + + + + Description of importExportTests + + + + + + + + + +
Home > testing > unit_tests > importExportTests.m
+ + + +

importExportTests +

+ +

PURPOSE ^

+
run this test case with the command
+ +

SYNOPSIS ^

+
function tests = importExportTests
+ +

DESCRIPTION ^

+
run this test case with the command
+results = runtests('importExportTests.m')
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 %run this test case with the command
+0002 %results = runtests('importExportTests.m')
+0003 function tests = importExportTests
+0004 tests = functiontests(localfunctions);
+0005 end
+0006 
+0007 function testExcelImport(testCase)
+0008 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
+0009 excelFile=fullfile(sourceDir,'tutorial','empty.xlsx');
+0010 %%Prepare test results, uncomment and run when new reference is needed
+0011 % modelExcel=importExcelModel(excelFile);
+0012 % sbmlFile=fullfile(sourceDir,'tutorial','empty.xml');
+0013 % modelSBML=importModel(sbmlFile);
+0014 % save(fullfile(sourceDir,'testing','unit_tests','test_data','importExportResults.mat'),'modelExcel','modelSBML');
+0015 evalc('model=importExcelModel(excelFile)'); % Repress warnings
+0016 load(fullfile(sourceDir,'testing','unit_tests','test_data','importExportResults.mat'), 'modelExcel');
+0017 verifyEqual(testCase,model,modelExcel)
+0018 end
+0019 
+0020 function testSBMLImport(testCase)
+0021 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
+0022 sbmlFile=fullfile(sourceDir,'tutorial','empty.xml');
+0023 evalc('model=importModel(sbmlFile)'); % Repress warnings
+0024 load(fullfile(sourceDir,'testing','unit_tests','test_data','importExportResults.mat'), 'modelSBML');
+0025 verifyEqual(testCase,model,modelSBML)
+0026 end
+0027 
+0028 function testYAMLimport(testCase)
+0029 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
+0030 yamlFile=fullfile(sourceDir,'tutorial','empty.yml');
+0031 evalc('model=readYAMLmodel(yamlFile)'); % Repress warnings
+0032 load(fullfile(sourceDir,'testing','unit_tests','test_data','importExportResults.mat'), 'modelYAML');
+0033 verifyEqual(testCase,model,modelYAML)
+0034 end
+0035 
+0036 function testExcelExport(testCase)
+0037 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
+0038 load(fullfile(sourceDir,'testing','unit_tests','test_data','ecoli_textbook.mat'), 'model');
+0039 evalc('exportToExcelFormat(model,fullfile(sourceDir,''testing'',''unit_tests'',''test_data'',''_test.xlsx''))');
+0040 %File will not be exactly equal as it contains the current date and time,
+0041 %so md5 or similar would not work. Just check whether file is reasonably
+0042 %sized.
+0043 s = dir(fullfile(sourceDir,'testing','unit_tests','test_data','_test.xlsx'));         
+0044 filesize = s.bytes;
+0045 verifyTrue(testCase,filesize>17000);
+0046 delete(fullfile(sourceDir,'testing','unit_tests','test_data','_test.xlsx'));
+0047 end
+0048 
+0049 function testSBMLExport(testCase)
+0050 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
+0051 load(fullfile(sourceDir,'testing','unit_tests','test_data','ecoli_textbook.mat'), 'model');
+0052 evalc('exportModel(model,fullfile(sourceDir,''testing'',''unit_tests'',''test_data'',''_test.xml''))');
+0053 %File will not be exactly equal as it contains the current date and time,
+0054 %so md5 or similar would not work. Just check whether file is reasonably
+0055 %sized.
+0056 s = dir(fullfile(sourceDir,'testing','unit_tests','test_data','_test.xml'));         
+0057 filesize = s.bytes;
+0058 verifyTrue(testCase,filesize>18500);
+0059 delete(fullfile(sourceDir,'testing','unit_tests','test_data','_test.xml'));
+0060 end
+0061 
+0062 function testSBMLExportNestedSubSystems(testCase)
+0063 %Regression test: a model where reactions have differing numbers of
+0064 %subsystems (nested cell-of-cells, e.g. one reaction in two subsystems and
+0065 %others in one) must be exportable to SBML. Previously exportModel failed
+0066 %with "Dimensions of arrays being concatenated are not consistent" because
+0067 %the subSystems flattening could not concatenate entries of unequal length.
+0068 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
+0069 load(fullfile(sourceDir,'testing','unit_tests','test_data','ecoli_textbook.mat'), 'model');
+0070 
+0071 %Assign nested subSystems: most reactions get a single subsystem, but a few
+0072 %get multiple, which is the scenario that triggered the bug.
+0073 nRxns=numel(model.rxns);
+0074 model.subSystems=repmat({{'Subsystem A'}},nRxns,1);
+0075 model.subSystems{1}={'Subsystem A','Subsystem B'};
+0076 model.subSystems{2}={'Subsystem B','Subsystem C'};
+0077 
+0078 tmpFile=fullfile(sourceDir,'testing','unit_tests','test_data','_testNested.xml');
+0079 %This call previously errored; verify it completes and round-trips.
+0080 evalc('exportModel(model,tmpFile)');
+0081 evalc('modelImported=importModel(tmpFile)');
+0082 delete(tmpFile);
+0083 
+0084 %Subsystems should be preserved (order within a reaction is not guaranteed)
+0085 srt=@(c) sort(reshape(c,1,[]));
+0086 for i=1:3
+0087     j=find(strcmp(modelImported.rxns,model.rxns{i}));
+0088     verifyEqual(testCase,srt(modelImported.subSystems{j}),srt(model.subSystems{i}));
+0089 end
+0090 end
+0091 
+0092 function testYAMLexport(testCase)
+0093 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
+0094 load(fullfile(sourceDir,'tutorial','empty.mat'), 'emptyModel');
+0095 evalc('writeYAMLmodel(emptyModel,fullfile(sourceDir,''testing'',''unit_tests'',''test_data'',''_test.yml''))');
+0096 %File will not be exactly equal as it contains the current date and time,
+0097 %so md5 or similar would not work. Just check whether file is reasonably
+0098 %sized.
+0099 s = dir(fullfile(sourceDir,'testing','unit_tests','test_data','_test.yml'));         
+0100 filesize = s.bytes;
+0101 verifyTrue(testCase,filesize>1290);
+0102 delete(fullfile(sourceDir,'testing','unit_tests','test_data','_test.yml'));
+0103 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/testing/unit_tests/index.html b/doc/testing/unit_tests/index.html new file mode 100644 index 000000000..d476f4516 --- /dev/null +++ b/doc/testing/unit_tests/index.html @@ -0,0 +1,31 @@ + + + + Index for Directory testing\unit_tests + + + + + + + + + + +
< Master indexIndex for testing\unit_tests >
+ +

Index for testing\unit_tests

+ +

Matlab files in this directory:

+ +
 blastPlusTestsrun this test case with the command
 cdhitTestsrun this test case with the command
 checkTasksTestsrun this test case with the command
 diamondTestsrun this test case with the command
 fillGapsLargeTestsrun this test case with the command
 fillGapsSmallTestsrun this test case with the command
 hmmerTestsrun this test case with the command
 importExportTestsrun this test case with the command
 mafftTestsrun this test case with the command
 mergeModelsTestsrun this test case with the command
 miriamTestsrun this test case with the command
 modelAbilitiesTestsrun this test case with the command
 modelConversionTestsrun this test case with the command
 modelCurationTestsrun this test case with the command
 modelSortingTestsrun this test case with the command
 solverTestsrun this test case with the command
 tinitTestsrun this test case with the command
+ + +

Subsequent directories:

+
    +
  • tINITtestInfo
  • test_data
+ +
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/testing/unit_tests/mafftTests.html b/doc/testing/unit_tests/mafftTests.html new file mode 100644 index 000000000..96a9f1fc2 --- /dev/null +++ b/doc/testing/unit_tests/mafftTests.html @@ -0,0 +1,117 @@ + + + + Description of mafftTests + + + + + + + + + +
Home > testing > unit_tests > mafftTests.m
+ + + +

mafftTests +

+ +

PURPOSE ^

+
run this test case with the command
+ +

SYNOPSIS ^

+
function tests = mafftTests
+ +

DESCRIPTION ^

+
run this test case with the command
+results = runtests('mafftTests.m')
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 %run this test case with the command
+0002 %results = runtests('mafftTests.m')
+0003 function tests = mafftTests
+0004 tests = functiontests(localfunctions);
+0005 end
+0006 
+0007 function testMafft(testCase)
+0008 %This unit test comprises the functionality test for MAFFT in RAVEN:
+0009 % 1. Check for resulting file against the expected one.
+0010 
+0011 %%
+0012 %Get the directory for RAVEN Toolbox
+0013 [ST, I]=dbstack('-completenames');
+0014 ravenPath=fileparts(fileparts(fileparts(ST(I).file)));
+0015 
+0016 %Import structure that contains expected MAFFT results
+0017 sourceDir = fileparts(which(mfilename));
+0018 load([sourceDir,'/test_data/expCdhitMafftOutput.mat'],'expCdhitMafftOutput');
+0019 
+0020 %Generate temporary names for working directory and outFile
+0021 tmpDIR=tempname;
+0022 outFile=tempname;
+0023 
+0024 %Run MAFFT multi-threaded to use all logical cores assigned to MATLAB
+0025 cores = evalc('feature(''numcores'')');
+0026 cores = strsplit(cores, 'MATLAB was assigned: ');
+0027 cores = regexp(cores{2},'^\d*','match');
+0028 cores = cores{1};
+0029 
+0030 %Create a temporary folder and copy multi-FASTA file there
+0031 [~, ~]=system(['mkdir "' tmpDIR '"']);
+0032 
+0033 sourceDir = fileparts(which(mfilename));
+0034 copyfile(fullfile(sourceDir,'test_data','yeast_galactosidases.fa'),tmpDIR);
+0035 
+0036 %%
+0037 %Run protein multi-sequence alignment with MAFFT
+0038 if ismac
+0039     [~, ~]=system(['"' fullfile(ravenPath,'software','mafft','mafft-mac','mafft.bat') '" --auto --anysymbol --thread "' num2str(cores) '" "' fullfile(tmpDIR, 'yeast_galactosidases.fa') '" > "' outFile '"']);
+0040 elseif isunix
+0041     [~, ~]=system(['"' fullfile(ravenPath,'software','mafft','mafft-linux64','mafft.bat') '" --auto --anysymbol --thread "' num2str(cores) '" "' fullfile(tmpDIR, 'yeast_galactosidases.fa') '" > "' outFile '"']);
+0042 elseif ispc
+0043     % Define WSL paths
+0044     wslPath.fastaFile=getWSLpath([tmpDIR filesep 'yeast_galactosidases.fa']);
+0045     wslPath.outFile=getWSLpath(outFile);
+0046     wslPath.mafft=getWSLpath(fullfile(ravenPath,'software','mafft','mafft-linux64','mafft.bat'));
+0047     [~, ~]=system(['wsl "' wslPath.mafft '" --auto --anysymbol --quiet --thread "' num2str(cores) '" --out "' wslPath.outFile '" "' wslPath.fastaFile '"']);
+0048 end
+0049 
+0050 %%
+0051 %Open actual MAFFT results file
+0052 actMafftOutput=importdata(fullfile(outFile));
+0053 
+0054 %Remove the old tempfiles
+0055 delete([outFile '*']);
+0056 
+0057 %Remove temporary folder, since testing is finished
+0058 [~, ~]=system(['rm "' tmpDIR '" -r']);
+0059 
+0060 %%
+0061 %Check 1a: Check if files for MAFFT results are the same
+0062 verifyEqual(testCase,actMafftOutput,expCdhitMafftOutput);
+0063 
+0064 %Check 1b: Change actual MAFFT results file and check if test fails
+0065 actMafftOutput='abc';
+0066 verifyNotEqual(testCase,actMafftOutput,expCdhitMafftOutput);
+0067 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/testing/unit_tests/mergeModelsTests.html b/doc/testing/unit_tests/mergeModelsTests.html new file mode 100644 index 000000000..ef7d42dc7 --- /dev/null +++ b/doc/testing/unit_tests/mergeModelsTests.html @@ -0,0 +1,159 @@ + + + + Description of mergeModelsTests + + + + + + + + + +
Home > testing > unit_tests > mergeModelsTests.m
+ + + +

mergeModelsTests +

+ +

PURPOSE ^

+
run this test case with the command
+ +

SYNOPSIS ^

+
function tests = mergeModelsTests
+ +

DESCRIPTION ^

+
run this test case with the command
+results = runtests('mergeModelsTests.m')
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 %run this test case with the command
+0002 %results = runtests('mergeModelsTests.m')
+0003 function tests = mergeModelsTests
+0004 tests = functiontests(localfunctions);
+0005 end
+0006 
+0007 function mergeModelsBasicTest(testCase)
+0008 %Merging plain models (without rxnFrom/metFrom/geneFrom) should create these
+0009 %fields and trace each reaction/metabolite/gene back to the model it came from
+0010 sourceDir = fileparts(which(mfilename));
+0011 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
+0012 
+0013 modelA    = model;
+0014 modelA.id = 'modelA';
+0015 
+0016 %Make all reactions and metabolites in modelB unique so that they are all
+0017 %added as new entities when merging (metabolites are matched by name)
+0018 modelB          = model;
+0019 modelB.id       = 'modelB';
+0020 modelB.rxns     = strcat(modelB.rxns,'_B');
+0021 modelB.mets     = strcat(modelB.mets,'_B');
+0022 modelB.metNames = strcat(modelB.metNames,'_B');
+0023 
+0024 evalc('modelMerged=mergeModels({modelA;modelB})');
+0025 
+0026 %The From fields should exist and have the same size as their entities. Before
+0027 %the fix, metFrom was not extended and ended up shorter than mets
+0028 verifyTrue(testCase,isfield(modelMerged,'rxnFrom'));
+0029 verifyTrue(testCase,isfield(modelMerged,'metFrom'));
+0030 verifyTrue(testCase,isfield(modelMerged,'geneFrom'));
+0031 verifyEqual(testCase,numel(modelMerged.rxnFrom),numel(modelMerged.rxns));
+0032 verifyEqual(testCase,numel(modelMerged.metFrom),numel(modelMerged.mets));
+0033 verifyEqual(testCase,numel(modelMerged.geneFrom),numel(modelMerged.genes));
+0034 
+0035 %Each reaction and metabolite should be traced back to its source model
+0036 verifyEqual(testCase,modelMerged.rxnFrom,[repmat({'modelA'},numel(modelA.rxns),1);repmat({'modelB'},numel(modelB.rxns),1)]);
+0037 verifyEqual(testCase,modelMerged.metFrom,[repmat({'modelA'},numel(modelA.mets),1);repmat({'modelB'},numel(modelB.mets),1)]);
+0038 %Genes are shared between the models, so all are traced to the first model
+0039 verifyTrue(testCase,all(ismember(modelMerged.geneFrom,{'modelA','modelB'})));
+0040 end
+0041 
+0042 function mergeModelsKeepExistingFromTest(testCase)
+0043 %If the input models already have rxnFrom/metFrom/geneFrom fields, mergeModels
+0044 %should keep those values instead of overwriting them with the model ids
+0045 sourceDir = fileparts(which(mfilename));
+0046 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
+0047 
+0048 modelA          = model;
+0049 modelA.id       = 'modelA';
+0050 modelA.rxnFrom  = repmat({'origA'},numel(modelA.rxns),1);
+0051 modelA.metFrom  = repmat({'origA'},numel(modelA.mets),1);
+0052 
+0053 modelB          = model;
+0054 modelB.id       = 'modelB';
+0055 modelB.rxns     = strcat(modelB.rxns,'_B');
+0056 modelB.mets     = strcat(modelB.mets,'_B');
+0057 modelB.metNames = strcat(modelB.metNames,'_B');
+0058 modelB.rxnFrom  = repmat({'origB'},numel(modelB.rxns),1);
+0059 modelB.metFrom  = repmat({'origB'},numel(modelB.mets),1);
+0060 
+0061 evalc('modelMerged=mergeModels({modelA;modelB})');
+0062 
+0063 %The pre-existing labels should be preserved, not replaced by the model ids
+0064 verifyEqual(testCase,modelMerged.rxnFrom,[repmat({'origA'},numel(modelA.rxns),1);repmat({'origB'},numel(modelB.rxns),1)]);
+0065 verifyEqual(testCase,modelMerged.metFrom,[repmat({'origA'},numel(modelA.mets),1);repmat({'origB'},numel(modelB.mets),1)]);
+0066 end
+0067 
+0068 function mergeModelsViaCopyToCompsTest(testCase)
+0069 %copyToComps runs mergeModels with the copyToComps flag set. When the input
+0070 %model has no rxnFrom/metFrom/geneFrom fields, the output should not gain any
+0071 sourceDir = fileparts(which(mfilename));
+0072 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
+0073 
+0074 evalc('modelNew=copyToComps(model,{''p''},''ACKr'')');
+0075 
+0076 verifyFalse(testCase,isfield(modelNew,'rxnFrom'));
+0077 verifyFalse(testCase,isfield(modelNew,'metFrom'));
+0078 verifyFalse(testCase,isfield(modelNew,'geneFrom'));
+0079 %The reaction should still have been copied to the new compartment
+0080 verifyTrue(testCase,ismember('ACKr_p',modelNew.rxns));
+0081 end
+0082 
+0083 function mergeModelsViaCopyToCompsKeepFromTest(testCase)
+0084 %When the input model already has the From fields, copyToComps should keep
+0085 %them and assign empty labels ('') to the newly created reactions/metabolites
+0086 sourceDir = fileparts(which(mfilename));
+0087 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
+0088 
+0089 model.rxnFrom  = repmat({'orig'},numel(model.rxns),1);
+0090 model.metFrom  = repmat({'orig'},numel(model.mets),1);
+0091 model.geneFrom = repmat({'orig'},numel(model.genes),1);
+0092 
+0093 nRxns = numel(model.rxns);
+0094 nMets = numel(model.mets);
+0095 
+0096 evalc('modelNew=copyToComps(model,{''p''},''ACKr'')');
+0097 
+0098 %The fields should still be present and consistent in size
+0099 verifyEqual(testCase,numel(modelNew.rxnFrom),numel(modelNew.rxns));
+0100 verifyEqual(testCase,numel(modelNew.metFrom),numel(modelNew.mets));
+0101 %The original labels are kept, the new reactions/metabolites are labelled ''
+0102 verifyEqual(testCase,modelNew.rxnFrom(1:nRxns),model.rxnFrom);
+0103 verifyEqual(testCase,modelNew.metFrom(1:nMets),model.metFrom);
+0104 verifyTrue(testCase,all(strcmp(modelNew.rxnFrom(nRxns+1:end),'')));
+0105 verifyTrue(testCase,all(strcmp(modelNew.metFrom(nMets+1:end),'')));
+0106 %No new genes are introduced, so geneFrom is left untouched
+0107 verifyEqual(testCase,modelNew.geneFrom,model.geneFrom);
+0108 end
+0109
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/testing/unit_tests/miriamTests.html b/doc/testing/unit_tests/miriamTests.html new file mode 100644 index 000000000..b84499d0f --- /dev/null +++ b/doc/testing/unit_tests/miriamTests.html @@ -0,0 +1,86 @@ + + + + Description of miriamTests + + + + + + + + + +
Home > testing > unit_tests > miriamTests.m
+ + + +

miriamTests +

+ +

PURPOSE ^

+
run this test case with the command
+ +

SYNOPSIS ^

+
function tests = miriamTests
+ +

DESCRIPTION ^

+
run this test case with the command
+results = runtests('miriamTests.m')
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 %run this test case with the command
+0002 %results = runtests('miriamTests.m')
+0003 function tests = miriamTests
+0004 tests = functiontests(localfunctions);
+0005 end
+0006 
+0007 function editMiriam_and_extractMiriamTest(testCase)
+0008 %This function tests the extractMiriam and editMiriam functions
+0009 
+0010 %%
+0011 %Load the expected (i.e. sorted) model
+0012 sourceDir = fileparts(which(mfilename));
+0013 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
+0014 
+0015 %Try out all combinations, keep metMiriams field, compare with output
+0016 modelTest=editMiriam(model,'met',1,'bigg.metabolite','test','add');
+0017 testOut{1}=modelTest.metMiriams;
+0018 modelTest=editMiriam(model,'met',1,'bigg.metabolite','test','replace');
+0019 testOut{end+1}=modelTest.metMiriams;
+0020 modelTest=editMiriam(model,'met',1,'bigg.metabolite','test','fill');
+0021 testOut{end+1}=modelTest.metMiriams;
+0022 modelTest=editMiriam(model,'met','all','bigg.metabolite','test','add');
+0023 testOut{end+1}=modelTest.metMiriams;
+0024 modelTest=editMiriam(model,'met',true(1,numel(model.mets)),'bigg.metabolite','test','add');
+0025 testOut{end+1}=modelTest.metMiriams;
+0026 modelTest=editMiriam(model,'met','3pg_c','bigg.metabolite','test','add');
+0027 testOut{end+1}=modelTest.metMiriams;
+0028 modelTest=editMiriam(model,'met','3pg_c','bigg.metabolite','3pg','add');
+0029 testOut{end+1}=modelTest.metMiriams;
+0030 
+0031 %Load the correct results to compare with
+0032 load([sourceDir,'/test_data/miriamTestOutput.mat'])
+0033 
+0034 %Check that the actual model is the same as the expected model
+0035 verifyEqual(testCase,testOut,testOutOriginal)
+0036 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/testing/unit_tests/modelAbilitiesTests.html b/doc/testing/unit_tests/modelAbilitiesTests.html new file mode 100644 index 000000000..6841b69a0 --- /dev/null +++ b/doc/testing/unit_tests/modelAbilitiesTests.html @@ -0,0 +1,173 @@ + + + + Description of modelAbilitiesTests + + + + + + + + + +
Home > testing > unit_tests > modelAbilitiesTests.m
+ + + +

modelAbilitiesTests +

+ +

PURPOSE ^

+
run this test case with the command
+ +

SYNOPSIS ^

+
function tests = modelAbilitiesTests
+ +

DESCRIPTION ^

+
run this test case with the command
+results = runtests('modelAbilitiesTests.m')
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 %run this test case with the command
+0002 %results = runtests('modelAbilitiesTests.m')
+0003 function tests = modelAbilitiesTests
+0004 tests = functiontests(localfunctions);
+0005 end
+0006 
+0007 function canConsumeTest(testCase)
+0008 %Load the model in RAVEN format
+0009 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
+0010 load(fullfile(sourceDir,'testing','unit_tests','test_data','ecoli_textbook.mat'), 'model');
+0011 
+0012 testOut=canConsume(model,{'r5p_c';'ru5p_DASH_D_c';'s7p_c';'succ_c';'succ_e';'succoa_c';'xu5p_DASH_D_c'});
+0013 
+0014 testCheck=[true;true;true;true;true;false;true];
+0015 
+0016 verifyEqual(testCase,testOut,testCheck)
+0017 end
+0018 
+0019 function canProduceTest(testCase)
+0020 %Load the model in RAVEN format
+0021 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
+0022 load(fullfile(sourceDir,'testing','unit_tests','test_data','ecoli_textbook.mat'), 'model');
+0023 
+0024 testOut=canProduce(model,{'r5p_c';'ru5p_DASH_D_c';'s7p_c';'succ_c';'succ_e';'succoa_c';'xu5p_DASH_D_c'});
+0025 
+0026 testCheck=[true;true;true;true;true;false;true];
+0027 
+0028 verifyEqual(testCase,testOut,testCheck)
+0029 end
+0030 
+0031 function checkProductionTest(testCase)
+0032 %Load the model in RAVEN format
+0033 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
+0034 load(fullfile(sourceDir,'testing','unit_tests','test_data','ecoli_textbook.mat'), 'model');
+0035 
+0036 [testOut.np, testOut.npn, testOut.nfpm,testOut.mtc,~]=checkProduction(model,true,model.comps,false);
+0037 
+0038 testCheck.np=[10;13;16;17;21;30;32;37;49;50;51;52;53;64;65;71];
+0039 testCheck.npn={'Acetyl-CoA[c]';'ADP[c]';'AMP[c]';'ATP[c]';'Coenzyme A[c]';'D-Fructose[e]';'Fumarate[e]';'L-Glutamine[e]';'L-Malate[e]';'NAD[c]';'NADH[c]';'NADP[c]';'NADPH[c]';'Ubiquinone-8[c]';'Ubiquinol-8[c]';'Succinyl-CoA[c]'};
+0040 testCheck.nfpm=[true,false,false,false,true,false,false,false,false,false,false,false,false,false,false,true;false,true,true,true,false,false,false,false,false,false,false,false,false,false,false,false;false,true,true,true,false,false,false,false,false,false,false,false,false,false,false,false;false,true,true,true,false,false,false,false,false,false,false,false,false,false,false,false;true,false,false,false,true,false,false,false,false,false,false,false,false,false,false,true;false,false,false,false,false,true,false,false,false,false,false,false,false,false,false,false;false,false,false,false,false,false,true,false,false,false,false,false,false,false,false,false;false,false,false,false,false,false,false,true,false,false,false,false,false,false,false,false;false,false,false,false,false,false,false,false,true,false,false,false,false,false,false,false;false,false,false,false,false,false,false,false,false,true,true,false,false,false,false,false;false,false,false,false,false,false,false,false,false,true,true,false,false,false,false,false;false,false,false,false,false,false,false,false,false,false,false,true,true,false,false,false;false,false,false,false,false,false,false,false,false,false,false,true,true,false,false,false;false,false,false,false,false,false,false,false,false,false,false,false,false,true,true,false;false,false,false,false,false,false,false,false,false,false,false,false,false,true,true,false;true,false,false,false,true,false,false,false,false,false,false,false,false,false,false,true];
+0041 testCheck.mtc={'Acetyl-CoA[c] (connects 3 metabolites)';'ADP[c] (connects 3 metabolites)';'NAD[c] (connects 2 metabolites)';'NADP[c] (connects 2 metabolites)';'Ubiquinone-8[c] (connects 2 metabolites)';'D-Fructose[e] (connects 1 metabolites)';'Fumarate[e] (connects 1 metabolites)';'L-Glutamine[e] (connects 1 metabolites)';'L-Malate[e] (connects 1 metabolites)'};
+0042 
+0043 verifyEqual(testCase,testOut,testCheck)
+0044 end
+0045 
+0046 function consumeSomethingTest(testCase)
+0047 %Load the model in RAVEN format
+0048 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
+0049 load(fullfile(sourceDir,'testing','unit_tests','test_data','ecoli_textbook.mat'), 'model');
+0050 
+0051 [testOut.s, testOut.m]=consumeSomething(model,{'r5p_c';'ru5p_DASH_D_c';'s7p_c';'succ_c';'succ_e';'succoa_c';'xu5p_DASH_D_c'});
+0052 % Simplify output for later check, no need for high precision
+0053 % testOut.s(abs(testOut.s)<1e-10)=0;
+0054 % testOut.s=round(testOut.s,4)
+0055 testCheck.s=[0;0;1.4591;0;0;1.4591;0;0;0;0;8.39;4.0126;0;1.4591;0;2.9183;0;1.4591;0;1.4591;0;0;1.4591;0;0;0;0;0;0;0;1.4591;0;0;0;0;-1.4591;1.4591;0;0;0;0;0;0;0;0;0;0;0;-1.4591;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;2.9183;0;0;-1.4591;1.4591;0;0;0;-1.4591;0;1.4591;1.4591;0;0;0;-1.4591;1.4591;0;0;0;0;0;0;0;0;0;0;0;0];
+0056 testCheck.m=[33];
+0057 
+0058 verifyEqual(testCase,testOut,testCheck,'AbsTol',1e-4)
+0059 end
+0060 
+0061 function makeSomethingTest(testCase)
+0062 %Load the model in RAVEN format
+0063 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
+0064 load(fullfile(sourceDir,'testing','unit_tests','test_data','ecoli_textbook.mat'), 'model');
+0065 
+0066 [testOut.s, testOut.m]=makeSomething(model,{'r5p_c';'ru5p_DASH_D_c';'s7p_c';'succ_c';'succ_e';'succoa_c';'xu5p_DASH_D_c'});
+0067 % Simplify output for later check, no need for high precision
+0068 % testOut.s(abs(testOut.s)<1e-10)=0;
+0069 % testOut.s=round(testOut.s,4);
+0070 
+0071 testCheck.s=[0;0;1.8644;0;0;0;0;0;0;0;8.39;4.6611;0;0;0;3.7289;0;1.8644;0;0;0;0;0;0;0;0;0;-0.93220;0;0;0;0;0;0;0;-1.8644;0;0;0;0.93220;0;0;0;0;0;0;0;0;-1.8644;0.93220;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;3.7289;0;0;-1.8644;1.8644;0.93220;0;-0.93220;-1.8644;0;1.8644;0;0;0;0;-1.8644;0.93220;0;0;0;0;0;0;0;0;0;0;0;0.93220];
+0072 testCheck.m=[6];
+0073 
+0074 verifyEqual(testCase,testOut,testCheck,'AbsTol',1e-4)
+0075 end
+0076 
+0077 function getElementalBalanceTest(testCase)
+0078 %Load the model in RAVEN format
+0079 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
+0080 load(fullfile(sourceDir,'testing','unit_tests','test_data','ecoli_textbook.mat'), 'model');
+0081 
+0082 testOut=getElementalBalance(model,1);
+0083 
+0084 testCheck.balanceStatus=1;
+0085 testCheck.elements.abbrevs={'C';'N';'O';'S';'P';'H'};
+0086 testCheck.elements.names={'carbon';'nitrogen';'oxygen';'sulfur';'phosphorus';'hydrogen'};
+0087 testCheck.leftComp=[44,14,31,1,5,62];
+0088 testCheck.rightComp=[44,14,31,1,5,62];
+0089 
+0090 verifyEqual(testCase,testOut,testCheck)
+0091 end
+0092 
+0093 function getAllowedBoundsTest(testCase)
+0094 %Load the model in RAVEN format
+0095 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
+0096 load(fullfile(sourceDir,'testing','unit_tests','test_data','ecoli_textbook.mat'), 'model');
+0097 
+0098 
+0099 evalc("[testOut.min, testOut.max, testOut.flag]=getAllowedBounds(model,[1:10],false);");
+0100 % Simplify output for later check, no need for high precision
+0101 % testOut.min(abs(testOut.min)<1e-10)=0;
+0102 % testOut.min=single(testOut.min);
+0103 % testOut.max(abs(testOut.max)<1e-10)=0;
+0104 % testOut.max=single(testOut.max);
+0105 
+0106 testCheck.min=[-20;0;0;0;0;0;-166.610;0;0;0];
+0107 testCheck.max=[0;20;20;20;20;20;0;20;10;20];
+0108 testCheck.flag=[1,1;1,1;1,1;1,1;1,1;1,1;1,1;1,1;1,1;1,1];
+0109 
+0110 verifyEqual(testCase,testOut,testCheck,'AbsTol',1e-4)
+0111 end
+0112 
+0113 function getEssentialRxnsTest(testCase)
+0114 %Load the model in RAVEN format
+0115 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
+0116 load(fullfile(sourceDir,'testing','unit_tests','test_data','ecoli_textbook.mat'), 'model');
+0117 
+0118 [testOut.r, testOut.i]=getEssentialRxns(model);
+0119 
+0120 testCheck.r={'EX_glc';'GLCpts'};
+0121 testCheck.i=[28;50];
+0122 verifyEqual(testCase,testOut,testCheck)
+0123 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/testing/unit_tests/modelConversionTests.html b/doc/testing/unit_tests/modelConversionTests.html new file mode 100644 index 000000000..269e71e1b --- /dev/null +++ b/doc/testing/unit_tests/modelConversionTests.html @@ -0,0 +1,75 @@ + + + + Description of modelConversionTests + + + + + + + + + +
Home > testing > unit_tests > modelConversionTests.m
+ + + +

modelConversionTests +

+ +

PURPOSE ^

+
run this test case with the command
+ +

SYNOPSIS ^

+
function tests = modelConversionTests
+ +

DESCRIPTION ^

+
run this test case with the command
+results = runtests('modelConversionTests.m')
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 %run this test case with the command
+0002 %results = runtests('modelConversionTests.m')
+0003 function tests = modelConversionTests
+0004 tests = functiontests(localfunctions);
+0005 end
+0006 
+0007 function ravenCobraWrapperTest(testCase)
+0008 %This function tests the ravenCobraWrapper function by going through a full
+0009 %cycle RAVEN -> COBRA -> RAVEN, and the model should be (near) identical
+0010 %(only annotation field should be lost).
+0011 
+0012 %Load the model in RAVEN format
+0013 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
+0014 load(fullfile(sourceDir,'testing','unit_tests','test_data','ecoli_textbook.mat'), 'model');
+0015 
+0016 %Prevent writing of messages to command window
+0017 evalc('modelCobra=ravenCobraWrapper(model);');
+0018 evalc('modelRaven=ravenCobraWrapper(modelCobra);');
+0019 
+0020 %We know that the annotation field is lost
+0021 modelNoAnnot=rmfield(model,'annotation');
+0022 
+0023 %Check that the actual model is the same as the expected model
+0024 verifyEqual(testCase,modelRaven,modelNoAnnot)
+0025 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/testing/unit_tests/modelCurationTests.html b/doc/testing/unit_tests/modelCurationTests.html new file mode 100644 index 000000000..dde7fe80c --- /dev/null +++ b/doc/testing/unit_tests/modelCurationTests.html @@ -0,0 +1,543 @@ + + + + Description of modelCurationTests + + + + + + + + + +
Home > testing > unit_tests > modelCurationTests.m
+ + + +

modelCurationTests +

+ +

PURPOSE ^

+
run this test case with the command
+ +

SYNOPSIS ^

+
function tests = modelCurationTests
+ +

DESCRIPTION ^

+
run this test case with the command
+results = runtests('modelCurationTests.m')
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 %run this test case with the command
+0002 %results = runtests('modelCurationTests.m')
+0003 function tests = modelCurationTests
+0004 tests = functiontests(localfunctions);
+0005 end
+0006 
+0007 function addExchangeRxnsTest(testCase)
+0008 sourceDir = fileparts(which(mfilename));
+0009 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
+0010 
+0011 modelNew=addExchangeRxns(model,'both','6pgl_c');
+0012 
+0013 %Perform the curation manually for comparison
+0014 modelManual=model;
+0015 modelManual.rxns(end+1)={'EXC_BOTH_6pgl_c'};
+0016 modelManual.lb(end+1)=-1000;
+0017 modelManual.ub(end+1)=1000;
+0018 modelManual.c(end+1)=0;
+0019 modelManual.rev(end+1)=1;
+0020 modelManual.rxnNames(end+1)={'6-phospho-D-glucono-1,5-lactone exchange (BOTH)'};
+0021 modelManual.grRules(end+1)={''};
+0022 modelManual.eccodes(end+1)={''};
+0023 modelManual.rxnGeneMat(end+1,:)=sparse(zeros(1,numel(modelManual.genes)));
+0024 modelManual.S(:,end+1)=sparse(zeros(numel(modelManual.mets),1));
+0025 modelManual.S(5,end)=-1;
+0026 
+0027 verifyEqual(testCase,modelNew,modelManual)
+0028 end
+0029 
+0030 function addTransportTest(testCase)
+0031 sourceDir = fileparts(which(mfilename));
+0032 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
+0033 
+0034 evalc('modelNew=addTransport(model,''c'',''e'',{''6-phospho-D-glucono-1,5-lactone''},false,false,''test_'');');
+0035 
+0036 %Perform the curation manually for comparison
+0037 modelManual=model;
+0038 modelManual.rxns(end+1)={'test_0001'};
+0039 modelManual.lb(end+1)=0;
+0040 modelManual.ub(end+1)=Inf;
+0041 modelManual.c(end+1)=0;
+0042 modelManual.rev(end+1)=0;
+0043 modelManual.rxnNames(end+1)={'6-phospho-D-glucono-1,5-lactone transport, Cytoplasm-Extraorganism'};
+0044 modelManual.grRules(end+1)={''};
+0045 modelManual.eccodes(end+1)={''};
+0046 modelManual.rxnGeneMat(end+1,:)=sparse(zeros(1,numel(modelManual.genes)));
+0047 
+0048 modelManual.S(:,end+1)=sparse(zeros(numel(modelManual.mets),1));
+0049 modelManual.S(end+1,:)=sparse(zeros(1,numel(modelManual.rxns)));
+0050 modelManual.S([5,73],end)=[-1,1];
+0051 
+0052 modelManual.mets(end+1)={'m_0001'};
+0053 modelManual.metNames(end+1)={'6-phospho-D-glucono-1,5-lactone'};
+0054 modelManual.metMiriams(end+1)=modelManual.metMiriams(5);
+0055 modelManual.b(end+1)=[0];
+0056 modelManual.metFormulas(end+1)={'C6H9O9P'};
+0057 modelManual.metComps(end+1)=[2];
+0058 
+0059 verifyEqual(testCase,modelNew,modelManual)
+0060 end
+0061 
+0062 function addGenesRavenTest(testCase)
+0063 sourceDir = fileparts(which(mfilename));
+0064 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
+0065 
+0066 genesToAdd.genes={'testgene1','testgene2'};
+0067 genesToAdd.geneShortNames={'short1','short2'};
+0068 genesToAdd.geneMiriams{1}=struct('name',{{'testDB1';'testDB2'}},'value',...
+0069     {{'testValue1';'testValue2'}});
+0070 genesToAdd.geneMiriams{2}=struct('name',{{'testDB2';'testDB1'}},'value',...
+0071     {{'testValue2';'testValue1'}});
+0072 
+0073 modelNew=addGenesRaven(model,genesToAdd);
+0074 
+0075 %Perform the curation manually for comparison
+0076 modelManual=model;
+0077 modelManual.geneMiriams(1:numel(modelManual.genes),1)={[]};
+0078 modelManual.genes(end+1:end+2)=genesToAdd.genes;
+0079 modelManual.geneShortNames(end+1:end+2)=genesToAdd.geneShortNames;
+0080 modelManual.rxnGeneMat(:,end+1:end+2)=sparse(zeros(numel(modelManual.rxns),2));
+0081 modelManual.geneMiriams(end+1:end+2)=genesToAdd.geneMiriams;
+0082 verifyEqual(testCase,modelNew,modelManual)
+0083 end
+0084 
+0085 function removeGenesTest(testCase)
+0086 sourceDir = fileparts(which(mfilename));
+0087 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
+0088 
+0089 modelNew=removeGenes(model,'b1817',true,true,false);
+0090 
+0091 %Perform the curation manually for comparison
+0092 modelManual=model;
+0093 modelManual.genes(54)=[];
+0094 modelManual.geneShortNames(54)=[];
+0095 modelManual.rxnGeneMat(:,54)=[];
+0096 modelManual.rxnGeneMat(45,:)=[];
+0097 modelManual.grRules(50)={'(b2415 and b1621 and b2417 and b2416) or (b2415 and b2417 and b2416 and b1101)'};
+0098 modelManual.grRules(45)=[];
+0099 modelManual.rxns(45)=[];
+0100 modelManual.rxnNames(45)=[];
+0101 modelManual.lb(45)=[];
+0102 modelManual.ub(45)=[];
+0103 modelManual.c(45)=[];
+0104 modelManual.rev(45)=[];
+0105 modelManual.S(:,45)=[];
+0106 modelManual.eccodes(45)=[];
+0107 verifyEqual(testCase,modelNew,modelManual)
+0108 end
+0109 
+0110 function addMetsTest(testCase)
+0111 sourceDir = fileparts(which(mfilename));
+0112 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
+0113 
+0114 metsToAdd.metNames={'metaboliteName','3-Phospho-D-glycerate'};
+0115 metsToAdd.compartments={'c','e'};
+0116 metsToAdd.metCharges=[2,0];
+0117 metsToAdd.metNotes={'this is just a test','another one'};
+0118 metsToAdd.metMiriams{1}=struct('name',{{'testDB1';'testDB2'}},'value',...
+0119     {{'testValue1';'testValue2'}});
+0120 metsToAdd.metMiriams{2}=struct('name',{{'testDB1'}},'value',...
+0121     {{'testValue1'}});
+0122 
+0123 evalc('modelNew=addMets(model,metsToAdd,true);');
+0124 
+0125 %Perform the curation manually for comparison
+0126 modelManual=model;
+0127 modelManual.metNotes(1:numel(modelManual.mets),1)={''};
+0128 modelManual.metCharges(1:numel(modelManual.mets),1)=NaN(numel(modelManual.mets),1);
+0129 modelManual.mets(end+1:end+2)={'m_0001','m_0002'};
+0130 modelManual.metNames(end+1:end+2)=metsToAdd.metNames;
+0131 modelManual.metNotes(end+1:end+2)=metsToAdd.metNotes;
+0132 modelManual.metMiriams(end+1:end+2)=metsToAdd.metMiriams;
+0133 modelManual.metCharges(end+1:end+2)=[2,NaN];
+0134 modelManual.b(end+1:end+2)=[0,0];
+0135 modelManual.metFormulas(end+1:end+2)={'','C3H4O7P'};
+0136 modelManual.metComps(end+1:end+2)=[1,2];
+0137 modelManual.S(end+1:end+2,:)=sparse(zeros(2,numel(modelManual.rxns)));
+0138 
+0139 verifyEqual(testCase,modelManual,modelNew)
+0140 end
+0141 
+0142 function addMets_oneCompTest(testCase)
+0143 sourceDir = fileparts(which(mfilename));
+0144 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
+0145 
+0146 metsToAdd.metNames={'metaboliteName','3-Phospho-D-glycerate'};
+0147 metsToAdd.compartments={'e'};
+0148 metsToAdd.metCharges=[2,0];
+0149 metsToAdd.metNotes={'this is just a test','another one'};
+0150 metsToAdd.metMiriams{1}=struct('name',{{'testDB1';'testDB2'}},'value',...
+0151     {{'testValue1';'testValue2'}});
+0152 metsToAdd.metMiriams{2}=struct('name',{{'testDB1'}},'value',...
+0153     {{'testValue1'}});
+0154 
+0155 evalc('modelNew=addMets(model,metsToAdd,true);');
+0156 
+0157 %Perform the curation manually for comparison
+0158 modelManual=model;
+0159 modelManual.metNotes(1:numel(modelManual.mets),1)={''};
+0160 modelManual.metCharges(1:numel(modelManual.mets),1)=NaN(numel(modelManual.mets),1);
+0161 modelManual.mets(end+1:end+2)={'m_0001','m_0002'};
+0162 modelManual.metNames(end+1:end+2)=metsToAdd.metNames;
+0163 modelManual.metNotes(end+1:end+2)=metsToAdd.metNotes;
+0164 modelManual.metMiriams(end+1:end+2)=metsToAdd.metMiriams;
+0165 modelManual.metCharges(end+1:end+2)=[2,NaN];
+0166 modelManual.b(end+1:end+2)=[0,0];
+0167 modelManual.metFormulas(end+1:end+2)={'','C3H4O7P'};
+0168 modelManual.metComps(end+1:end+2)=2;
+0169 modelManual.S(end+1:end+2,:)=sparse(zeros(2,numel(modelManual.rxns)));
+0170 
+0171 verifyEqual(testCase,modelManual,modelNew)
+0172 end
+0173 
+0174 function removeMetsTest(testCase)
+0175 sourceDir = fileparts(which(mfilename));
+0176 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
+0177 
+0178 modelNew=removeMets(model,'Acetate',true,true,true,true);
+0179 
+0180 %Perform the curation manually for comparison
+0181 modelManual=model;
+0182 modelManual.mets(6:7)=[];
+0183 modelManual.metNames(6:7)=[];
+0184 modelManual.metMiriams(6:7)=[];
+0185 modelManual.b(6:7)=[];
+0186 modelManual.metFormulas(6:7)=[];
+0187 modelManual.metComps(6:7)=[];
+0188 modelManual.S(6:7,:)=[];
+0189 
+0190 modelManual.rxnGeneMat(20,:)=[];
+0191 modelManual.grRules(20)=[];
+0192 modelManual.rxns(20)=[];
+0193 modelManual.rxnNames(20)=[];
+0194 modelManual.lb(20)=[];
+0195 modelManual.ub(20)=[];
+0196 modelManual.c(20)=[];
+0197 modelManual.rev(20)=[];
+0198 modelManual.S(:,20)=[];
+0199 modelManual.eccodes(20)=[];
+0200 verifyEqual(testCase,modelNew,modelManual)
+0201 end
+0202 
+0203 function addRxnsTest(testCase)
+0204 sourceDir = fileparts(which(mfilename));
+0205 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
+0206 rxnsToAdd.rxns='test1';
+0207 rxnsToAdd.equations='2-Oxoglutarate => TEST';
+0208 rxnsToAdd.rxnNames={'testRxn1'}; % test cell array
+0209 rxnsToAdd.rxnMiriams{1}=struct('name',{{'testDB1';'testDB2'}},'value',...
+0210     {{'testValue1';'testValue2'}});
+0211 rxnsToAdd.grRules="b0008"; % test string
+0212 evalc('modelNew=addRxns(model,rxnsToAdd,2,''c'',true);');
+0213 
+0214 rxnsToAdd.rxns='test2';
+0215 rxnsToAdd=rmfield(rxnsToAdd,'equations');
+0216 rxnsToAdd.mets={{'6pgl_c','atp_c'}};
+0217 rxnsToAdd.stoichCoeffs=[[-1,2]];
+0218 rxnsToAdd.lb=-1000;
+0219 rxnsToAdd.grRules='test';
+0220 evalc('modelNew=addRxns(modelNew,rxnsToAdd,1,''c'',true,true);');
+0221 
+0222 %Perform the curation manually for comparison
+0223 modelManual=model;
+0224 
+0225 modelManual.rxnMiriams=cell(numel(modelManual.rxns),1);
+0226 modelManual.rxns(end+1:end+2)={'test1';'test2'};
+0227 modelManual.mets(end+1)={'m_0001'};
+0228 modelManual.S(end+1,:)=zeros(1,numel(modelManual.rxns)-2);
+0229 modelManual.S(:,end+1:end+2)=zeros(numel(modelManual.mets),2);
+0230 modelManual.S(end,96)=1;
+0231 modelManual.S([14,73],end-1)=[-1,1];
+0232 modelManual.S([5,17],end)=[-1,2];
+0233 modelManual.lb(end+1:end+2)=[0;-1000];
+0234 modelManual.ub(end+1:end+2)=[Inf;Inf];
+0235 modelManual.rev(end+1:end+2)=[0;1];
+0236 modelManual.c(end+1:end+2)=[0;0];
+0237 modelManual.b(end+1)=[0];
+0238 modelManual.rxnNames(end+1:end+2)={'testRxn1';'testRxn1'};
+0239 modelManual.grRules(end+1:end+2)={'b0008';'test'};
+0240 
+0241 modelManual.rxnGeneMat(end+1:end+2,:)=zeros(2,numel(modelManual.genes));
+0242 modelManual.rxnGeneMat(:,end+1)=zeros(numel(modelManual.rxns),1);
+0243 modelManual.rxnGeneMat(97,end)=1;
+0244 modelManual.rxnGeneMat(end-1,1)=1;
+0245 modelManual.rxnGeneMat(end,138)=1;
+0246 
+0247 modelManual.eccodes(end+1:end+2)={'';''};
+0248 modelManual.genes(end+1)={'test'};
+0249 modelManual.geneShortNames(end+1)={''};
+0250 modelManual.metNames(end+1)={'TEST'};
+0251 modelManual.metComps(end+1)=[1];
+0252 modelManual.metFormulas(end+1)={''};
+0253 modelManual.metMiriams(end+1)={[]};
+0254 modelManual.rxnMiriams(end+1:end+2)={struct('name',{{'testDB1';'testDB2'}},'value',...
+0255     {{'testValue1';'testValue2'}})};
+0256 
+0257 verifyEqual(testCase,modelManual,modelNew)
+0258 end
+0259 
+0260 function removeReactionsTest(testCase)
+0261 sourceDir = fileparts(which(mfilename));
+0262 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
+0263 
+0264 modelNew=removeMets(model,'Acetate',true,true,true,true);
+0265 
+0266 %Perform the curation manually for comparison
+0267 modelManual=model;
+0268 modelManual.mets(6:7)=[];
+0269 modelManual.metNames(6:7)=[];
+0270 modelManual.metMiriams(6:7)=[];
+0271 modelManual.b(6:7)=[];
+0272 modelManual.metFormulas(6:7)=[];
+0273 modelManual.metComps(6:7)=[];
+0274 modelManual.S(6:7,:)=[];
+0275 
+0276 modelManual.rxnGeneMat(20,:)=[];
+0277 modelManual.grRules(20)=[];
+0278 modelManual.rxns(20)=[];
+0279 modelManual.rxnNames(20)=[];
+0280 modelManual.lb(20)=[];
+0281 modelManual.ub(20)=[];
+0282 modelManual.c(20)=[];
+0283 modelManual.rev(20)=[];
+0284 modelManual.S(:,20)=[];
+0285 modelManual.eccodes(20)=[];
+0286 verifyEqual(testCase,modelNew,modelManual)
+0287 end
+0288 
+0289 function getMetsInCompTest(testCase)
+0290 %Load the model in RAVEN format
+0291 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
+0292 load(fullfile(sourceDir,'testing','unit_tests','test_data','ecoli_textbook.mat'), 'model');
+0293 
+0294 evalc('[testOut.I, testOut.metNames]=getMetsInComp(model,''e'');');
+0295 
+0296 testCheck.I=[false;false;false;false;false;false;true;false;true;false;false;false;false;false;true;false;false;false;false;true;false;false;false;false;true;false;false;false;true;true;false;true;false;false;true;false;true;false;true;false;false;true;false;true;false;false;true;false;true;false;false;false;false;false;true;false;true;false;false;false;true;false;true;false;false;false;false;false;false;true;false;false];
+0297 testCheck.metNames={'Acetate';'Acetaldehyde';'2-Oxoglutarate';'CO2';'Ethanol';'Formate';'D-Fructose';'Fumarate';'D-Glucose';'L-Glutamine';'L-Glutamate';'H2O';'H+';'D-Lactate';'L-Malate';'Ammonium';'O2';'Phosphate';'Pyruvate';'Succinate'};
+0298 verifyEqual(testCase,testOut,testCheck)
+0299 end
+0300 
+0301 function getRxnsInCompTest(testCase)
+0302 %Load the model in RAVEN format
+0303 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
+0304 load(fullfile(sourceDir,'testing','unit_tests','test_data','ecoli_textbook.mat'), 'model');
+0305 
+0306 evalc('[testOut.I, testOut.rxnNames]=getRxnsInComp(model,''e'');');
+0307 
+0308 testCheck.I=[20;21;22;23;24;25;26;27;28;29;30;31;32;33;34;35;36;37;38;39];
+0309 testCheck.rxnNames={'Acetate exchange';'Acetaldehyde exchange';'2-Oxoglutarate exchange';'CO2 exchange';'Ethanol exchange';'Formate exchange';'D-Fructose exchange';'Fumarate exchange';'D-Glucose exchange';'L-Glutamine exchange';'L-Glutamate exchange';'H+ exchange';'H2O exchange';'D-lactate exchange';'L-Malate exchange';'Ammonia exchange';'O2 exchange';'Phosphate exchange';'Pyruvate exchange';'Succinate exchange'};
+0310 verifyEqual(testCase,testOut,testCheck)
+0311 end
+0312 
+0313 function getAllRxnsFromGenesTest(testCase)
+0314 %Load the model in RAVEN format
+0315 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
+0316 load(fullfile(sourceDir,'testing','unit_tests','test_data','ecoli_textbook.mat'), 'model');
+0317 evalc('testOut=getAllRxnsFromGenes(model,''ACONTa'');');
+0318 
+0319 testCheck={'ACONTa';'ACONTb'};
+0320 verifyEqual(testCase,testOut,testCheck)
+0321 end
+0322 
+0323 function changeRxnsTest(testCase)
+0324 %Load the model in RAVEN format
+0325 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
+0326 load(fullfile(sourceDir,'testing','unit_tests','test_data','ecoli_textbook.mat'), 'model');
+0327 
+0328 evalc('modelNew=changeRxns(model,''ACKr'',''2-Oxoglutarate <=> TEST'',2,''c'',true);');
+0329 
+0330 equations.mets={{'2-Oxoglutarate','TEST'}};
+0331 equations.stoichCoeffs={[-1,1]};
+0332 
+0333 evalc('modelNewStruct=changeRxns(model,''ACKr'',equations,2,''c'',true);');
+0334 
+0335 %Perform the curation manually for comparison
+0336 modelManual=model;
+0337 
+0338 modelManual.mets(end+1)={'m_0001'};
+0339 modelManual.S(end+1,:)=zeros(1,numel(modelManual.rxns));
+0340 modelManual.S(:,3)=0;
+0341 modelManual.S([14,73],3)=[-1,1];
+0342 
+0343 modelManual.metNames(end+1)={'TEST'};
+0344 modelManual.metComps(end+1)=[1];
+0345 modelManual.metFormulas(end+1)={''};
+0346 modelManual.metMiriams(end+1)={[]};
+0347 modelManual.b(end+1)=[0];
+0348 modelManual.rev(3)=[1];
+0349 
+0350 verifyEqual(testCase,modelNew,modelManual)
+0351 verifyEqual(testCase,modelNewStruct,modelManual)
+0352 end
+0353 
+0354 function removeBadRxnsTest(testCase)
+0355 %Load the model in RAVEN format
+0356 sourceDir=fileparts(fileparts(fileparts(which(mfilename))));
+0357 load(fullfile(sourceDir,'testing','unit_tests','test_data','ecoli_textbook.mat'), 'model');
+0358 
+0359 [~,exchRxns]=getExchangeRxns(model);
+0360 modelNew=model;
+0361 
+0362 modelNew.lb(exchRxns)=[0];
+0363 modelNew.ub(exchRxns)=[0];
+0364 modelNew.lb(modelNew.lb>0)=0;
+0365 modelNew.S(17,:)=1;
+0366 [~, testOut]=removeBadRxns(modelNew);
+0367 evalc('[~, testOut]=removeBadRxns(modelNew,3,modelNew.metComps==2);');
+0368 
+0369 import matlab.unittest.constraints.AnyCellOf;
+0370 import matlab.unittest.constraints.ContainsSubstring;
+0371 verifyThat(testCase,AnyCellOf({'SUCDi','FRD7'}),ContainsSubstring(testOut{:}),'test')
+0372 %Either SUCDi or FRD7 should be given as output
+0373 end
+0374 
+0375 function changeGrRulesTest(testCase)
+0376 sourceDir = fileparts(which(mfilename));
+0377 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
+0378 
+0379 modelNew=changeGrRules(model,{'ACKr','ACONTa'},{'b2296 and b1849';'b1849'},true);
+0380 modelNew=changeGrRules(modelNew,'ACONTa','b1849',false);
+0381 
+0382 %Perform the curation manually for comparison
+0383 modelManual=model;
+0384 modelManual.grRules(3:4)={'b2296 and b1849';'b1849 or b1849'};
+0385 modelManual.rxnGeneMat(3:4,:)=0;
+0386 modelManual.rxnGeneMat(3,[57,76])=1;
+0387 modelManual.rxnGeneMat(4,57)=1;
+0388 
+0389 verifyEqual(testCase,modelNew,modelManual)
+0390 end
+0391 
+0392 function copyToCompsTest(testCase)
+0393 sourceDir = fileparts(which(mfilename));
+0394 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
+0395 
+0396 modelNew=copyToComps(model,{'p','e'},'ACKr');
+0397 
+0398 %Perform the curation manually for comparison
+0399 modelManual=model;
+0400 
+0401 modelManual.rxns(end+1:end+2)={'ACKr_p';'ACKr_e'};
+0402 modelManual.mets(end+1:end+7)={'ac_c_p';'actp_c_p';'adp_c_p';'atp_c_p';'actp_c_e';'adp_c_e';'atp_c_e'};
+0403 modelManual.S(end+1:end+7,:)=zeros(7,numel(modelManual.rxns)-2);
+0404 modelManual.S(:,end+1:end+2)=zeros(numel(modelManual.mets),2);
+0405 
+0406 modelManual.S([73,74,75,76],end-1)=[1,-1,-1,1];
+0407 modelManual.S([7,77,78,79],end)=[1,-1,-1,1];
+0408 
+0409 modelManual.lb(end+1:end+2)=[-1000;-1000];
+0410 modelManual.ub(end+1:end+2)=[1000;1000];
+0411 modelManual.rev(end+1:end+2)=[1;1];
+0412 modelManual.c(end+1:end+2)=[0;0];
+0413 modelManual.rxnNames(end+1:end+2)={'acetate kinase';'acetate kinase'};
+0414 modelManual.grRules(end+1:end+2)={'b1849 or b2296 or b3115';'b1849 or b2296 or b3115'};
+0415 modelManual.eccodes(end+1:end+2)={'2.7.2.1';'2.7.2.1'};
+0416 
+0417 modelManual.rxnGeneMat(end+1:end+2,:)=zeros(2,numel(modelManual.genes));
+0418 modelManual.rxnGeneMat(end-1:end,[57,76,97])=1;
+0419 
+0420 modelManual.metNames(end+1:end+7)={'Acetate';'Acetyl phosphate';'ADP';'ATP';'Acetyl phosphate';'ADP';'ATP'};
+0421 modelManual.metComps(end+1:end+7)=[3;3;3;3;2;2;2];
+0422 modelManual.metFormulas(end+1:end+7)={'C2H3O2';'C2H3O5P';'C10H12N5O10P2';'C10H12N5O13P3';'C2H3O5P';'C10H12N5O10P2';'C10H12N5O13P3'};
+0423 modelManual.metMiriams(end+1:end+7)=modelManual.metMiriams([6,12,13,17,12,13,17]);
+0424 modelManual.b(end+1:end+7)=[0];
+0425 
+0426 modelManual.comps(end+1)={'p'};
+0427 modelManual.compNames(end+1)={'p'};
+0428 
+0429 verifyEqual(testCase,modelNew,modelManual)
+0430 end
+0431 
+0432 function setExchangeBoundsTest(testCase)
+0433 sourceDir = fileparts(which(mfilename));
+0434 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
+0435 
+0436 modelNew=setExchangeBounds(model,{'ac_e';'akg_e'},-500,500);
+0437 
+0438 %Perform the curation manually for comparison
+0439 modelManual=model;
+0440 
+0441 exchRxns=[21;23;24;25;26;27;28;29;30;31;32;33;34;35;36;37;38;39];
+0442 modelManual.lb(exchRxns)=0;
+0443 modelManual.lb([20,22])=-500;
+0444 modelManual.ub([20,22])=500;
+0445 
+0446 verifyEqual(testCase,modelNew,modelManual)
+0447 end
+0448 
+0449 function addRxnsGenesMetsTest(testCase)
+0450 sourceDir = fileparts(which(mfilename));
+0451 load(fullfile(sourceDir,'test_data','ecoli_textbook.mat'), 'model');
+0452 
+0453 sbmlFile=fullfile(sourceDir,'..','..','tutorial','empty.xml');
+0454 evalc('modelEmpty=importModel(sbmlFile,[],true)'); % Repress warnings
+0455 
+0456 evalc('modelNew=addRxnsGenesMets(model,modelEmpty,''r1'',true);');
+0457 
+0458 %Perform the curation manually for comparison
+0459 modelManual=model;
+0460 
+0461 modelManual.rxns(end+1)={'r1'};
+0462 modelManual.mets(end+1:end+3)={'m1';'m2';'m3'};
+0463 modelManual.S(end+1:end+3,:)=zeros(3,numel(modelManual.rxns)-1);
+0464 modelManual.S(:,end+1)=zeros(numel(modelManual.mets),1);
+0465 modelManual.S([42,73,74,75],end)=[-1,-1,1,1];
+0466 
+0467 modelManual.lb(end+1)=[0];
+0468 modelManual.ub(end+1)=[1000];
+0469 modelManual.rev(end+1)=[0];
+0470 modelManual.c(end+1)=[0];
+0471 modelManual.rxnNames(end+1)={'Breakdown of sucrose (invertase)'};
+0472 modelManual.grRules(end+1)={'g1'};
+0473 modelManual.eccodes(end+1)={''};
+0474 modelManual.rxnNotes(1:numel(modelManual.rxns),1)={''};
+0475 modelManual.rxnNotes(end)={'Added via addRxnsGenesMets()'};
+0476 modelManual.rxnConfidenceScores(1:numel(modelManual.rxns),1)=NaN;
+0477 modelManual.rxnConfidenceScores(end)=[0];
+0478 
+0479 modelManual.genes(end+1)={'g1'};
+0480 modelManual.geneShortNames(end+1)={''};
+0481 
+0482 modelManual.rxnGeneMat(end+1,:)=zeros(1,numel(modelManual.genes)-1);
+0483 modelManual.rxnGeneMat(:,end+1)=zeros(numel(modelManual.rxns),1);
+0484 modelManual.rxnGeneMat(end,end)=1;
+0485 
+0486 modelManual.metNames(end+1:end+3)={'sucrose';'glucose';'fructose'};
+0487 modelManual.metComps(end+1:end+3)=[2;2;2];
+0488 modelManual.metFormulas(end+1:end+3)={'C12H22O11';'C6H12O6';'C6H12O6'};
+0489 modelManual.metMiriams(end+1:end+3)={[];[];[]};
+0490 modelManual.b(end+1:end+3)=[0];
+0491 
+0492 verifyEqual(testCase,modelNew,modelManual)
+0493 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/testing/unit_tests/modelSortingTests.html b/doc/testing/unit_tests/modelSortingTests.html new file mode 100644 index 000000000..f75a2fb7f --- /dev/null +++ b/doc/testing/unit_tests/modelSortingTests.html @@ -0,0 +1,118 @@ + + + + Description of modelSortingTests + + + + + + + + + +
Home > testing > unit_tests > modelSortingTests.m
+ + + +

modelSortingTests +

+ +

PURPOSE ^

+
run this test case with the command
+ +

SYNOPSIS ^

+
function tests = modelSortingTests
+ +

DESCRIPTION ^

+
run this test case with the command
+results = runtests('modelSortingTests.m')
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 %run this test case with the command
+0002 %results = runtests('modelSortingTests.m')
+0003 function tests = modelSortingTests
+0004 tests = functiontests(localfunctions);
+0005 end
+0006 
+0007 function sortIdentifirs_and_permuteModelTest(testCase)
+0008 
+0009 %Load the expected (i.e. sorted) model
+0010 sourceDir = fileparts(which(mfilename));
+0011 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
+0012 expModel = model;
+0013 
+0014 %Create the actual model that will be permuted and sorted
+0015 actModel = expModel;
+0016 
+0017 %Randomly permutate model, do not use RAVEN functions
+0018 rndIdx = randperm(numel(actModel.rxns));
+0019 fieldsToChange = {'rxns','lb','ub','rev','c','rxnNames','grRules','eccodes'};
+0020 for i=1:numel(fieldsToChange)
+0021     actModel.(fieldsToChange{i}) = actModel.(fieldsToChange{i})(rndIdx);
+0022 end
+0023 actModel.S          = actModel.S(:,rndIdx);
+0024 actModel.rxnGeneMat = actModel.rxnGeneMat(rndIdx,:);
+0025 
+0026 rndIdx = randperm(numel(actModel.mets));
+0027 fieldsToChange = {'mets','metNames','metComps','metFormulas','metMiriams'};
+0028 for i=1:numel(fieldsToChange)
+0029     actModel.(fieldsToChange{i}) = actModel.(fieldsToChange{i})(rndIdx);
+0030 end
+0031 actModel.S     = actModel.S(rndIdx,:);
+0032 
+0033 rndIdx = randperm(numel(actModel.genes));
+0034 fieldsToChange = {'genes','geneShortNames'};
+0035 for i=1:numel(fieldsToChange)
+0036     actModel.(fieldsToChange{i}) = actModel.(fieldsToChange{i})(rndIdx);
+0037 end
+0038 actModel.rxnGeneMat = actModel.rxnGeneMat(:,rndIdx);
+0039 
+0040 rndIdx = randperm(numel(actModel.comps));
+0041 fieldsToChange = {'comps','compNames'};
+0042 for i=1:numel(fieldsToChange)
+0043     actModel.(fieldsToChange{i}) = actModel.(fieldsToChange{i})(rndIdx);
+0044 end
+0045 [~,J]=sort(rndIdx);
+0046 [toreplace, bywhat] = ismember(actModel.metComps,1:length(J));
+0047 actModel.metComps(toreplace) = J(bywhat(toreplace));
+0048 
+0049 %Sort randomly permutated model
+0050 actModel = sortIdentifiers(actModel);
+0051 
+0052 %Check that the actual model is the same as the expected model
+0053 verifyEqual(testCase,actModel,expModel)
+0054 end
+0055 
+0056 function expandModel_and_contractModelTest(testCase)
+0057 %Load the expected model
+0058 sourceDir = fileparts(which(mfilename));
+0059 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
+0060 
+0061 % Note that this does not work any model, as grRules might not be properly
+0062 % sorted (but should still be valid)
+0063 evalc('modelNew = expandModel(model);'); % Suppress warnings about complex grRules
+0064 modelNew = contractModel(modelNew);
+0065 
+0066 verifyEqual(testCase,model,modelNew)
+0067 end
+0068
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/testing/unit_tests/solverTests.html b/doc/testing/unit_tests/solverTests.html new file mode 100644 index 000000000..ef3aee14f --- /dev/null +++ b/doc/testing/unit_tests/solverTests.html @@ -0,0 +1,192 @@ + + + + Description of solverTests + + + + + + + + + +
Home > testing > unit_tests > solverTests.m
+ + + +

solverTests +

+ +

PURPOSE ^

+
run this test case with the command
+ +

SYNOPSIS ^

+
function tests = solverTests
+ +

DESCRIPTION ^

+
run this test case with the command
+results = runtests('solverTests.m')
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 %run this test case with the command
+0002 %results = runtests('solverTests.m')
+0003 function tests = solverTests
+0004 tests = functiontests(localfunctions);
+0005 end
+0006 
+0007 function testGlpk(testCase)
+0008 sourceDir = fileparts(which(mfilename));
+0009 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
+0010 try
+0011     oldSolver=getpref('RAVEN','solver');
+0012 catch
+0013 end
+0014 setRavenSolver('glpk');
+0015 
+0016 try
+0017     evalc('sol=solveLP(model,0);');
+0018 catch
+0019     try
+0020         setRavenSolver(oldSolver);
+0021     catch
+0022         rmpref('RAVEN','solver');
+0023     end
+0024     error('Solver not working')
+0025 end
+0026 try
+0027     setRavenSolver(oldSolver);
+0028 catch
+0029     rmpref('RAVEN','solver');
+0030 end
+0031 
+0032 load([sourceDir,'/test_data/solverTestOutput.mat'], 'solOut');
+0033 %Check that the actual model is the same as the expected model
+0034 verifyEqual(testCase,sol,solOut,'AbsTol',0.1) %Quite generous tolerance, as shadow price calculations fluctuate quite a bit between solvers
+0035 end
+0036 
+0037 function testGurobi(testCase)
+0038 sourceDir = fileparts(which(mfilename));
+0039 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
+0040 try
+0041     oldSolver=getpref('RAVEN','solver');
+0042 catch
+0043 end
+0044 
+0045 setRavenSolver('gurobi');
+0046 
+0047 if exist('gurobi','file')~=3
+0048     error('Gurobi not installed or cannot be found in MATLAB path.')
+0049 else
+0050     try
+0051         % Try all three types of flux minimization
+0052         evalc('sol=solveLP(model,3);');
+0053         evalc('sol=solveLP(model,1);');
+0054         evalc('sol=solveLP(model,0);');
+0055     catch ME
+0056         try
+0057             setRavenSolver(oldSolver);
+0058         catch
+0059             rmpref('RAVEN','solver');
+0060         end
+0061         error(ME.message)
+0062     end
+0063 end
+0064 try
+0065     setRavenSolver(oldSolver);
+0066 catch
+0067     rmpref('RAVEN','solver');
+0068 end
+0069 
+0070 load([sourceDir,'/test_data/solverTestOutput.mat'], 'solOut');
+0071 %Check that the actual model is the same as the expected model
+0072 verifyEqual(testCase,sol,solOut,'AbsTol',0.1)
+0073 end
+0074 
+0075 function testSCIP(testCase)
+0076 if exist('scip','file')~=3
+0077     error('SCIP MEX binary not installed or not functional.')
+0078 end
+0079 sourceDir = fileparts(which(mfilename));
+0080 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
+0081 try
+0082     oldSolver=getpref('RAVEN','solver');
+0083 catch
+0084 end
+0085 setRavenSolver('scip');
+0086 try
+0087     evalc('sol=solveLP(model,0);');
+0088 catch
+0089     try
+0090         setRavenSolver(oldSolver);
+0091     catch
+0092         rmpref('RAVEN','solver');
+0093     end
+0094     error('Solver not working')
+0095 end
+0096 try
+0097     setRavenSolver(oldSolver);
+0098 catch
+0099     rmpref('RAVEN','solver');
+0100 end
+0101 
+0102 load([sourceDir,'/test_data/solverTestOutput.mat'], 'solOutSCIP');
+0103 %Check that the actual model is the same as the expected model
+0104 verifyEqual(testCase,sol,solOutSCIP,'AbsTol',0.1)
+0105 end
+0106 
+0107 function testCobra(testCase)
+0108 if exist('initCobraToolbox.m','file')~=2
+0109     error('COBRA Toolbox not installed or cannot be found in MATLAB path.')
+0110 end
+0111 sourceDir = fileparts(which(mfilename));
+0112 load([sourceDir,'/test_data/ecoli_textbook.mat'], 'model');
+0113 try
+0114     oldSolver=getpref('RAVEN','solver');
+0115 catch
+0116 end
+0117 global CBT_LP_SOLVER
+0118 global CBT_MILP_SOLVER
+0119 CBT_LP_SOLVER = 'glpk';
+0120 CBT_MILP_SOLVER = 'glpk';
+0121 setRavenSolver('cobra');
+0122 
+0123 try
+0124     evalc('sol=solveLP(model,0);');
+0125 catch
+0126     try
+0127         setRavenSolver(oldSolver);
+0128     catch
+0129         rmpref('RAVEN','solver');
+0130     end
+0131     error('Solver not working')
+0132 end
+0133 try
+0134     setRavenSolver(oldSolver);
+0135 catch
+0136     rmpref('RAVEN','solver');
+0137 end
+0138 
+0139 load([sourceDir,'/test_data/solverTestOutput.mat'], 'solOut');
+0140 %Check that the actual model is the same as the expected model
+0141 verifyEqual(testCase,sol,solOut,'AbsTol',0.1)
+0142 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/testing/unit_tests/tinitTests.html b/doc/testing/unit_tests/tinitTests.html new file mode 100644 index 000000000..f699d0e0d --- /dev/null +++ b/doc/testing/unit_tests/tinitTests.html @@ -0,0 +1,665 @@ + + + + Description of tinitTests + + + + + + + + + +
Home > testing > unit_tests > tinitTests.m
+ + + +

tinitTests +

+ +

PURPOSE ^

+
run this test case with the command
+ +

SYNOPSIS ^

+
function tests = tinitTests
+ +

DESCRIPTION ^

+
run this test case with the command
+results = runtests('tinitTests.m')
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + +

SUBFUNCTIONS ^

+ + +

SOURCE CODE ^

+
0001 %run this test case with the command
+0002 %results = runtests('tinitTests.m')
+0003 function tests = tinitTests
+0004 tests = functiontests(localfunctions);
+0005 solverExist = [exist('gurobi','file'), exist('scip.mexw64','file')] ==3;
+0006 if solverExist(1)
+0007     try
+0008         gurobi_read('solverTests.m'); % Random function call
+0009     catch ME
+0010         if ~startsWith(ME.message,'Gurobi error 10012') % Expected error code, others may indicate problems with license
+0011             solverExist(1) = false;
+0012         end
+0013     end
+0014 end
+0015 if all(~solverExist)
+0016     disp('No suitable solver (gurobi or scip) was found, ftINIT tests skipped.')
+0017     skipTests = contains({tests.Name},'ftinit','IgnoreCase',true);
+0018     tests(skipTests) = [];
+0019 end
+0020 end
+0021 
+0022 function testparsexpTask1List(testCase)
+0023 sourceDir = fileparts(which(mfilename));
+0024 taskStruct = parseTaskList(strcat(sourceDir, '/test_data/test_tasks.txt'));
+0025 taskStructExcel = parseTaskList(strcat(sourceDir, '/test_data/test_tasks.xls'));
+0026 %check that all fields in the first line are what we expect
+0027 
+0028 expTask1.id='ER';
+0029 expTask1.description='Aerobic rephosphorylation of ATP from glucose';
+0030 expTask1.shouldFail=true;
+0031 expTask1.printFluxes=true;
+0032 expTask1.comments='Messed up reaction';
+0033 expTask1.inputs={'O2[s]';'glucose[s]'};
+0034 expTask1.LBin=[23.6;23.6];
+0035 expTask1.UBin=[23.8;23.8];
+0036 expTask1.outputs={'H2O[s]';'CO2[s]'};
+0037 expTask1.LBout=[26.1;26.1];
+0038 expTask1.UBout=[26.2;26.2];
+0039 expTask1.equations={'ATP[c] + H2O[c] => ADP[c] + Pi[c] + H+[c]'};
+0040 expTask1.LBequ=30.2;
+0041 expTask1.UBequ=30.6;
+0042 expTask1.changed={'ATP[a] + H2O[a] => ADP[a] + Pi[a] + H+[a]'};
+0043 expTask1.LBrxn=56.2;
+0044 %check that the check works as expected
+0045 verifyNotEqual(testCase,taskStruct(1),expTask1)
+0046 expTask1.UBrxn=60;%now add the last
+0047 
+0048 
+0049 verifyEqual(testCase,taskStruct(1),expTask1)
+0050 verifyEqual(testCase,taskStructExcel(1),expTask1)
+0051 
+0052 %check that we have 2 tasks in total
+0053 verifyEqual(testCase,length(taskStruct),2)
+0054 verifyEqual(testCase,length(taskStructExcel),2)
+0055 
+0056 expTask2.id='BS';
+0057 expTask2.description='ATP de novo synthesis';
+0058 expTask2.shouldFail=false;
+0059 expTask2.printFluxes=false;
+0060 expTask2.comments='';
+0061 expTask2.inputs={'O2[s]';'glucose[s]';'NH3[s]';'Pi[s]'};
+0062 expTask2.LBin=[0;0;0;0];
+0063 expTask2.UBin=[1000;1000;1000;1000];
+0064 expTask2.outputs={'H2O[s]';'CO2[s]';'ATP[c]'};
+0065 expTask2.LBout=[0;0;1];
+0066 expTask2.UBout=[1.1;1.1;1.3];
+0067 expTask2.equations={'ATP[c] + H2O[c] <=> ADP[c] + Pi[c] + H+[c]'};
+0068 expTask2.LBequ=-1000;
+0069 expTask2.UBequ=1000;
+0070 expTask2.changed={};
+0071 expTask2.LBrxn=[];
+0072 expTask2.UBrxn=[];
+0073 
+0074 verifyEqual(testCase,taskStruct(2),expTask2)
+0075 verifyEqual(testCase,taskStructExcel(2),expTask2)
+0076 
+0077 %and, check that the two formats produce the same
+0078 verifyEqual(testCase,taskStruct,taskStructExcel)
+0079 end
+0080 
+0081 
+0082 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+0083 % testModel
+0084 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+0085 
+0086 function testModel = getTstModel()
+0087 testModel = struct();
+0088 testModel.id = 'testModel';
+0089 testModel.rxns = {};
+0090 testModel.S=[];
+0091 testModel.rev=[];
+0092 testModel.mets = {'as';'ac';'bc';'cc';'dc';'ec';'es';'fc'};
+0093 testModel.metNames = {'a';'a';'b';'c';'d';'e';'e';'f'};
+0094 testModel.comps = {'s';'c'};
+0095 testModel.compNames = testModel.comps;
+0096 testModel.metComps = [1;2;2;2;2;2;1;2];
+0097 testModel.genes = {'G1';'G2';'G3';'G4';'G5';'G6';'G7';'G8';'G9';'G10'};
+0098 testModel.grRules = {};
+0099 testModel.rxnGeneMat = [];
+0100 
+0101 rxnsToAdd = struct();
+0102 rxnsToAdd.rxns = {'R1';'R2';'R3';'R4';'R5';'R6';'R7';'R8';'R9';'R10'};
+0103 rxnsToAdd.equations = {'=> a[s]';...
+0104     'a[s] <=> a[c]';...
+0105     'a[c] <=> b[c] + c[c]';...
+0106     'a[c] <=> 2 d[c]';...
+0107     'b[c] + c[c] => e[c]';...
+0108     '2 d[c] => e[c]';...
+0109     'e[c] => e[s]';...
+0110     'e[s] =>';...
+0111     'a[c] <=> f[c]';...
+0112     'f[c] <=> e[c]'};
+0113 rxnsToAdd.grRules = {'';'';'G3';'G4';'G5';'G6';'G7';'';'G9';'G10'};
+0114 testModel = addRxns(testModel,rxnsToAdd, 3);
+0115 testModel.c = [0;0;0;0;0;0;0;1;0;0];%optimize for output flux, if this is used, not sure
+0116 testModel.ub = repmat(1000,10,1);
+0117 testModel.lb = [0;-1000;-1000;-1000;0;0;0;0;-1000;-1000];
+0118 testModel.rxnNames = testModel.rxns;
+0119 testModel.b = repmat(0,8,1);
+0120 end
+0121 
+0122 function testModelRxnScores = getTstModelRxnScores()
+0123 testModelRxnScores = [-2;-2;-1;7;0.5;0.5;-1;-2;-3;3.5];
+0124 end
+0125 
+0126 function testModelTasks = getTstModelTasks()
+0127 testModelTasks = struct();
+0128 testModelTasks.id = 'Gen e[s] from a[s]';
+0129 testModelTasks.description = 'Gen e[s] from a[s]';
+0130 testModelTasks.shouldFail = false;
+0131 testModelTasks.printFluxes = false;
+0132 testModelTasks.comments = '';
+0133 testModelTasks.inputs = {'a[s]'};
+0134 testModelTasks.LBin = 0;
+0135 testModelTasks.UBin = inf;
+0136 testModelTasks.outputs = {'e[s]'};
+0137 testModelTasks.LBout = 1;
+0138 testModelTasks.UBout = 1;
+0139 testModelTasks.equations = {};
+0140 testModelTasks.LBequ = [];
+0141 testModelTasks.UBequ = [];
+0142 testModelTasks.changed = {};
+0143 testModelTasks.LBrxn = {};
+0144 testModelTasks.UBrxn = {};
+0145 end
+0146 
+0147 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+0148 % testModel2 - not used directly for now, but indirectly
+0149 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+0150 
+0151 function testModel2 = getTstModel2()
+0152 testModel2 = struct();
+0153 testModel2.id = 'testModel2';
+0154 testModel2.rxns = {};
+0155 testModel2.S=[];
+0156 testModel2.rev=[];
+0157 testModel2.mets = {'a';'b'};
+0158 testModel2.metNames = {'a';'b'};
+0159 testModel2.comps = {'s'};
+0160 testModel2.compNames = testModel2.comps;
+0161 testModel2.metComps = [1;1];
+0162 testModel2.genes = {'G1';'G2';'G3';'G4'};
+0163 testModel2.grRules = {};
+0164 testModel2.rxnGeneMat = [];
+0165 
+0166 rxnsToAdd = struct();
+0167 rxnsToAdd.rxns = {'R1';'R2';'R3';'R4'};
+0168 rxnsToAdd.equations = {'a[s] <=>';...
+0169     'a[s] => b[s]';...
+0170     'a[s] <=> b[s]';...
+0171     'b[s] =>'};
+0172 rxnsToAdd.grRules = testModel2.genes;
+0173 testModel2 = addRxns(testModel2,rxnsToAdd,3,'',true,true);
+0174 testModel2.c = [0;0;0;1];%optimize for output flux, if this is used, not sure
+0175 testModel2.ub = repmat(1000,4,1);
+0176 testModel2.lb = [-1000;0;-1000;0];
+0177 testModel2.rxnNames = testModel2.rxns;
+0178 testModel2.b = zeros(2,1);
+0179 end
+0180 
+0181 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+0182 % testModel4
+0183 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+0184 
+0185 function testModel4 = getTstModel4()
+0186 testModel2 = getTstModel2();
+0187 testModel4 = testModel2;
+0188 
+0189 rxnsToAdd = struct();
+0190 rxnsToAdd.rxns = {'R5';'R6';'R7';'R8';'R9';'R10';'R11'};
+0191 rxnsToAdd.equations = {'5 a[s] <=> 5 d[s]';...
+0192     'e[s] <=> d[s]';
+0193     'f[s] + g[s] <=> e[s]';
+0194     'b[s] <=> f[s]';
+0195     'h[s] <=> g[s]';
+0196     'h[s] =>';
+0197     'e[s] => g[s]'};
+0198 rxnsToAdd.grRules = {'G5';'G6';'G7';'G8';'G9';'G10';'G11'};
+0199 [~,testModel4] = evalc("addRxns(testModel4,rxnsToAdd, 3, [], true, true);");
+0200 end
+0201 
+0202 function testModel4RxnScores = getTstModel4RxnScores()
+0203 testModel4RxnScores = [-1;-1;2;-1;0.5;-2;1;1.3;-0.5;-0.4;8];
+0204 end
+0205 
+0206 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+0207 % testModel5
+0208 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+0209 
+0210 function testModel5 = getTstModel5()
+0211 testModel = getTstModel();
+0212 
+0213 rxnsToAdd = struct();
+0214 rxnsToAdd.rxns = {'R11';'R12';'R13';'R14'};
+0215 rxnsToAdd.equations = {'a[c] <=> g[c]';...
+0216     'a[c] <=> g[c]';...
+0217     'g[c] <=> e[c]';...
+0218     'g[c] <=> e[c]'};
+0219 rxnsToAdd.grRules = {'G11';'G12';'G13';'G14'};
+0220 [~,testModel5] = evalc("addRxns(testModel,rxnsToAdd, 3, [], true, true);");
+0221 end
+0222 
+0223 function testModel5RxnScores = getTstModel5RxnScores()
+0224 testModel5RxnScores = [getTstModelRxnScores();-1;-1.5;-1;-1.5];
+0225 end
+0226 
+0227 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+0228 %T0001: testModel without tasks
+0229 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+0230 function testftINIT_T0001(testCase)
+0231 solverExist = [exist('gurobi','file'), exist('scip.mexw64','file')] == 3;
+0232 currSolver = getpref('RAVEN','solver');
+0233 if solverExist(1)
+0234     setRavenSolver('gurobi');
+0235 elseif solverExist(2)
+0236     setRavenSolver('scip');
+0237 else
+0238     error('No compatible solvers found');
+0239 end
+0240 %    detectedMets = {};
+0241 testParams = struct();
+0242 
+0243 %    params.TimeLimit = 10;
+0244 
+0245 testModel = getTstModel();
+0246 [~, prepDataTest1] = evalc('prepINITModel(testModel, {}, {}, false, {}, ''s'');');
+0247 %check some things in the prepData
+0248 %1. We expect 3 rxns in origRxnsToZero:
+0249 verifyTrue(testCase, all(strcmp(prepDataTest1.refModel.rxns(prepDataTest1.toIgnoreExch) , {'R1';'R8'})))
+0250 %note that R7 should not be there, since it has a GPR.
+0251 
+0252 arrayData1.genes = testModel.genes;
+0253 arrayData1.tissues = {'a'};
+0254 arrayData1.levels = getExprForRxnScore(getTstModelRxnScores());
+0255 arrayData1.threshold = 1;
+0256 
+0257 [~,tst1ResModel1] = evalc('ftINIT(prepDataTest1,arrayData1.tissues{1},[],[],arrayData1,[],getINITSteps(),true,true,testParams,false);');
+0258 
+0259 %We expect R1 and R8 to be added since they have no GPRs and are exch rxns. The transport rxn R2 without GPR will however be removed,
+0260 %since we in the standard setting run the third step with [1;0;0;0;1;0;0], meaning that such reactions will be removed
+0261 %R7 however will not be added since it has a GPR
+0262 verifyTrue(testCase, all(strcmp(tst1ResModel1.rxns,{'R1';'R4';'R6';'R8';'R9';'R10'})))
+0263 
+0264 %also test spontaneous
+0265 [~, prepDataTest1] = evalc('prepINITModel(testModel, {}, {''R7'';''R10''}, false, {}, ''s'');');
+0266 verifyTrue(testCase, all(strcmp(prepDataTest1.refModel.rxns(prepDataTest1.toIgnoreExch | prepDataTest1.toIgnoreSpont), {'R1';'R7';'R8';'R10'})))
+0267 arrayData1.genes = testModel.genes;
+0268 arrayData1.tissues = {'a'};
+0269 arrayData1.levels = getExprForRxnScore(getTstModelRxnScores());
+0270 arrayData1.threshold = 1;
+0271 [~,tst1ResModel1] = evalc('ftINIT(prepDataTest1,arrayData1.tissues{1},[],[],arrayData1,[],getINITSteps(),true,true,testParams,false);');
+0272 %the model should now change to include the "correct" path (including 'R2') and
+0273 %skip R9/R10:
+0274 verifyTrue(testCase, all(strcmp(tst1ResModel1.rxns,{'R1';'R2';'R4';'R6';'R7';'R8'})), 1)
+0275 setRavenSolver(currSolver);
+0276 end
+0277 
+0278 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+0279 %T0002: Create a task that wants to generate e[s] from a[s] for testModel
+0280 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+0281 function testftINIT_T0002(testCase)
+0282 solverExist = [exist('gurobi','file'), exist('scip.mexw64','file')] ==3;
+0283 currSolver = getpref('RAVEN','solver');
+0284 if solverExist(1)
+0285     setRavenSolver('gurobi');
+0286 elseif solverExist(2)
+0287     setRavenSolver('scip');
+0288 else
+0289     error('No compatible solvers found');
+0290 end
+0291 testModel = getTstModel();
+0292 testModelTasks = getTstModelTasks();
+0293 testRxnScores = getTstModelRxnScores();
+0294 testParams = struct();
+0295 [~, prepDataTest1] = evalc('prepINITModel(testModel, testModelTasks, {}, false, {}, ''s'');');
+0296 %We now expect to R2 and R7 to be essential. Note that R1 and R8 are not essential,
+0297 %the exchange rxns are not used when checking tasks.
+0298 %This is a bit complicated to check, because the essential rxns are expressed
+0299 %as rxn ids of the linearly merged model. We expect those to be called R1 and R7:
+0300 verifyTrue(testCase, all(strcmp(prepDataTest1.essentialRxns,{'R1';'R7'})))
+0301 
+0302 arrayData1.genes = testModel.genes;
+0303 arrayData1.tissues = {'a'};
+0304 arrayData1.levels = getExprForRxnScore(testRxnScores);
+0305 arrayData1.threshold = 1;
+0306 [~,tst1ResModel1] = evalc('ftINIT(prepDataTest1,arrayData1.tissues{1},[],[],arrayData1,[],getINITSteps(),true,true,testParams,false);');
+0307 %Since both R2 and R7 are now essential, we expect all rxns to be on except R3 and
+0308 %R5 (which have a negative total score and are not needed for the task)
+0309 verifyTrue(testCase, all(strcmp(tst1ResModel1.rxns,{'R1';'R2';'R4';'R6';'R7';'R8';'R9';'R10'})))
+0310 setRavenSolver(currSolver);
+0311 end
+0312 
+0313 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+0314 %T0003: The second step - gapfilling
+0315 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+0316 function testftINIT_T0003(testCase)
+0317 %First generate a model with gaps. We can use testModel. First we add
+0318 %boundary mets. Then we remove the exchange reactions
+0319 %(which is required for filling gaps) and create a gap by removing the R7 reaction.
+0320 testModel = getTstModel();
+0321 testModelTasks = getTstModelTasks();
+0322 testRxnScores = getTstModelRxnScores();
+0323 
+0324 mTempRef = closeModel(testModel);
+0325 mTempRef = removeReactions(mTempRef, {'R1';'R8'});
+0326 mTemp = removeReactions(mTempRef, {'R7'});
+0327 mTemp.id = 'tmp';
+0328 tmpRxnScores = testRxnScores([2;3;4;5;6;7;9;10]);
+0329 %now check that R7 is added back
+0330 [~,outModel,addedRxnMat] = evalc('ftINITFillGapsForAllTasks(mTemp,mTempRef,[],false,min(tmpRxnScores,-0.1),testModelTasks);');
+0331 verifyTrue(testCase, all(strcmp(mTempRef.rxns(addedRxnMat),'R7')))%ok
+0332 end
+0333 
+0334 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+0335 %T0004: MergeLinear and groupRxnScores
+0336 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+0337 function testftINIT_T0004(testCase)
+0338 %first testModel
+0339 testModel = getTstModel();
+0340 testRxnScores = getTstModelRxnScores();
+0341 [reducedModel,origRxnIds,groupIds,reversedRxns]=mergeLinear(testModel, {});
+0342 %We expect mergeLinear to merge {R1,R2}, {R3,R5}, {R4,R6}, {R7,R8}, {R9,R10}
+0343 verifyTrue(testCase, all(groupIds == [1;1;2;3;2;3;4;4;5;5]))
+0344 %we expect R1, R3, R4, R7 to be irreversible, R9 to be reversible
+0345 verifyTrue(testCase, all(reducedModel.rev == [0;0;0;0;1]))
+0346 verifyTrue(testCase, all(reducedModel.lb == [0;0;0;0;-1000]))
+0347 
+0348 newRxnScores=groupRxnScores(reducedModel, testRxnScores, origRxnIds, groupIds, ismember(origRxnIds, {'R1';'R2';'R8'}));
+0349 verifyTrue(testCase, all(newRxnScores == [0;-0.5;7.5;-1;0.5]))
+0350 
+0351 %then testModel4
+0352 testModel4 = getTstModel4();
+0353 [reducedModel,origRxnIds,groupIds,reversedRxns]=mergeLinear(testModel4, {});
+0354 %we expect {R5,R6},{R7,R8}, and{R9,R10} to be merged
+0355 verifyTrue(testCase, all(groupIds == [0;0;0;0;1;1;2;2;3;3;0]))
+0356 %check reversibility
+0357 verifyTrue(testCase, all(reducedModel.rev == [1;0;1;0;1;1;0;0]))
+0358 %check that some reactions have flipped direction when turned to irrev
+0359 verifyTrue(testCase, strcmp(constructEquations(reducedModel, 'R9'),'g[s] => '))
+0360 verifyTrue(testCase, all(find(reversedRxns) == [6;9]))
+0361 end
+0362 
+0363 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+0364 %T0006: reverseRxns
+0365 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+0366 
+0367 function testftINIT_T0006(testCase)
+0368 %R1 = '=> a[s]';...
+0369 %R3 = 'a[c] <=> b[c] + c[c]';...
+0370 testModel = getTstModel();
+0371 
+0372 tmpModel = reverseRxns(testModel, {'R1';'R3'});
+0373 res = constructEquations(tmpModel, {'R1';'R3'});
+0374 expRes = {'a[s] => ';'b[c] + c[c] <=> a[c]'};
+0375 verifyTrue(testCase, all(strcmp(res,expRes)))
+0376 end
+0377 
+0378 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+0379 %T0007: rescaleModelForINIT
+0380 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+0381 function testftINIT_T0007(testCase)
+0382 miniModel = struct();
+0383 miniModel.S = [1,1000;-1,-40];
+0384 miniModel.rxns = {'1';'2'};
+0385 miniModel.mets = {'1';'2'};
+0386 res = rescaleModelForINIT(miniModel,10);
+0387 verifyTrue(testCase, abs(res.S(1,2) - res.S(2,2)*-10) < 10^-6)
+0388 verifyTrue(testCase, abs((abs(res.S(1,2)) + abs(res.S(2,2)))/2) - 1 < 10^-6)
+0389 end
+0390 
+0391 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+0392 %T0008: testModel with metabolomics
+0393 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+0394 function testftINIT_T0008(testCase)
+0395 solverExist = [exist('gurobi','file'), exist('scip.mexw64','file')] ==3;
+0396 currSolver = getpref('RAVEN','solver');
+0397 if solverExist(1)
+0398     setRavenSolver('gurobi');
+0399 elseif solverExist(2)
+0400     setRavenSolver('scip');
+0401 else
+0402     error('No compatible solvers found');
+0403 end
+0404 
+0405 testParams = struct();
+0406 
+0407 testModel = getTstModel();
+0408 [~, prepDataTest1] = evalc('prepINITModel(testModel, {}, {}, false, {}, ''s'');');
+0409 
+0410 arrayData1.genes = testModel.genes;
+0411 arrayData1.tissues = {'a'};
+0412 arrayData1.levels = getExprForRxnScore(getTstModelRxnScores());
+0413 arrayData1.threshold = 1;
+0414 
+0415 [~,tst1ResModel1] = evalc('ftINIT(prepDataTest1,arrayData1.tissues{1},[],[],arrayData1,[],getINITSteps(),true,true,testParams,false);');
+0416 
+0417 %First the same as in T0001 (we keep them here to make the test case understandable):
+0418 %We expect R1 and R8 to be added since they have no GPRs and are exch rxns. The transport rxn R2 without GPR will however be removed,
+0419 %since we in the standard setting run the third step with [1;0;0;0;1;0;0], meaning that such reactions will be removed
+0420 %R7 however will not be added since it has a GPR
+0421 verifyTrue(testCase, all(strcmp(tst1ResModel1.rxns,{'R1';'R4';'R6';'R8';'R9';'R10'})))
+0422 
+0423 %make R7 and R10 spontaneous (also same as in T0001)
+0424 [~, prepDataTest1] = evalc('prepINITModel(testModel, {}, {''R7'';''R10''}, false, {}, ''s'');');
+0425 verifyTrue(testCase, all(strcmp(prepDataTest1.refModel.rxns(prepDataTest1.toIgnoreExch | prepDataTest1.toIgnoreSpont), {'R1';'R7';'R8';'R10'})))
+0426 [~,tst1ResModel1] = evalc('ftINIT(prepDataTest1,arrayData1.tissues{1},[],[],arrayData1,[],getINITSteps(),true,true,testParams,false);');
+0427 %the model should now change to include the "correct" path (including 'R2') and
+0428 %skip R9/R10:
+0429 verifyTrue(testCase, all(strcmp(tst1ResModel1.rxns,{'R1';'R2';'R4';'R6';'R7';'R8'})))
+0430 %now, test to add the metabolite f - this should turn back the favor to R9/R10:
+0431 [~,tst1ResModel1] = evalc('ftINIT(prepDataTest1,arrayData1.tissues{1},[],[],arrayData1,{''f''},getINITSteps(),true,true,testParams,false);');
+0432 %R9 should now be included, the presence of R2 is random
+0433 if length(tst1ResModel1.rxns) == 7
+0434     verifyTrue(testCase, all(strcmp(tst1ResModel1.rxns,{'R1';'R4';'R6';'R7';'R8';'R9';'R10'})))
+0435 else
+0436     verifyTrue(testCase, all(strcmp(tst1ResModel1.rxns,{'R1';'R2';'R4';'R6';'R7';'R8';'R9';'R10'})))
+0437 end
+0438 %now, test to add the metabolite a, e, f - this should give the same result:
+0439 [~,tst1ResModel1] = evalc('ftINIT(prepDataTest1,arrayData1.tissues{1},[],[],arrayData1,{''f'';''a'';''e''},getINITSteps(),true,true,testParams,false);');
+0440 %Should be the same as above (R2 is random)
+0441 if length(tst1ResModel1.rxns) == 7
+0442     verifyTrue(testCase, all(strcmp(tst1ResModel1.rxns,{'R1';'R4';'R6';'R7';'R8';'R9';'R10'})))
+0443 else
+0444     verifyTrue(testCase, all(strcmp(tst1ResModel1.rxns,{'R1';'R2';'R4';'R6';'R7';'R8';'R9';'R10'})))
+0445 end
+0446 
+0447 %now, test to add the metabolite b - this should turn on R2 and R3/R5 and turn off R9:
+0448 [~,tst1ResModel1] = evalc('ftINIT(prepDataTest1,arrayData1.tissues{1},[],[],arrayData1,{''b''},getINITSteps(),true,true,testParams,false);');
+0449 verifyTrue(testCase, all(strcmp(tst1ResModel1.rxns,{'R1';'R2';'R3';'R4';'R5';'R6';'R7';'R8'})))
+0450 
+0451 %now on model 5 to test reactions that are not linearly merged (testModel has only merged rxns)
+0452 testModel5 = getTstModel5();
+0453 arrayData1.genes = testModel5.genes;
+0454 arrayData1.tissues = {'a'};
+0455 arrayData1.levels = getExprForRxnScore(getTstModel5RxnScores());
+0456 arrayData1.threshold = 1;
+0457 
+0458 [~, prepDataTest5] = evalc('prepINITModel(testModel5, {}, {''R7'';''R10''}, false, {}, ''s'');');
+0459 [~,tst1ResModel1] = evalc('ftINIT(prepDataTest5,arrayData1.tissues{1},[],[],arrayData1,{},getINITSteps(),true,true,testParams,false);');
+0460 %We expect the 'true' path, i.e. through R2, not R9/R10 or R11-R14
+0461 verifyTrue(testCase, all(strcmp(tst1ResModel1.rxns,{'R1';'R2';'R4';'R6';'R7';'R8'})), 1)
+0462 
+0463 %now add metabolite g
+0464 %modify the scores a bit
+0465 [~, prepDataTest5] = evalc('prepINITModel(testModel5, {}, {''R10''}, false, {}, ''s'');');
+0466 arrayData1.levels(7) = getExprForRxnScore(-1.1); %modify to avoid randomness
+0467 [~,tst1ResModel1] = evalc('ftINIT(prepDataTest5,arrayData1.tissues{1},[],[],arrayData1,{''g''},getINITSteps(),true,true,testParams,false);');
+0468 %We expect R2 to be replaced with R11 and R13
+0469 verifyTrue(testCase, all(strcmp(tst1ResModel1.rxns,{'R1';'R4';'R6';'R8';'R11';'R13'})), 1)
+0470 setRavenSolver(currSolver);
+0471 end
+0472 
+0473 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+0474 %T0009: getExprFromRxnScore
+0475 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+0476 function testftINIT_T0009(testCase)
+0477 testModel = getTstModel();
+0478 [~, prepDataTest1] = evalc('prepINITModel(testModel, {}, {}, false, {}, ''s'');');
+0479 
+0480 arrayData1.genes = testModel.genes;
+0481 arrayData1.tissues = {'a'};
+0482 arrayData1.levels = getExprForRxnScore(getTstModelRxnScores());
+0483 arrayData1.threshold = 1;
+0484 
+0485 rxnScores = scoreComplexModel(prepDataTest1.refModel,[],arrayData1,arrayData1.tissues{1},[]);
+0486 expRes = getTstModelRxnScores();
+0487 verifyTrue(testCase, all(abs(rxnScores - expRes) < 10^-10)) %ok
+0488 end
+0489 
+0490 function testModelL = getTstModelL()
+0491 testModelL = struct();
+0492 testModelL.id = 'testModel';
+0493 testModelL.rxns = {};
+0494 testModelL.S=[];
+0495 testModelL.rev=[];
+0496 testModelL.metNames = {'e1';'e2';'e3';'e4';'e5';'e6';'e7';'e8';'e9';'e1';'e2';'e3';'e4';'e5';'e6';'e7';'e8';'e9';'x1';'x2';'x3';'x4';'x5';'x6';'x7';'x8';'x9';'x10';'x11'};
+0497 testModelL.comps = {'s';'c'};
+0498 testModelL.compNames = testModelL.comps;
+0499 testModelL.metComps = [1;1;1;1;1;1;1;1;1;2;2;2;2;2;2;2;2;2;2;2;2;2;2;2;2;2;2;2;2];
+0500 testModelL.mets = strcat(testModelL.metNames, testModelL.comps(testModelL.metComps));
+0501 
+0502 testModelL.grRules = {};
+0503 testModelL.rxnGeneMat = [];
+0504 
+0505 testModelL.genes = {'Ge1';'Ge2';'Ge4';'Ge5';'Ge7';'Ge9'; 'Gr1';'Gr2';'Gr3';'Gr5';'Gr6';'Gr7';'Gr8';'Gr9';'Gr10';'Gr11';'Gr12';'Gr14';'Gr15'};
+0506 
+0507 testModelL.ub = [];
+0508 testModelL.lb = [];
+0509 
+0510 rxnsToAdd = struct();
+0511 rxnsToAdd.rxns = {  'S1';'S2';'S3';'S4';'S5';'S6';'S7';'S8';'S9';'E1';'E2';'E2b';'E3';'E4';'E5';'E6';'E7';'E8';'E9';'R1';'R2';'R3';'R4';'R5';'R6';'R7';'R8';'R9';'R10';'R11';'R12';'R13';'R14';'R15'};
+0512 rxnsToAdd.grRules = {'';  '';  '';  '';  '';  '';  '';  '';  ''; 'Ge1';'Ge2';'';'';'Ge4';'Ge5';'';'Ge7';'';'Ge9'; 'Gr1';'Gr2';'Gr3';'';'Gr5';'Gr6';'Gr7';'Gr8';'Gr9';'Gr10';'Gr11';'Gr12';'';'Gr14';'Gr15'};
+0513 rxnsToAdd.equations = {'e1[s] <=>';...
+0514     'e2[s] <=>';...
+0515     'e3[s] <=>';...
+0516     'e4[s] <=>';...
+0517     'e5[s] <=>';...
+0518     'e6[s] <=>';...
+0519     'e7[s] <=>';...
+0520     'e8[s] <=>';...
+0521     'e9[s] <=>';...
+0522     'e1[s] <=> e1[c]';...
+0523     'e2[s] <=> e2[c]';...
+0524     'e2[s] <=> e2[c]';... %b variant
+0525     'e3[s] <=> e3[c]';...
+0526     'e4[s] <=> e4[c]';...
+0527     'e5[s] <=> e5[c]';...
+0528     'e6[s] <=> e6[c]';...
+0529     'e7[s] <=> e7[c]';...
+0530     'e8[s] <=> e8[c]';...
+0531     'e9[s] <=> e9[c]';...
+0532     'e1[c] + e2[c] <=> x1[c]';... %R1
+0533     'e1[c] + e3[c] => x2[c] + x3[c]';... %R2
+0534     'e4[c] + x3[c] => x4[c] + x5[c]';... %R3
+0535     'e5[c] + e6[c] + x4[c] => 2 x2[c] + x6[c]';... %R4
+0536     'x1[c] + x2[c] <=> x7[c] + 2 x8[c]';... %R5
+0537     'x2[c] + x8[c] => x3[c] + x9[c]';... %R6
+0538     'x4[c] <=> x9[c]';... %R7
+0539     'x5[c] <=> x9[c]';... %R8
+0540     'x6[c] <=> x10[c]';... %R9
+0541     'x6[c] <=> x11[c]';... %R10
+0542     'x10[c] + 2 x11[c] => e7[c]';... %R11
+0543     'x9[c] + x10[c] <=> e8[c]';... %R12
+0544     'x7[c] + x8[c] + x9[c] => e9[c]';... %R13
+0545     'x6[c] => x9[c]';... %R14
+0546     'x3[c] => x9[c]'... %R15
+0547     };
+0548 testModelL = addRxns(testModelL,rxnsToAdd, 3);
+0549 testModelL.c = [0;0;0;0;0;0;0;1;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0];%optimize for output flux, if this is used, not sure
+0550 testModelL.rxnNames = testModelL.rxns;
+0551 testModelL.b = repmat(0,length(testModelL.mets),1);
+0552 end
+0553 
+0554 function testModelLGeneScores = getTstModelLGeneScores()
+0555 %testModelL.genes = {'Ge1';'Ge2';'Ge4';'Ge5';'Ge7';'Ge9'; 'Gr1';'Gr2';'Gr3';'Gr5';'Gr6';'Gr7';'Gr8';'Gr9';'Gr10';'Gr11';'Gr12';'Gr14';'Gr15'};
+0556 testModelLGeneScores = [3; -1;   8;    6;    -5;    5;     4;    5;    2;    3;    6;    1;    3;    1;    -3;    1;     3;      1;    2];
+0557 end
+0558 
+0559 
+0560 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+0561 %T0050: Test ftINIT on a slightly larger and more complex model
+0562 %       Specifically tests if the three-step variant and the "full"
+0563 %       variant gives similar results
+0564 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+0565 function testftINIT_T0050(testCase)
+0566 solverExist = [exist('gurobi','file'), exist('scip.mexw64','file')] ==3;
+0567 currSolver = getpref('RAVEN','solver');
+0568 if solverExist(1)
+0569     setRavenSolver('gurobi');
+0570 elseif solverExist(2)
+0571     setRavenSolver('scip');
+0572 else
+0573     error('No compatible solvers found');
+0574 end
+0575 
+0576 testModelL = getTstModelL();
+0577 testModelLGeneScores = getTstModelLGeneScores();
+0578 testParams = struct();
+0579 
+0580 arrayDataL = struct();
+0581 arrayDataL.genes = testModelL.genes;
+0582 arrayDataL.tissues = {'t1'};
+0583 arrayDataL.levels = getExprForRxnScore(testModelLGeneScores,1);
+0584 arrayDataL.threshold = 1;
+0585 
+0586 %Run prep data
+0587 [~, prepDataL] = evalc('prepINITModel(testModelL, [], {}, false, {}, ''s'');');
+0588 
+0589 [~,mres] = evalc('ftINIT(prepDataL,arrayDataL.tissues{1},[],[],arrayDataL,[],getINITSteps(),true,true,testParams,false);');
+0590 [~,mres2] = evalc('ftINIT(prepDataL,arrayDataL.tissues{1},[],[],arrayDataL,[],getINITSteps([], ''full''),true,true,testParams,false);');
+0591 
+0592 expResult = {  'S1';'S2';'S3';'S4';'S5';'S6';'S7';'S8';'S9';'E1';'E2';'E3';'E4';'E5';'E6';'E8';'E9';'R1';'R2';'R3';'R4';'R5';'R6';'R7';'R8';'R9';'R12';'R13';'R14';'R15'};
+0593 
+0594 verifyTrue(testCase, all(contains(mres.rxns,expResult)))
+0595 verifyTrue(testCase, all(contains(mres2.rxns,expResult)))
+0596 
+0597 %run the old tINIT version (in Human-GEM)
+0598 %this is just to show that they become different, not really part of the test case
+0599 %paramsL2 = struct();
+0600 %paramsL2.TimeLimit = 1000;
+0601 %testModelL2 = closeModel(testModelL);
+0602 %init_modelOrig = getINITModel2(testModelL2,arrayDataL.tissues{1},[],[],arrayDataL,[],true,[],true,true,[],paramsL2);
+0603 
+0604 %in this call, I have modified the code - the possibility to turn off met secretion + don't allow flux in both directions is not possible.
+0605 %The following line, around line 337, is changed
+0606 %from:
+0607 %[~, deletedRxnsInINIT, metProduction] = runINIT(simplifyModel(cModel),rxnScores,metabolomicsData,essentialRxnsForTasks,0,true,false,params);
+0608 %to:
+0609 %[~, deletedRxnsInINIT, metProduction] = runINIT(simplifyModel(cModel),rxnScores,metabolomicsData,essentialRxnsForTasks,0,false,true,params);
+0610 %init_modelOrigNoSecrOneDirOnly = getINITModel2(testModelL2,arrayDataL.tissues{1},[],[],arrayDataL,[],true,[],true,true,[],paramsL2);
+0611 
+0612 %The models init_modelOrigNoSecrOneDirOnly and mres2 are very similar, (only one exch rxn differ, which is expected)
+0613 %init_modelOrig is quite different, with a lot of gaps, and worse. So, the conclusion is that the new version does a pretty good job.
+0614 setRavenSolver(currSolver);
+0615 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/tutorial/index.html b/doc/tutorial/index.html new file mode 100644 index 000000000..b1ccd2ccc --- /dev/null +++ b/doc/tutorial/index.html @@ -0,0 +1,31 @@ + + + + Index for Directory tutorial + + + + + + + + + + +
< Master indexIndex for tutorial >
+ +

Index for tutorial

+ +

Matlab files in this directory:

+ +
 tutorial1tutorial1
 tutorial2tutorial2
 tutorial2_solutionstutorial2_solutions
 tutorial3tutorial3
 tutorial3_solutionstutorial3_solutions
 tutorial4tutorial4
 tutorial4_solutionstutorial4_solutions
 tutorial5tutorial5
 tutorial6tutorial6
+ +

Other Matlab-specific files in this directory:

+
    +
  • empty.mat
  • iMK1208+suppInfo.mat
  • pathway.mat
  • pcPathway.mat
+ + +
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/tutorial/tutorial1.html b/doc/tutorial/tutorial1.html new file mode 100644 index 000000000..c7483e543 --- /dev/null +++ b/doc/tutorial/tutorial1.html @@ -0,0 +1,194 @@ + + + + Description of tutorial1 + + + + + + + + + +
Home > tutorial > tutorial1.m
+ + + +

tutorial1 +

+ +

PURPOSE ^

+
tutorial1
+ +

SYNOPSIS ^

+
This is a script file.
+ +

DESCRIPTION ^

+
 tutorial1
+   This is a short introduction that shows how to load a genome-scale
+   metabolic model (GEM), set reaction constraints, objective function and
+   perform an optimization through flux balance analysis (FBA). The
+   resulting fluxes are visualized and exported to a PDF file.
+   For a more detailed description of the individual functions, see
+   [raven_directory]/doc/index.html.
+   A GEM for the filamentous fungus Penicillium chrysogenum is used in
+   this tutorial. The model can be found in a Microsoft Excel file under
+   the name "iAL1006 v1.00.xlsx" and in SBML file "iAL1006 v1.00.xml".
+   See Tutorial 1 in "RAVEN tutorials.docx" for more details.
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 % tutorial1
+0002 %   This is a short introduction that shows how to load a genome-scale
+0003 %   metabolic model (GEM), set reaction constraints, objective function and
+0004 %   perform an optimization through flux balance analysis (FBA). The
+0005 %   resulting fluxes are visualized and exported to a PDF file.
+0006 %   For a more detailed description of the individual functions, see
+0007 %   [raven_directory]/doc/index.html.
+0008 %   A GEM for the filamentous fungus Penicillium chrysogenum is used in
+0009 %   this tutorial. The model can be found in a Microsoft Excel file under
+0010 %   the name "iAL1006 v1.00.xlsx" and in SBML file "iAL1006 v1.00.xml".
+0011 %   See Tutorial 1 in "RAVEN tutorials.docx" for more details.
+0012 
+0013 %Import the model from Excel. This function performs a number of checks
+0014 %regarding the model structure (such as for incorrectly written equations
+0015 %or illegal characters). In this structure there is only one warning; that
+0016 %the formula for the metabolite LPE could not be parsed. The "false" flag
+0017 %imports a model with exchange reactions in their "closed" form. This makes
+0018 %the model unsuited for modelling, but it is useful for some quality
+0019 %control steps.
+0020 model=importExcelModel('iAL1006 v1.00.xlsx',false);
+0021 
+0022 %The Excel interface is supposed to work in all the systems (Windows, Unix,
+0023 %macOS), but upon any problems, the model can be imported from SBML format
+0024 %instead. However, in such case the user would not be able to run Tutorials
+0025 %2-4, which involve the editing of Excel files. Run the command below
+0026 %(remove "%" sign) instead, if having such problem:
+0027 %model=importModel('iAL1006 v1.00.xml',false);
+0028 
+0029 %The following function prints some properties of the model. The two "true"
+0030 %flags say that it should also list potential problems such as dead-end
+0031 %reactions or unconnected metabolites.
+0032 printModelStats(model,true,true);
+0033 
+0034 %As can be seen the model contains 1632 reactions, 1395 metabolites and
+0035 %1006 genes
+0036 
+0037 %Most modelling approaches using GEMs are based on the mass balancing
+0038 %around the internal metabolites in the system. However, in order for the
+0039 %system to uptake or excrete metabolites, some metabolites have been
+0040 %defined as "unconstrained". In order to simulate something, those
+0041 %metabolites have to be removed from the model. The function simplifyModel
+0042 %is a general-purpose function for making models smaller. This includes the
+0043 %options such as grouping linear reactions and deleting reactions which
+0044 %cannot carry flux. Here it is chosen to delete the exchange metabolites,
+0045 %all reactions that are constrained to zero (mainly uptake of non-standard
+0046 %carbon sources), and all reactions that cannot carry flux (mainly
+0047 %reactions that were dependent on any of those non-standard carbons
+0048 %sources).
+0049 model=simplifyModel(model,true,false,true,true);
+0050 
+0051 %As can be seen the model now contains only 1305 reactions, 1037
+0052 %metabolites and 1006 genes
+0053 
+0054 %As a first way of validating the model, calculate the theoretical yield of
+0055 %carbon dioxide from glucose. The supplied model already allows for uptake
+0056 %of phosphate, sulfate, NH3, O2 and the co-factor precursors thiamin and
+0057 %pimelate. The setParam function is used for setting constraints,
+0058 %reversibility and objective function coefficients.
+0059 %Set the uptake of glucose to be no more than 1 mmol/gDW/h and no uptake of
+0060 %ethanol.
+0061 model=setParam(model,'ub',{'glcIN' 'etohIN'},[1 0]);
+0062 
+0063 %Set the objective for the simulation to maximize CO2 production
+0064 model=setParam(model,'obj',{'co2OUT'},1);
+0065 
+0066 %The problem can now be solved using linear programming. The solveLP
+0067 %function takes a model and solves the linear programming problem defined
+0068 %by the constraints and the objective value coefficients.
+0069 sol=solveLP(model);
+0070 
+0071 %If everything worked fine one should see a structure that contains the
+0072 %fields .f which is the objective value, .stat which is 1 if the
+0073 %optimization terminated successfully and .x which contains the fluxes
+0074 %through each of the reactions in this particular solution of the problem.
+0075 %sol.x contains 1305 values which makes it rather difficult to interpret. A
+0076 %first approach is to look at only the reactions that transports
+0077 %metabolites in to or out from the system. The printFluxes function prints
+0078 %(parts of) the flux distribution to the console.
+0079 printFluxes(model, sol.x, true, 10^-7); %true means only print exchange fluxes
+0080 
+0081 %One can see that the system took up one unit of glucose and 6 units of O2
+0082 %while producing 6 units of CO2 and 6 units of H2O. To get more detailed
+0083 %insight how this happens, one can use the same function to plot all fluxes
+0084 %(above 10^-7).
+0085 printFluxes(model, sol.x, false, 10^-7);
+0086 
+0087 %The results show many reactions that have -1000 or 1000 flux. This is
+0088 %because there are loops in the solution. In order to clean up the solution
+0089 %one can minimize the sum of all the fluxes. This is done by setting the
+0090 %third flag to solveLP to true (take a look at solveLP, there are other
+0091 %options as well).
+0092 sol=solveLP(model,1);
+0093 printFluxes(model, sol.x, false, 10^-7);
+0094 
+0095 %Now there are much fewer reactions that are active. Some of them will
+0096 %probably appear to be a little "weird" but that is because the ATP and
+0097 %NAD(P)H produced has to go somewhere in order to be mass balanced.
+0098 
+0099 %If one wants to study the growth instead, change the objective to be the
+0100 %production of biomass instead of CO2
+0101 model=setParam(model,'obj',{'bmOUT'},1);
+0102 sol=solveLP(model,1);
+0103 printFluxes(model, sol.x, true, 10^-7);
+0104 
+0105 %The results show that the growth rate is 0.084/h and that the system now
+0106 %also requires sulfate, phosphate, NH3, thiamin and pimelate. Compare this
+0107 %to the growth on ethanol instead of glucose. Use three times the molar
+0108 %flux of ethanol since it contains 2 carbons rather than 6. 'eq' means
+0109 %'equal to' and sets the lower and upper bound to the same value.
+0110 modelETH=setParam(model,'eq',{'glcIN' 'etohIN'},[0 3]);
+0111 solETH=solveLP(modelETH,1);
+0112 printFluxes(modelETH, solETH.x, true, 10^-7);
+0113 
+0114 %Investigate how metabolism changes between the two carbon sources.
+0115 %followChanged takes two flux distributions and lets the user select which
+0116 %reactions should be printed. Here the reactions are shown that differ with
+0117 %more than 50%, has a flux higher than 0.5 mmol/gDW/h and an absolute
+0118 %difference higher than 0.5 mmol/gDW/h.
+0119 followChanged(modelETH,sol.x,solETH.x, 50, 0.5, 0.5);
+0120 
+0121 %There are 65 such reactions. By studying them one can start to get an idea
+0122 %about where the key changes occur. Visualization can help a lot in this
+0123 %regard. One can investigate how ATP metabolism changes by running the
+0124 %following command:
+0125 followChanged(modelETH,sol.x,solETH.x, 30, 0.4, 0.4,{'ATP'});
+0126 
+0127 %See that on glucose ATP is generated in glycolysis but on ethanol it seems
+0128 %to have to do with acetate and so on. This allows the user to look further
+0129 %and further down until one understands the underlying flux redistributions
+0130 %that give rise to different phenotypes.
+0131 
+0132 %The fluxes can also be visualized on a metabolic map. Green corresponds to
+0133 %reactions which are more used for growth on glucose, and red are reactions
+0134 %which are more used for growth on ethanol. Open the "GLCvsETH.pdf" file to
+0135 %be able to zoom in on individual reactions.
+0136 load 'pcPathway.mat' pathway;
+0137 drawMap('Glucose vs ethanol',pathway,model,sol.x,solETH.x,modelETH,'GLCvsETH.pdf',10^-5);
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/tutorial/tutorial2.html b/doc/tutorial/tutorial2.html new file mode 100644 index 000000000..f480bd48a --- /dev/null +++ b/doc/tutorial/tutorial2.html @@ -0,0 +1,73 @@ + + + + Description of tutorial2 + + + + + + + + + +
Home > tutorial > tutorial2.m
+ + + +

tutorial2 +

+ +

PURPOSE ^

+
tutorial2
+ +

SYNOPSIS ^

+
This is a script file.
+ +

DESCRIPTION ^

+
 tutorial2
+   This exercise deals with the a small glycolysis model in RAVEN
+   compatible Excel format and shows the most basic aspects of the
+   stoichiometric modelling. It is shown how to build a simple model from
+   scratch, set parameters and perform simple simulations.
+   See Tutorial 2 in "RAVEN tutorials.docx" for more details.
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 % tutorial2
+0002 %   This exercise deals with the a small glycolysis model in RAVEN
+0003 %   compatible Excel format and shows the most basic aspects of the
+0004 %   stoichiometric modelling. It is shown how to build a simple model from
+0005 %   scratch, set parameters and perform simple simulations.
+0006 %   See Tutorial 2 in "RAVEN tutorials.docx" for more details.
+0007 
+0008 %Import the Excel model into a RAVEN model structure
+0009 smallModel=importExcelModel('empty.xlsx');
+0010 
+0011 %This solves the linear programming problem.
+0012 %NOTE: if sol.f is equal to zero then the problem is not solvable. Ensure
+0013 %that uptake and excretion of all necessary stuff are added to the model
+0014 %and run the solveLP again.
+0015 sol=solveLP(smallModel);
+0016 
+0017 %Print the resulting exchange fluxes
+0018 printFluxes(smallModel,sol.x,true);
+0019 
+0020 %Print all fluxes
+0021 printFluxes(smallModel,sol.x,false,10^-5,[],'%rxnID (%rxnName):\n\t%eqn\n\t%flux\n');
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/tutorial/tutorial2_solutions.html b/doc/tutorial/tutorial2_solutions.html new file mode 100644 index 000000000..1c7a6102f --- /dev/null +++ b/doc/tutorial/tutorial2_solutions.html @@ -0,0 +1,67 @@ + + + + Description of tutorial2_solutions + + + + + + + + + +
Home > tutorial > tutorial2_solutions.m
+ + + +

tutorial2_solutions +

+ +

PURPOSE ^

+
tutorial2_solutions
+ +

SYNOPSIS ^

+
This is a script file.
+ +

DESCRIPTION ^

+
 tutorial2_solutions
+   This script contains the solutions for Tutorial 2, see Tutorial 2 in
+   "RAVEN tutorials.docx" for more details.
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 % tutorial2_solutions
+0002 %   This script contains the solutions for Tutorial 2, see Tutorial 2 in
+0003 %   "RAVEN tutorials.docx" for more details.
+0004 
+0005 %Import the Excel model into a RAVEN model structure
+0006 smallModel=importExcelModel('small.xlsx');
+0007 
+0008 %This solves the linear programming problem.
+0009 %NOTE: if sol.f is equal to zero then the problem is not solvable. Ensure
+0010 %that uptake and excretion of all necessary stuff are added to the model
+0011 %and run the solveLP again.
+0012 sol=solveLP(smallModel);
+0013 
+0014 %Print the resulting exchange fluxes
+0015 printFluxes(smallModel,sol.x,true);
+0016 
+0017 %Print all fluxes
+0018 printFluxes(smallModel,sol.x,false,10^-5,[],'%rxnID (%rxnName):\n\t%eqn\n\t%flux\n');
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/tutorial/tutorial3.html b/doc/tutorial/tutorial3.html new file mode 100644 index 000000000..f4cd9cc9c --- /dev/null +++ b/doc/tutorial/tutorial3.html @@ -0,0 +1,134 @@ + + + + Description of tutorial3 + + + + + + + + + +
Home > tutorial > tutorial3.m
+ + + +

tutorial3 +

+ +

PURPOSE ^

+
tutorial3
+ +

SYNOPSIS ^

+
This is a script file.
+ +

DESCRIPTION ^

+
 tutorial3
+   This exercise shows how to run FBA and minimization of metabolic
+   adjustment (MOMA) simulations and how one can use GEMs as a scaffold
+   for interpreting microarray data. A simplified model of yeast
+   metabolism is used in this approach as an example.
+   See Tutorial 3 in "RAVEN tutorials.docx" for more details.
+
+   It is assumed that the user has already completed Tutorial 2
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 % tutorial3
+0002 %   This exercise shows how to run FBA and minimization of metabolic
+0003 %   adjustment (MOMA) simulations and how one can use GEMs as a scaffold
+0004 %   for interpreting microarray data. A simplified model of yeast
+0005 %   metabolism is used in this approach as an example.
+0006 %   See Tutorial 3 in "RAVEN tutorials.docx" for more details.
+0007 %
+0008 %   It is assumed that the user has already completed Tutorial 2
+0009 
+0010 %Import the Excel model
+0011 model=importExcelModel('smallYeast.xlsx',true);
+0012 
+0013 %Set the upper bound of glucose uptake to 1 and O2 uptake to unlimited
+0014 model=setParam(model,'ub',{'glcIN' 'o2IN'},[1 1000]);
+0015 
+0016 %Set the objective to be ethanol production
+0017 model=setParam(model,'obj',{'ethOUT'},1);
+0018 
+0019 %Solve the model
+0020 sol=solveLP(model);
+0021 
+0022 %Print the resulting exchange fluxes
+0023 printFluxes(model,sol.x,true);
+0024 
+0025 %Compare two flux distributions by loading the map
+0026 load 'pathway.mat' pathway;
+0027 drawMap('Aerobic vs Anaerobic',pathway,model,solA.x,solB.x,[],'mapFBA.pdf',10^-5);
+0028 
+0029 %Run a single gene deletion
+0030 [genes, fluxes, originalGenes, details]=findGeneDeletions(model,'sgd','fba');
+0031 
+0032 %Get the indexes of these reactions
+0033 I=getIndexes(model,{'biomassOUT'},'rxns');
+0034 J=getIndexes(model,{'glyOUT'},'rxns');
+0035 
+0036 okSolutions=find(fluxes(I,:)>10^-2); %Only look at solutions which are still growing
+0037 [maxGlycerol, J]=max(fluxes(J,okSolutions));
+0038 disp(maxGlycerol);
+0039 disp(originalGenes(genes(okSolutions(J),:)));
+0040 
+0041 %Draw map for the ZWF1 deletion strain
+0042 model2=setParam(model,'eq',{'ZWF'},0);
+0043 sol2=solveLP(model2);
+0044 drawMap('ZWF1 deletion vs WT',pathway,model,sol.x,sol2.x,[],'mapZWF.pdf',10^-5);
+0045 followChanged(model,sol2.x,sol.x, 10, 10^-2, 0,{'NADPH' 'NADH' 'NAD' 'NADP'});
+0046 
+0047 %Import the model
+0048 SBMLFromExcel('smallYeast.xlsx','smallYeast.xml')
+0049 model=importModel('smallYeast.xml',true);
+0050 sol=solveLP(model);
+0051 
+0052 %Define another model where all exchange reactions are open
+0053 model2=model;
+0054 I=getIndexes(model,getExchangeRxns(model),'rxns');
+0055 model2.lb(I)=0;
+0056 model2.ub(I)=1000;
+0057 
+0058 %Delete ZWF gene
+0059 model2=setParam(model2,'eq',{'ZWF'},0);
+0060 
+0061 %Run MOMA
+0062 [fluxA, fluxB, flag]=qMOMA(model,model2);
+0063 drawMap('Aerobic vs Anaerobic MOMA',pathway,model,fluxA,fluxB,[],'mapMOMA.pdf',10^-5);
+0064 
+0065 %Read microarray results and calculate reporter metabolites (metabolites
+0066 %around which there are significant transcriptional changes)
+0067 [orfs, pvalues]=textread('expression.txt','%s%f');
+0068 repMets=reporterMetabolites(model,orfs,pvalues);
+0069 [I, J]=sort(repMets.metPValues);
+0070 
+0071 fprintf('TOP 10 REPORTER METABOLITES:\n');
+0072 for i=1:min(numel(J),10)
+0073     fprintf([repMets.mets{J(i)} '\t' num2str(I(i)) '\n']);
+0074 end
+0075 
+0076 %Get all reactions involving those metabolites and display them on a map
+0077 mets=ismember(model.mets,repMets.mets(J(1:10)));
+0078 [~, I]=find(model.S(mets,:));
+0079 pathway=trimPathway(pathway, model.rxns(I), true);
+0080 drawMap('Reactions involving the top 10 Reporter Metabolites',pathway,model,ones(numel(model.rxns),1),zeros(numel(model.rxns),1),[],'mapRM.pdf',10^-5);
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/tutorial/tutorial3_solutions.html b/doc/tutorial/tutorial3_solutions.html new file mode 100644 index 000000000..2aa5cfdfa --- /dev/null +++ b/doc/tutorial/tutorial3_solutions.html @@ -0,0 +1,166 @@ + + + + Description of tutorial3_solutions + + + + + + + + + +
Home > tutorial > tutorial3_solutions.m
+ + + +

tutorial3_solutions +

+ +

PURPOSE ^

+
tutorial3_solutions
+ +

SYNOPSIS ^

+
This is a script file.
+ +

DESCRIPTION ^

+
 tutorial3_solutions
+   This script contains the solutions for Tutorial 3, see Tutorial 3 in
+   "RAVEN tutorials.docx" for more details. All the parameters are set in
+   this script, rather than modifying the Excel model file.
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 % tutorial3_solutions
+0002 %   This script contains the solutions for Tutorial 3, see Tutorial 3 in
+0003 %   "RAVEN tutorials.docx" for more details. All the parameters are set in
+0004 %   this script, rather than modifying the Excel model file.
+0005 
+0006 %Import the Excel model
+0007 model=importExcelModel('smallYeast.xlsx',true);
+0008 
+0009 %Step 1
+0010 %Set the upper bound of glucose uptake to 1 and O2 uptake to zero
+0011 model=setParam(model,'ub',{'glcIN' 'o2IN'},[1 0]);
+0012 
+0013 %Set the objective to be ATP hydrolysis
+0014 model=setParam(model,'obj',{'ATPX'},1);
+0015 
+0016 %Solve the model
+0017 sol=solveLP(model);
+0018 
+0019 %Print the resulting fluxes. The ATP production rate should be 2.0. It was
+0020 %4.0 in Tutorial 2, but there sucrose was used instead of glucose.
+0021 printFluxes(model,sol.x,false);
+0022 
+0023 %Step 2
+0024 %Check the yield of different products and print the results
+0025 %Change to fully aerobic
+0026 model=setParam(model,'ub',{'glcIN' 'o2IN'},[1 1000]);
+0027 model=setParam(model,'obj',{'ethOUT'},1);
+0028 sol=solveLP(model);
+0029 fprintf(['Yield of ethanol is ' num2str(sol.f) ' mol/mol\n']);
+0030 model=setParam(model,'obj',{'acOUT'},1);
+0031 sol=solveLP(model);
+0032 fprintf(['Yield of acetate is ' num2str(sol.f) ' mol/mol\n']);
+0033 model=setParam(model,'obj',{'glyOUT'},1);
+0034 sol=solveLP(model);
+0035 fprintf(['Yield of glycerol is ' num2str(sol.f) ' mol/mol\n']);
+0036 model=setParam(model,'obj',{'biomassOUT'},1);
+0037 sol=solveLP(model);
+0038 fprintf(['Yield of biomass is ' num2str(sol.f) '/h\n']);
+0039 
+0040 %Step 3
+0041 %Solve for both aerobic and anaerobic growth
+0042 solA=solveLP(model);
+0043 model=setParam(model,'ub',{'o2IN'},0.5);
+0044 solB=solveLP(model);
+0045 
+0046 %Plot the differences
+0047 %Load the map
+0048 load 'pathway.mat' pathway;
+0049 drawMap('Aerobic vs Anaerobic',pathway,model,solA.x,solB.x,[],'mapFBA.pdf',10^-5);
+0050 
+0051 %Step 4
+0052 %Change to anaerobic growth and maximize for biomass
+0053 model=setParam(model,'eq',{'o2IN'},0);
+0054 model=setParam(model,'obj',{'biomassOUT'},1);
+0055 sol=solveLP(model);
+0056 printFluxes(model,sol.x,true);
+0057 %One can see that the model predicts a glycerol production of 0.23
+0058 %mmol/gDW/h
+0059 
+0060 %Run a single gene deletion
+0061 [genes, fluxes, originalGenes, details]=findGeneDeletions(model,'sgd','fba');
+0062 
+0063 %Get the indexes of these reactions
+0064 I=getIndexes(model,{'biomassOUT'},'rxns');
+0065 J=getIndexes(model,{'glyOUT'},'rxns');
+0066 
+0067 okSolutions=find(fluxes(I,:)>10^-2); %Only look at solutions which are still growing
+0068 [maxGlycerol, J]=max(fluxes(J,okSolutions));
+0069 fprintf(['Glycerol production is ' num2str(maxGlycerol) ' after deletion of ' originalGenes{genes(okSolutions(J),:)} '\n']);
+0070 
+0071 %The best gene deletion corresponds to turning off the ZWF1 reaction
+0072 %(YNL241C)
+0073 model2=setParam(model,'eq',{'ZWF'},0);
+0074 sol2=solveLP(model2);
+0075 drawMap('ZWF1 deletion vs WT',pathway,model,sol2.x,sol.x,[],'mapZWF.pdf',10^-5);
+0076 followChanged(model,sol2.x,sol.x, 10, 10^-2, 0,{'NADPH' 'NADH' 'NAD' 'NADP'});
+0077 
+0078 %Step 5
+0079 %Set the exchange rates to the recorded batch values
+0080 model=setParam(model,'lb',{'acOUT' 'biomassOUT' 'co2OUT' 'ethOUT' 'glyOUT' 'glcIN' 'o2IN' 'ethIN'},[0 0.67706 22.4122 19.0946 1.4717 15 1.6 0]*0.9999);
+0081 model=setParam(model,'ub',{'acOUT' 'biomassOUT' 'co2OUT' 'ethOUT' 'glyOUT' 'glcIN' 'o2IN' 'ethIN'},[0 0.67706 22.4122 19.0946 1.4717 15 1.6 0]*1.0001);
+0082 
+0083 %Define another model where all exchange reactions are open.
+0084 model2=model;
+0085 I=getIndexes(model,getExchangeRxns(model),'rxns');
+0086 model2.lb(I)=0;
+0087 model2.ub(I)=1000;
+0088 
+0089 %Delete ZWF gene
+0090 model2=setParam(model2,'eq',{'ZWF'},0);
+0091 
+0092 %Run MOMA
+0093 [fluxA, fluxB, flag]=qMOMA(model,model2);
+0094 drawMap('ZWF deletion vs wild type',pathway,model,fluxB,fluxA,[],'mapMOMA.pdf',10^-5);
+0095 
+0096 %As one can see, the glycerol production is higher in the deletion strain.
+0097 %Note that this is without any objectives, just by trying to maintain the
+0098 %cells original flux distribution.
+0099 
+0100 %Step 6
+0101 %Read microarray results and calculate reporter metabolites (metabolites
+0102 %around which there are significant transcriptional changes)
+0103 [orfs, pvalues]=textread('expression.txt','%s%f');
+0104 repMets=reporterMetabolites(model,orfs,pvalues);
+0105 [I, J]=sort(repMets.metPValues);
+0106 
+0107 fprintf('TOP 10 REPORTER METABOLITES:\n');
+0108 for i=1:min(numel(J),10)
+0109     fprintf([repMets.mets{J(i)} '\t' num2str(I(i)) '\n']);
+0110 end
+0111 
+0112 %Get all reactions involving those metabolites and display them on a map
+0113 mets=ismember(model.mets,repMets.mets(J(1:10)));
+0114 [~, I]=find(model.S(mets,:));
+0115 pathway=trimPathway(pathway, model.rxns(I), true);
+0116 drawMap('Reactions involving the top 10 Reporter Metabolites',pathway,model,ones(numel(model.rxns),1),zeros(numel(model.rxns),1),[],'mapRM.pdf',10^-5);
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/tutorial/tutorial4.html b/doc/tutorial/tutorial4.html new file mode 100644 index 000000000..6f3e8a77f --- /dev/null +++ b/doc/tutorial/tutorial4.html @@ -0,0 +1,84 @@ + + + + Description of tutorial4 + + + + + + + + + +
Home > tutorial > tutorial4.m
+ + + +

tutorial4 +

+ +

PURPOSE ^

+
tutorial4
+ +

SYNOPSIS ^

+
This is a script file.
+ +

DESCRIPTION ^

+
 tutorial4
+   This script contains the list of functions necessary for running
+   Tutorial 4, see Tutorial 4 in "RAVEN tutorials.docx" for more details.
+   Several key stages may be missing, try to fill these gaps before
+   checking the solutions in tutorial4_solutions. It is assumed that the
+   user is somewhat familiar with linear programming.
+
+   It is assumed that the user has already completed Tutorials 2-3
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 % tutorial4
+0002 %   This script contains the list of functions necessary for running
+0003 %   Tutorial 4, see Tutorial 4 in "RAVEN tutorials.docx" for more details.
+0004 %   Several key stages may be missing, try to fill these gaps before
+0005 %   checking the solutions in tutorial4_solutions. It is assumed that the
+0006 %   user is somewhat familiar with linear programming.
+0007 %
+0008 %   It is assumed that the user has already completed Tutorials 2-3
+0009 
+0010 %Import the Excel model
+0011 model=importExcelModel('smallYeastBad.xlsx');
+0012 model.b=[model.b inf(numel(model.b),1)];
+0013 sol=solveLP(model,1);
+0014 printFluxes(model,sol.x,false,10^-5,[],'%rxnID (%rxnName):\n\t%eqn\n\t%flux\n');
+0015 I=canConsume(model);
+0016 disp(model.mets(I));
+0017 gapReport(model,{refModel});
+0018 
+0019 model=importExcelModel('smallYeastBad2.xlsx');
+0020 [reducedModel, deletedReactions, deletedMetabolites]=simplifyModel(model,false,false,false,true);
+0021 disp(deletedReactions);
+0022 disp(deletedMetabolites);
+0023 [notProducedMets, ~, neededForProductionMat, minToConnect]=checkProduction(model,true,model.comps,false);
+0024 disp(minToConnect);
+0025 
+0026 refModel=importExcelModel('smallYeast.xlsx');
+0027 [newConnected, cannotConnect, addedRxns, newModel]=fillGaps(model,{refModel},false);
+0028 disp(addedRxns);
+0029 disp(newConnected);
+0030 disp(cannotConnect);
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/tutorial/tutorial4_solutions.html b/doc/tutorial/tutorial4_solutions.html new file mode 100644 index 000000000..74c15ea0b --- /dev/null +++ b/doc/tutorial/tutorial4_solutions.html @@ -0,0 +1,207 @@ + + + + Description of tutorial4_solutions + + + + + + + + + +
Home > tutorial > tutorial4_solutions.m
+ + + +

tutorial4_solutions +

+ +

PURPOSE ^

+
tutorial4_solutions
+ +

SYNOPSIS ^

+
This is a script file.
+ +

DESCRIPTION ^

+
 tutorial4_solutions
+   This script contains the solutions for Tutorial 4, see Tutorial 4 in
+   "RAVEN tutorials.docx" for more details.
+
+   NOTE: Many of these changes are easier to do in the Excel sheet. They
+   are done here in code just to avoid having several model files.
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 % tutorial4_solutions
+0002 %   This script contains the solutions for Tutorial 4, see Tutorial 4 in
+0003 %   "RAVEN tutorials.docx" for more details.
+0004 %
+0005 %   NOTE: Many of these changes are easier to do in the Excel sheet. They
+0006 %   are done here in code just to avoid having several model files.
+0007 
+0008 %Import the Excel model
+0009 model=importExcelModel('smallYeastBad.xlsx');
+0010 
+0011 %Close all uptake and maximize for production
+0012 model=setParam(model,'eq',{'glcIN', 'o2IN'},[0 0]);
+0013 model=setParam(model,'obj',{'acOUT' 'biomassOUT' 'co2OUT' 'ethOUT' 'glyOUT'},[1 1 1 1 1]);
+0014 sol=solveLP(model);
+0015 printFluxes(model,sol.x,true); %Nothing produced, good
+0016 
+0017 %Add some fake reactions
+0018 rxns.rxns={'FREE_ATP';'FREE_NADH';'FREE_NADPH'};
+0019 rxns.equations={'ATP <=> ADP + phosphate';'NAD(+) <=> NADH';'NADP(+) <=> NADPH'};
+0020 model=addRxns(model,rxns,2,'c');
+0021 sol=solveLP(model,1);
+0022 
+0023 %Lots of ethanol produced. Also plot the equations to make the error easier
+0024 %to find
+0025 printFluxes(model,sol.x,false,[],[],'%rxnID (%rxnName):%flux\n\t%eqn\n');
+0026 
+0027 %See that ADH1 should only produce one unit of ethanol. Change the reaction
+0028 %equation
+0029 model=changeRxns(model,'ADH1','acetaldehyde[c] + NADH[c] => ethanol[c] + NAD(+)[c]',3);
+0030 sol=solveLP(model,1);
+0031 printFluxes(model,sol.x,true); %Nothing produced, good
+0032 
+0033 %Add excretion of all metabolites
+0034 model.b=[model.b inf(numel(model.b),1)];
+0035 sol=solveLP(model,1);
+0036 printFluxes(model,sol.x,false,10^-5,[],'%rxnID (%rxnName):\n\t%eqn\n\t%flux\n');
+0037 
+0038 %By looking at the reactions which were unbalanced and that were in the
+0039 %flux list one can see that FBP should be changed to result in only one unit
+0040 %of F6P
+0041 model=changeRxns(model,'FBP','beta-D-fructofuranose 1,6-bisphosphate[c] => beta-D-fructofuranose 6-phosphate[c] + phosphate[c]',3);
+0042 sol=solveLP(model,1);
+0043 printFluxes(model,sol.x,false,10^-5,[],'%rxnID (%rxnName):\n\t%eqn\n\t%flux\n');
+0044 
+0045 %The same thing again and one should change PFK to only give one unit of
+0046 %F16P
+0047 model=changeRxns(model,'PFK','ATP[c] + beta-D-fructofuranose 6-phosphate[c] => ADP[c] + beta-D-fructofuranose 1,6-bisphosphate[c]',3);
+0048 sol=solveLP(model,1);
+0049 printFluxes(model,sol.x,false,10^-5,[],'%rxnID (%rxnName):\n\t%eqn\n\t%flux\n'); %Now it works
+0050 
+0051 %Set all uptakes and production to 0
+0052 model=setParam(model,'eq',getExchangeRxns(model),0);
+0053 
+0054 %Since it is checked which metabolites could be consumed without
+0055 %production, one can no longer have free production of all metabolites
+0056 model.b=model.b(:,1);
+0057 I=canConsume(model);
+0058 disp(model.mets(I)); %These 12 metabolites can be consumed without any production
+0059 
+0060 %Allow all uptake
+0061 model.b=[ones(numel(model.b),1)*-1000 model.b];
+0062 
+0063 %Pick CO2 and force uptake of it
+0064 model=setParam(model,'eq',{'co2OUT'},-1); %Negative output means input
+0065 sol=solveLP(model);
+0066 printFluxes(model,sol.x,false,10^-5,[],'%rxnID (%rxnName):\n\t%eqn\n\t%flux\n'); %Now it works
+0067 
+0068 %See that PDC converts pyruvate (3 carbons) to acetaldehyde (2 carbons)
+0069 %without any other products. If one googles, one may realize that CO2 is
+0070 %missing. This would be simpler to change in the Excel file (or using
+0071 %changeRxns), but one can change it here as an exercise. One therefore
+0072 %needs to find the index of the reactions and the index of cytosolic CO2 in
+0073 %order to change the reaction
+0074 Irxn=ismember(model.rxns,'PDC');
+0075 Imet=ismember(model.mets,'CO2_c');
+0076 model.S(Imet,Irxn)=1; %The coefficient is 1.0
+0077 
+0078 %Display the new equation just to be sure
+0079 constructEquations(model,Irxn)
+0080 
+0081 %The solution is now not feasible, meaning that it is no longer possible to
+0082 %force uptake of CO2 without any output
+0083 sol=solveLP(model);
+0084 
+0085 %***Second part of tutorial
+0086 model=importExcelModel('smallYeastBad2.xlsx',true,false,true); %This has to be loaded with the setting to ignore error or it would find the error
+0087 [reducedModel, deletedReactions, deletedMetabolites]=simplifyModel(model,false,false,false,true);
+0088 disp(deletedReactions);
+0089 disp(deletedMetabolites);
+0090 
+0091 %It turned out that G15L_c was spelled G15Lc in one reaction. The best
+0092 %solution would be just to change it in the reaction list and remove the
+0093 %duplicate metabolite, but one can do it here as an exercise. The indexes
+0094 %of the two metabolites are needed.
+0095 Igood=ismember(model.mets,'G15L_c');
+0096 Ibad=ismember(model.mets,'G15Lc');
+0097 
+0098 %Get all reactions and the coefficients in which the wrong one participates
+0099 %move them to be for the right one instead
+0100 model.S(Igood,:)=model.S(Igood,:)+model.S(Ibad,:);
+0101 
+0102 %Delete the bad one
+0103 model=removeMets(model,'G15Lc');
+0104 [reducedModel, deletedReactions, deletedMetabolites]=simplifyModel(model,false,false,false,true);
+0105 disp(deletedReactions);
+0106 disp(deletedMetabolites);
+0107 
+0108 %The only difference was that there were 20 deleted metabolites instead of
+0109 %21. Nothing too spectacular. Check production can tell the user what one
+0110 %needs to connect.
+0111 [notProducedMets, ~, neededForProductionMat, minToConnect]=checkProduction(model,true,model.comps,false);
+0112 
+0113 %In order to have production of all 54 metabolites one needs to enable
+0114 %production of these 12. This small model does not include net synthesis of
+0115 %co-factors, so one should concentrate on the other ones. Glycerone
+0116 %phosphate allows for connection 18 others, so it seems like a good target.
+0117 disp(minToConnect);
+0118 
+0119 %If one googles around a little bit, and knows the metabolism, one would
+0120 %find that DHAP (dihydroxyacetone) and GLYP (glycerone phosphate) are
+0121 %actually synonymes. Only use DHAP
+0122 Igood=ismember(model.mets,'DHAP_c');
+0123 Ibad=ismember(model.mets,'GLYP_c');
+0124 
+0125 %Get all reactions and the coefficients in which the wrong one participates
+0126 %move them to be for the right one instead
+0127 model.S(Igood,:)=model.S(Igood,:)+model.S(Ibad,:);
+0128 
+0129 %Delete the bad one
+0130 model=removeMets(model,'GLYP_c');
+0131 [reducedModel, deletedReactions, deletedMetabolites]=simplifyModel(model,false,false,false,true);
+0132 disp(deletedReactions);
+0133 disp(deletedMetabolites);
+0134 [notProducedMets, ~, neededForProductionMat, minToConnect]=checkProduction(model,true,model.comps,false);
+0135 disp(minToConnect);
+0136 
+0137 %Still quite a lot of gaps and no immediate way to fix it. One could try
+0138 %including reactions from a reference network and see if that helps. Use
+0139 %the small yeast model from Tutorial 3
+0140 refModel=importExcelModel('smallYeast.xlsx');
+0141 [newConnected, cannotConnect, addedRxns, newModel]=fillGaps(model,{refModel},false);
+0142 disp(addedRxns);
+0143 disp(newConnected);
+0144 
+0145 %By including the ALD6 reaction from the reference model it was possible to
+0146 %connect 21 reactions
+0147 [reducedModel, deletedReactions, deletedMetabolites]=simplifyModel(newModel,false,false,false,true);
+0148 disp(deletedMetabolites);
+0149 disp(deletedReactions);
+0150 
+0151 %All the model seems to be connected
+0152 
+0153 %All this stuff may be done in a more automated manner as well
+0154 model=importExcelModel('smallYeastBad2.xlsx',true,false,true);
+0155 gapReport(model,{refModel});
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/tutorial/tutorial5.html b/doc/tutorial/tutorial5.html new file mode 100644 index 000000000..cd50311e9 --- /dev/null +++ b/doc/tutorial/tutorial5.html @@ -0,0 +1,252 @@ + + + + Description of tutorial5 + + + + + + + + + +
Home > tutorial > tutorial5.m
+ + + +

tutorial5 +

+ +

PURPOSE ^

+
tutorial5
+ +

SYNOPSIS ^

+
This is a script file.
+ +

DESCRIPTION ^

+
 tutorial5
+   This exercise is about creating a model from KEGG, based on protein
+   sequences in a FASTA file, and doing some functionality checks on the
+   model. The example case is for the yeast Saccharomyces cerevisiae. This
+   tutorial is more of a showcase than the previous four, and its main
+   purpose is to serve as a scaffold to reconstruct a GEM for any
+   organism.
+   This refers to Tutorial 5 from "RAVEN tutorials.docx"
+ 
+ Start by downloading trained Hidden Markov Models for eukaryotes. This can
+ be done automatically or manually from the RAVEN Wiki in its GitHub
+ repository. In this tutorial, the archive "euk90_kegg105" is picked for
+ the automatic download. See the documentation in the RAVEN Wiki for more
+ information regarding preparation of such archive.
+ 
+ This creates a model for S. cerevisiae. The parameters are set to exclude
+ general or unclear reactions and reactions with undefined stoichiometry.
+ Type "help getKEGGModelForOrganism" to see what the different parameters
+ are for. This process takes up to 20-35 minutes in macOS, Unix systems and
+ 40-55 minutes in Windows, depending on your hardware and the size of
+ target organism proteome
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 % tutorial5
+0002 %   This exercise is about creating a model from KEGG, based on protein
+0003 %   sequences in a FASTA file, and doing some functionality checks on the
+0004 %   model. The example case is for the yeast Saccharomyces cerevisiae. This
+0005 %   tutorial is more of a showcase than the previous four, and its main
+0006 %   purpose is to serve as a scaffold to reconstruct a GEM for any
+0007 %   organism.
+0008 %   This refers to Tutorial 5 from "RAVEN tutorials.docx"
+0009 %
+0010 % Start by downloading trained Hidden Markov Models for eukaryotes. This can
+0011 % be done automatically or manually from the RAVEN Wiki in its GitHub
+0012 % repository. In this tutorial, the archive "euk90_kegg105" is picked for
+0013 % the automatic download. See the documentation in the RAVEN Wiki for more
+0014 % information regarding preparation of such archive.
+0015 %
+0016 % This creates a model for S. cerevisiae. The parameters are set to exclude
+0017 % general or unclear reactions and reactions with undefined stoichiometry.
+0018 % Type "help getKEGGModelForOrganism" to see what the different parameters
+0019 % are for. This process takes up to 20-35 minutes in macOS, Unix systems and
+0020 % 40-55 minutes in Windows, depending on your hardware and the size of
+0021 % target organism proteome
+0022 model=getKEGGModelForOrganism('sce','sce.fa','euk90_kegg105','output',false,false,false,false,10^-30,0.8,0.3,-1);
+0023 
+0024 % The resulting model should contain around 1589 reactions, 1600
+0025 % metabolites and 836 genes. Small variations are possible since it is an
+0026 % heuristic algorithm and different KEGG versions will give slightly
+0027 % different results.
+0028 disp(model);
+0029 
+0030 % A first control is that the model should not be able to produce any
+0031 % metabolites without uptake of some metabolites. This commonly happens when
+0032 % metabolites have a different meaning in different reactions. The best way
+0033 % to find such reactions is to run makeSomething and analyze the resulting
+0034 % solution for bad reactions. An automated approach is to use removeBadRxns,
+0035 % which tries to do the same thing in an automated manner. Type
+0036 % "help removeBadRxns" for details.
+0037 [newModel, removedRxns]=removeBadRxns(model);
+0038 
+0039 % One can see an error about that H+ can be made even if no reactions were
+0040 % unbalanced. Protons are particularly problematic since it is rather
+0041 % arbitary at which pH the formulas are written for. For the purpose of this
+0042 % analysis, the protons can be ignored and fixed later.
+0043 [newModel, removedRxns]=removeBadRxns(model,1,{'H+'},true);
+0044 
+0045 % Only one reaction was removed because it enabled the model to produce
+0046 % something from nothing. Since it is only one reaction, it might be
+0047 % worthwhile to look into this in more detail.
+0048 disp(removedRxns);
+0049 
+0050 % According to the information in KEGG about this reaction it is a general
+0051 % polymer reaction. One might want to look at the flux distributions
+0052 % in more detail to try to find out if there is any better alternative to
+0053 % delete. Use makeSomething to do this.
+0054 [fluxes, metabolite]=makeSomething(model,{'H+'},true);
+0055 model.metNames(metabolite)
+0056 
+0057 % The model could produce H2O using the following reactions
+0058 printFluxes(model, fluxes, false, [], [],'%rxnID (%rxnName):\n\t%eqn: %flux\n')
+0059 
+0060 % That resulted in quite a lot of fluxes to look through. Maybe it is easier
+0061 % if the elementally balanced reactions are excluded.
+0062 balanceStructure=getElementalBalance(model);
+0063 
+0064 % The hydrogen balancing is a bit tricky, so this time it seems more
+0065 % relevant to only look at the ones unbalanced for oxygen (since water was
+0066 % produced)
+0067 goodOnes=balanceStructure.leftComp(:,6)==balanceStructure.rightComp(:,6);
+0068 printFluxes(removeReactions(model,goodOnes), fluxes(~goodOnes), false, [], [],'%rxnID (%rxnName):\n\t%eqn: %flux\n');
+0069 
+0070 % There is still a good number of reactions. Leave only the reactions which
+0071 % involve amylose or starch, from one of the problematic reactions that was
+0072 % identified earlier.
+0073 printFluxes(model, fluxes, false, [], [],'%rxnID (%rxnName):\n\t%eqn: %flux\n',{'Amylose';'Starch'});
+0074 
+0075 % There are two elementally unbalanced reactions, including, the reaction
+0076 % which was identified by removeBadRxns. When looking to these reactions
+0077 % closer, one can notice the contradiction between the reactions. The first
+0078 % one shows that amylose and starch are interconvertible, while the second
+0079 % reaction shows that amylose contains one less glucose unit than starch.
+0080 % This type of general reactions are problematic and should be fixed
+0081 % manually. It is hereby chosen to trust removeBadRxns and delete R02110.
+0082 model=removeReactions(model,'R02110');
+0083 
+0084 % The model can no longer make something from nothing. Can it consume
+0085 % something without any output?
+0086 [solution, metabolite]=consumeSomething(model,{'H+'},true);
+0087 model.metNames(metabolite)
+0088 
+0089 % Nope, so that was good. Add some uptakes and see what it can produce.
+0090 [~, J]=ismember({'D-Glucose';'H2O';'Orthophosphate';'Oxygen';'NH3';'Sulfate'},model.metNames);
+0091 [model, addedRxns]=addExchangeRxns(model,'in',J);
+0092 
+0093 % Check which metabolites can be produced given these uptakes. The
+0094 % canProduce function allows for output of all metabolites. This will not
+0095 % happen in the real cell, but it is very useful for functionality testing
+0096 % of the model. Once it is functional, the excretion reactions based on
+0097 % evidence can be added as well.
+0098 I=canProduce(model);
+0099 
+0100 fprintf('%d%%\n', round(sum(I)/numel(model.mets)*100));
+0101 % It seems that around 31% of the metabolites could be synthesized. It is
+0102 % not directly clear whether this is a high or low number, many metabolites
+0103 % should not be possible to synthesize from those simple precursors.
+0104 
+0105 % Try to fill gaps using the full KEGG model to see if that gives a
+0106 % significantly higher number
+0107 keggModel=getModelFromKEGG([],false,false,false,false);
+0108 
+0109 % The KEGG model is associated to more than 6,400,000 genes. They will not
+0110 % be used for the gapfilling, so they are removed to make this a little
+0111 % faster
+0112 keggModel=rmfield(keggModel,'genes');
+0113 keggModel=rmfield(keggModel,'rxnGeneMat');
+0114 
+0115 % It is already known from the previous commands that there are some
+0116 % unbalanced reactions in KEGG. Only use the balanced ones for the gap
+0117 % filling
+0118 balanceStructure=getElementalBalance(keggModel);
+0119 keggModel=removeReactions(keggModel,balanceStructure.balanceStatus~=1,true,true);
+0120 
+0121 % The function fillGaps with these settings will try to include reactions in
+0122 % order to have flux through all reactions in the model. There are other
+0123 % settings as well. The first flag says that production of all metabolites
+0124 % should be allowed.
+0125 params.relGap=0.6; %Lower number for a more exhaustive search
+0126 params.printReport=true;
+0127 [newConnected, cannotConnect, addedRxns, newModel, exitFlag]=fillGaps(model,keggModel,true,false,false,[],params);
+0128 
+0129 % The results show that fillGaps could connect around 29 reactions
+0130 % (newConnected) by including around 41 reactions from the KEGG model
+0131 % (addedRxns). Those should of course be checked manually to confirm that
+0132 % they exist in yeast, but in this tutorial it is assumed that all these
+0133 % reactions indeed occur in yeast.
+0134 
+0135 % Continue to improve the connectivity of the model by identifying
+0136 % metabolites that should be connected. A convenient way to get an overview
+0137 % of how connected the model is, and at the same time getting a lot of
+0138 % useful data, is to use gapReport. Note that it can take several to many
+0139 % hours to run, depending on the number of gaps in the model.
+0140 [noFluxRxns, noFluxRxnsRelaxed, subGraphs, notProducedMets, minToConnect,...
+0141     neededForProductionMat]=gapReport(newModel);
+0142 
+0143 % The results show that 532 from 1634 reactions cannot carry flux. Remember
+0144 % that an output is allowed for all metabolites, that is why it calculates
+0145 % 532 in both cases. 543 from 1617 metabolites cannot be synthesized from
+0146 % the precursors which are supplied. There are 6 subnetworks in the model,
+0147 % of which 1605 from 1617 metabolites belong to the first one.
+0148 
+0149 % It will also print something similar to:
+0150 
+0151 % To enable net production of all metabolites, a total of 322 metabolites
+0152 % must be connected
+0153 % Top 10 metabolites to connect:
+0154 %     1. Acyl-CoA[s] (connects 162 metabolites)
+0155 %     2. Thiamin diphosphate[s] (connects 17 metabolites)
+0156 %     3. G00003[s] (connects 14 metabolites)
+0157 %     4. Androstenediol[s] (connects 13 metabolites)
+0158 %     5. [Dihydrolipoyllysine-residue succinyltransferase] S-glutaryldihydrolipoyllysine[s] (connects 13 metabolites)
+0159 %     6. Selenomethionyl-tRNA(Met)[s] (connects 12 metabolites)
+0160 %     7. Retinyl ester[s] (connects 11 metabolites)
+0161 %     8. 1-Alkyl-2-acylglycerol[s] (connects 10 metabolites)
+0162 %     9. G00146[s] (connects 10 metabolites)
+0163 %     10. Progesterone[s] (connects 9 metabolites)
+0164 
+0165 % This is a very useful way of directing the gap-filling tasks to where they
+0166 % are of the greatest use. In this case it says that in order to have net
+0167 % production of all metabolites in the model from the simple inputs which
+0168 % have been defined (543 metabolites can currently not have net production)
+0169 % one needs to connect 322 unconnected metabolites in. However, by
+0170 % connecting only the top 10 in the list 271/543 (50%) of them will now be
+0171 % connected. When looking at the list one can see that the top ranking one
+0172 % is Acyl-CoA, which represents many different fatty acid chains. The second
+0173 % metabolite, thiamine disphosphate, is an enzyme co-factor. It turns out
+0174 % that yeast cannot grow on only the substrates that had been defined, but
+0175 % that it requires some other precursors for co-factor synthesis as well.
+0176 
+0177 % Add uptake reactions for the minimal media constituents needed for yeast
+0178 % to grow.
+0179 [~, J]=ismember({'4-Aminobenzoate';'Riboflavin';'Thiamine';'Biotin';'Folate';'Nicotinate';'Zymosterol';'Choline'},newModel.metNames);
+0180 [newModel, addedRxns]=addExchangeRxns(newModel,'in',J);
+0181 
+0182 % Rerun gapReport and use the output for targeting the gap-filling efforts.
+0183 % Note that only some info is printed; most of it is available in the output
+0184 % structures. Work like this in an iterative manner until the model is of
+0185 % sufficient quality.
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/tutorial/tutorial6.html b/doc/tutorial/tutorial6.html new file mode 100644 index 000000000..e4ebff117 --- /dev/null +++ b/doc/tutorial/tutorial6.html @@ -0,0 +1,208 @@ + + + + Description of tutorial6 + + + + + + + + + +
Home > tutorial > tutorial6.m
+ + + +

tutorial6 +

+ +

PURPOSE ^

+
tutorial6
+ +

SYNOPSIS ^

+
This is a script file.
+ +

DESCRIPTION ^

+
 tutorial6
+   This exercise demonstrates how to reconstruct a combined draft GEM by
+   from KEGG and MetaCyc pathway databases. A combined model with the
+   comprehensive coverage of metabolic pathways is generated from
+   different de novo reconstruction approaches. The input is a FASTA
+   format file with whole-proteome sequences. The combined model is
+   subsequently used for refinement of existing high-quality model and
+   generation of a new version of GEM, by utilizing the manual curation
+   results. This tutorial is a showcase of the new features released in
+   RAVEN 2.0 through demonstrating the utilization of the newly developed
+   functions on GEM reconstruction and curation for Streptomyces
+   coelicolor strain A3(2). Users may apply this script as the template in
+   their own work for other organisms.
+   This refers to Tutorial 6 from "RAVEN tutorials.docx"
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 % tutorial6
+0002 %   This exercise demonstrates how to reconstruct a combined draft GEM by
+0003 %   from KEGG and MetaCyc pathway databases. A combined model with the
+0004 %   comprehensive coverage of metabolic pathways is generated from
+0005 %   different de novo reconstruction approaches. The input is a FASTA
+0006 %   format file with whole-proteome sequences. The combined model is
+0007 %   subsequently used for refinement of existing high-quality model and
+0008 %   generation of a new version of GEM, by utilizing the manual curation
+0009 %   results. This tutorial is a showcase of the new features released in
+0010 %   RAVEN 2.0 through demonstrating the utilization of the newly developed
+0011 %   functions on GEM reconstruction and curation for Streptomyces
+0012 %   coelicolor strain A3(2). Users may apply this script as the template in
+0013 %   their own work for other organisms.
+0014 %   This refers to Tutorial 6 from "RAVEN tutorials.docx"
+0015 
+0016 %Before reconstruction, a FASTA file with protein sequences of the target
+0017 %organism needs to be prepared. In this tutorial, all protein sequences of
+0018 %S. coelicolor A3(2) were downloaded from the NCBI genome database and
+0019 %provided in current folder (Sco_all_protein.faa). The description lines
+0020 %(starting with ">" character) of this FASTA file were modified by keeping
+0021 %only the locus tag (e.g. SCO6005), which is commonly used as the gene
+0022 %names in GEMs.
+0023 
+0024 %Generate a draft GEM from MetaCyc database. The first parameter is
+0025 %organismID and needs to be specified by user. The other parameters are set
+0026 %to exclude unbalanced and undetermined reactions, but keep transport
+0027 %reactions. The two parameters for homology search are set to the default
+0028 %values that have been optimized to capture the protein hits with both
+0029 %comprehensive coverage and the least false positives.
+0030 ScoMetaCycDraftModel=getMetaCycModelForOrganism('ScoMetaCyc','Sco_all_protein.faa',1);
+0031 
+0032 %Generate the two draft models from KEGG database. The first one is
+0033 %reconstructed from the genome information annotated by KEGG. Since KEGG
+0034 %provides genome annotations for over 5000 organisms, their GEMs can thus
+0035 %be generated without providing protein sequences while only using the
+0036 %organismID. The organisms with KEGG annotation and their associated ids
+0037 %(e.g. 'sco' for Streptomyces coelicolor) can be found from here:
+0038 %https://www.kegg.jp/kegg/catalog/org_list.html.
+0039 %Generate a draft model using KEGG annotation and exclude incomplete
+0040 %reactions and reactions with undefined stoichiometry
+0041 ScoKEGGAnnotation=getKEGGModelForOrganism('sco','','','',1,0,0);
+0042 
+0043 %Generate the second KEGG-based draft model based on sequence homology to
+0044 %KEGG Ortholog sequence clusters while excluding incomplete reactions and
+0045 %the ones with undefined stoichiometry. Type "help getKEGGModelForOrganism"
+0046 %to see the detailed instructions for the choice of different parameters.
+0047 %The default values for homology search are used because they have been
+0048 %optimized for the best performance.
+0049 ScoKEGGHomology=getKEGGModelForOrganism('ScoKEGGHMMs','Sco_all_protein.faa','prok90_kegg105','',1,0,0);
+0050 
+0051 %De novo reconstruction from MetaCyc should take about 10 minutes, while
+0052 %both reconstructions from KEGG may take up to 50-60 minutes in overall
+0053 %depending on the computer hardware and the system used. Given that KEGG
+0054 %and MetaCyc databases are formulated in different ways; KEGG relies on
+0055 %sequence-based annotation, while MetaCyc collects only experimentally
+0056 %verified pathways. Therefore, integration of MetaCyc- and KEGG-based draft
+0057 %models could have a better coverage of the metbolism for the target
+0058 %organism.
+0059 
+0060 %At first, the two KEGG-based models can be directly merged
+0061 ScoKEGGDraftModel=mergeModels({ScoKEGGAnnotation ScoKEGGHomology});
+0062 
+0063 disp(numel(ScoKEGGHomology.rxns)+numel(ScoKEGGAnnotation.rxns));
+0064 disp(numel(ScoKEGGDraftModel.rxns));
+0065 %By checking the reaction number, it can be seen that reaction number in
+0066 %the merged model equals adding up the reaction numbers in homology and
+0067 %annotation KEGG draft models. And there are duplicated reactions in this
+0068 %merged model.
+0069 
+0070 %Merge the duplicated reactions into one and combine multiple iso-enzymes
+0071 %into a single grRules. The expandModel and contractModel functions are
+0072 %utilised, see their instructions for details.
+0073 ScoKEGGDraftModel=expandModel(ScoKEGGDraftModel);
+0074 ScoKEGGDraftModel=contractModel(ScoKEGGDraftModel);
+0075 
+0076 %In the end, KEGG- and MetaCyc-based draft models can be further combined
+0077 %into an integrated GEM. This step is achieved by the function
+0078 %combineMetaCycKEGGModels, which firstly converts metabolite and reaction
+0079 %identifiers in the KEGG model into corresponding MetaCyc ids, and then
+0080 %detects duplications and keeps only unique reactions and metabolites that
+0081 %are mostly in MetaCyc identifiers.
+0082 ScoCombinedDraftModel=combineMetaCycKEGGModels(ScoMetaCycDraftModel, ScoKEGGDraftModel);
+0083 
+0084 %With this combined model, the existing iMK1208 model is refined by
+0085 %incorporating the new pathways/reactions that are found in the combined
+0086 %model but absent from the previous iMK1208 model. At the time of
+0087 %publication, a total of 398 reactions in the combined draft model were
+0088 %determined as new pathways based on manual curation results, which have
+0089 %been organized into TableS3. Load these manually selected reactions and
+0090 %their subSystems as the pre-processed array structure selectedNewRxns.
+0091 load('iMK1208+suppInfo.mat','selectedNewRxns');
+0092 disp(selectedNewRxns);
+0093 
+0094 %Generate a sub-model that includes only these new reactions. This is
+0095 %implemented by subtracting the other reactions from the combined model
+0096 %using function removeReactions
+0097 rxnsToRemove=setdiff(ScoCombinedDraftModel.rxns,selectedNewRxns.rxns);
+0098 newRxnSubModel=removeReactions(ScoCombinedDraftModel,rxnsToRemove,1,1);
+0099 
+0100 %Now this newRxnSubModel contains only these new reactions. It needs to be
+0101 %modified before merging with the iMK1208. Since these reactions are
+0102 %metabolic ones and can all be assigned to the cytoplasm compartment
+0103 newRxnSubModel.comps{1}='c';
+0104 newRxnSubModel.compNames{1}='Cytoplasm';
+0105 
+0106 %Amend to the genes and rxnGeneMat fields
+0107 newRxnSubModel.genes={};
+0108 for k=1:numel(newRxnSubModel.rxns)
+0109    newRxnSubModel.genes=[newRxnSubModel.genes;transpose(strsplit(newRxnSubModel.grRules{k},' or '))];
+0110 end
+0111 newRxnSubModel.genes=unique(newRxnSubModel.genes);
+0112 [~, newRxnSubModel.rxnGeneMat, ~]=standardizeGrRules(newRxnSubModel);
+0113 
+0114 %Since the newRxnSubModel is ready for incorportation, the iMK1208 model
+0115 %can be loaded for integration
+0116 load('iMK1208+suppInfo.mat','iMK1208');
+0117 
+0118 %It should be noted that the incompatible nomenclatures (especially the
+0119 %metabolite identifiers) used in different GEMs and databases led to a
+0120 %serious problem in model comparison, curation and integration. In order to
+0121 %properly integrate the iMK1208 with this sub-model, both models should be
+0122 %unified into the same name space, since the metabolites in the sub-model
+0123 %use MetaCyc identifiers that are different from the ones used in iMK1208
+0124 %model. TableS2 contains the results for database mining and intensive
+0125 %manual curation while associating these metabolite identifiers. Load
+0126 %these manually selected reactions and their subSystems as the
+0127 %pre-processed array structure metaCycMetsIniMK.
+0128 load('iMK1208+suppInfo.mat','metaCycMetsIniMK');
+0129 
+0130 %Replace the metabolites in the sub-model with the identifiers and names
+0131 %used in iMK1208 according to the mapping information in TableS2
+0132 %(metaCycMetsIniMK).
+0133 [a, b]=ismember(newRxnSubModel.mets,metaCycMetsIniMK);
+0134 I=find(a);
+0135 newRxnSubModel.mets=strcat(newRxnSubModel.mets,'_c');
+0136 newRxnSubModel.metNames(I)=iMK1208.metNames(b(I));
+0137 newRxnSubModel.mets(I)=iMK1208.mets(b(I));
+0138 
+0139 %The necessary issues for merging iMK1208 with the new reactions determined
+0140 %from de novo generated draft GEMs have been resolved. Those can be
+0141 %directly merged into the Sco4 model, which refers to the 4th major update
+0142 %of the GEM for Streptomyces coelicolor.
+0143 Sco4=mergeModels({iMK1208 newRxnSubModel});
+0144 
+0145 %Check out if the newly generated Sco4 could grow
+0146 sol=solveLP(Sco4);
+0147 disp(sol.f);
+0148 %The results indicate that this new model is functional
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/up.png b/doc/up.png new file mode 100644 index 0000000000000000000000000000000000000000..b348b9a1b19bd5030efd3df293d84a18b41ef6a4 GIT binary patch literal 162 zcmeAS@N?(olHy`uVBq!ia0vp^{2x4R4De + + + Description of emptyOrLogicalScalar + + + + + + + + + +
Home > utils > emptyOrLogicalScalar.m
+ + + +

emptyOrLogicalScalar +

+ +

PURPOSE ^

+
+ +

SYNOPSIS ^

+
function emptyOrLogical(x)
+ +

DESCRIPTION ^

+
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function emptyOrLogical(x)
+0002     if isempty(x)
+0003         return;
+0004     end
+0005     validateattributes(x, {'logical'}, {'scalar'});
+0006 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/utils/emptyOrTextOrCellOfText.html b/doc/utils/emptyOrTextOrCellOfText.html new file mode 100644 index 000000000..72298c9a3 --- /dev/null +++ b/doc/utils/emptyOrTextOrCellOfText.html @@ -0,0 +1,90 @@ + + + + Description of emptyOrTextOrCellOfText + + + + + + + + + +
Home > utils > emptyOrTextOrCellOfText.m
+ + + +

emptyOrTextOrCellOfText +

+ +

PURPOSE ^

+
Validate [] OR text scalar (char row or string scalar) OR cell array of such text.
+ +

SYNOPSIS ^

+
function mustBeEmptyOrTextOrCellOfText(x)
+ +

DESCRIPTION ^

+
 Validate [] OR text scalar (char row or string scalar) OR cell array of such text.
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function mustBeEmptyOrTextOrCellOfText(x)
+0002 % Validate [] OR text scalar (char row or string scalar) OR cell array of such text.
+0003 
+0004 % Allow explicit empty
+0005 if isempty(x)
+0006     return;
+0007 end
+0008 
+0009 % Allow a single text scalar
+0010 if ischar(x)
+0011     if ~isrow(x)
+0012         error('Text must be a character row vector, a string scalar, or empty.');
+0013     end
+0014     return;
+0015 elseif isstring(x)
+0016     if ~isscalar(x)
+0017         error('Text must be a string scalar, a character row vector, or empty.');
+0018     end
+0019     return;
+0020 end
+0021 
+0022 % Allow a cell array of text
+0023 if iscell(x)
+0024     for k = 1:numel(x)
+0025         v = x{k};
+0026         if ischar(v)
+0027             if ~isrow(v)   % '' is 1x0 char, which is a row -> allowed
+0028                 error('Each cell element must be a character row vector or a string scalar.');
+0029             end
+0030         elseif isstring(v)
+0031             if ~isscalar(v)  % "" is a scalar string -> allowed
+0032                 error('Each cell element must be a string scalar or a character row vector.');
+0033             end
+0034         else
+0035             error('Each cell element must be text (string scalar or character row vector).');
+0036         end
+0037     end
+0038     return;
+0039 end
+0040 
+0041 % Anything else is invalid
+0042 error('Value must be empty, a text value, or a cell array of text values.');
+0043 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/utils/emptyOrTextScalar.html b/doc/utils/emptyOrTextScalar.html new file mode 100644 index 000000000..7d53acd3c --- /dev/null +++ b/doc/utils/emptyOrTextScalar.html @@ -0,0 +1,59 @@ + + + + Description of emptyOrTextScalar + + + + + + + + + +
Home > utils > emptyOrTextScalar.m
+ + + +

emptyOrTextScalar +

+ +

PURPOSE ^

+
+ +

SYNOPSIS ^

+
function mustBeEmptyOrTextScalar(x)
+ +

DESCRIPTION ^

+
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function mustBeEmptyOrTextScalar(x)
+0002     if isempty(x)
+0003         return;
+0004     end
+0005     if isstring(x)
+0006         if ~isscalar(x), error('Value must be a string scalar or empty.'); end
+0007     elseif ischar(x)
+0008         if ~isrow(x), error('Char input must be a row vector or empty.'); end
+0009     else
+0010         error('Value must be a string/char scalar or empty.');
+0011     end
+0012 end
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/utils/index.html b/doc/utils/index.html new file mode 100644 index 000000000..9a1637b6a --- /dev/null +++ b/doc/utils/index.html @@ -0,0 +1,29 @@ + + + + Index for Directory utils + + + + + + + + + + +
< Master indexIndex for utils >
+ +

Index for utils

+ +

Matlab files in this directory:

+ +
 emptyOrLogicalScalar
 emptyOrTextOrCellOfTextValidate [] OR text scalar (char row or string scalar) OR cell array of such text.
 emptyOrTextScalar
 runRAVENtestsrunRAVENtests
+ + + + +
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/utils/runRAVENtests.html b/doc/utils/runRAVENtests.html new file mode 100644 index 000000000..da9c79b70 --- /dev/null +++ b/doc/utils/runRAVENtests.html @@ -0,0 +1,60 @@ + + + + Description of runRAVENtests + + + + + + + + + +
Home > utils > runRAVENtests.m
+ + + +

runRAVENtests +

+ +

PURPOSE ^

+
runRAVENtests
+ +

SYNOPSIS ^

+
function testResults = runRAVENtests
+ +

DESCRIPTION ^

+
 runRAVENtests
+  Runs all unit tests found at RAVEN/test/unit_tests, and prints output in
+  command window.
+ + +

CROSS-REFERENCE INFORMATION ^

+This function calls: +
    +
+This function is called by: +
    +
+ + + + +

SOURCE CODE ^

+
0001 function testResults = runRAVENtests
+0002 % runRAVENtests
+0003 %  Runs all unit tests found at RAVEN/test/unit_tests, and prints output in
+0004 %  command window.
+0005 
+0006 ravenPath = findRAVENroot;
+0007 curwd = pwd;
+0008 cd(fullfile(ravenPath,'testing','unit_tests'));
+0009 testResults = runtests(struct2table(dir('*.m')).name);
+0010 
+0011 cd(curwd);
+
Generated by m2html © 2005
+ + \ No newline at end of file diff --git a/doc/windows.png b/doc/windows.png new file mode 100644 index 0000000000000000000000000000000000000000..6cec95b8815d3d5dab8c97c41c75197fdb014135 GIT binary patch literal 286 zcmV+(0pb3MP)4J#NJjgjrM8h9Te~(8G kcWyrh{e1gnl+pf{?#tSrFr=&ZY5)KL07*qoM6N<$f*5RoFaQ7m literal 0 HcmV?d00001 From 41b89fd4e2e6c1f2caa073df9b097203efb97993 Mon Sep 17 00:00:00 2001 From: Eduard Kerkhoven Date: Wed, 30 Sep 2026 19:28:03 +0200 Subject: [PATCH 7/7] Skip getCurrentTask when Parallel Computing Toolbox is not licensed --- doc/solver/optimizeProb.html | 384 ++++++++++++++++++----------------- solver/optimizeProb.m | 10 +- 2 files changed, 199 insertions(+), 195 deletions(-) diff --git a/doc/solver/optimizeProb.html b/doc/solver/optimizeProb.html index a6ec84623..328b92faa 100644 --- a/doc/solver/optimizeProb.html +++ b/doc/solver/optimizeProb.html @@ -146,199 +146,201 @@

SOURCE CODE ^% If run in parallel, then one thread per gurobi. getCurrentTask 0094 % requires the Parallel Computing Toolbox. -0095 try -0096 inParallel = ~isempty(getCurrentTask); -0097 catch -0098 inParallel = false; -0099 end -0100 if inParallel -0101 solverparams.Threads=1; -0102 end -0103 solverparams = structUpdate(solverparams,params); -0104 -0105 % Restructering problem according to gurobi format -0106 if isfield(prob, 'csense') -0107 prob.sense = renameparams(prob.csense, {'L','G','E'}, {'<','>','='}); -0108 prob = rmfield(prob, {'csense'}); -0109 end -0110 if isfield(prob, 'osense') -0111 osense = prob.osense; -0112 prob.modelsense = renameparams(num2str(prob.osense), {'1','-1'}, {'min','max'}); -0113 prob = rmfield(prob, {'osense'}); -0114 end -0115 [prob.obj, prob.rhs, prob.vtype] = deal(prob.c, prob.b, prob.vartype); -0116 prob = rmfield(prob, {'c','b','vartype'}); -0117 -0118 resG = gurobi(prob,solverparams); +0095 inParallel = false; +0096 if license('test','Distrib_Computing_Toolbox') +0097 try +0098 inParallel = ~isempty(getCurrentTask); +0099 catch +0100 end +0101 end +0102 if inParallel +0103 solverparams.Threads=1; +0104 end +0105 solverparams = structUpdate(solverparams,params); +0106 +0107 % Restructering problem according to gurobi format +0108 if isfield(prob, 'csense') +0109 prob.sense = renameparams(prob.csense, {'L','G','E'}, {'<','>','='}); +0110 prob = rmfield(prob, {'csense'}); +0111 end +0112 if isfield(prob, 'osense') +0113 osense = prob.osense; +0114 prob.modelsense = renameparams(num2str(prob.osense), {'1','-1'}, {'min','max'}); +0115 prob = rmfield(prob, {'osense'}); +0116 end +0117 [prob.obj, prob.rhs, prob.vtype] = deal(prob.c, prob.b, prob.vartype); +0118 prob = rmfield(prob, {'c','b','vartype'}); 0119 -0120 try -0121 % Name output fields the same as COBRA does -0122 res.full = resG.x; -0123 res.obj = resG.objval; -0124 res.origStat = resG.status; -0125 if isfield(resG,{'pi','rc'}) -0126 res.dual = -resG.pi*osense; -0127 res.rcost = -resG.rc*osense; -0128 end -0129 if milp && strcmp(resG.status, 'TIME_LIMIT') -0130 % If res has the objval field, it succeeded, regardless of -0131 % time_limit status -0132 resG.status = 'OPTIMAL'; -0133 end -0134 switch resG.status -0135 case 'OPTIMAL' -0136 res.stat = 1; -0137 case 'UNBOUNDED' -0138 res.stat = 2; -0139 otherwise -0140 res.stat = 0; -0141 end -0142 if ~milp -0143 res.vbasis = resG.vbasis; -0144 res.cbasis = resG.cbasis; -0145 else -0146 res.mipgap = resG.mipgap; -0147 end -0148 catch -0149 res.stat = 0; -0150 res.origStat = resG.status; % useful information to have -0151 end -0152 %% Use GLPK using RAVEN-provided binary -0153 case 'glpk' -0154 solverparams.scale = 1; % Auto scaling -0155 %solverparams.tmlim = defaultparams.timeLimit; -0156 solverparams.tolbnd = defaultparams.feasTol; -0157 solverparams.toldj = defaultparams.optTol; -0158 solverparams.tolint = defaultparams.intTol; -0159 solverparams.tolobj = defaultparams.objTol; -0160 solverparams.msglev = 0; % Level of verbosity -0161 solverparams = structUpdate(solverparams,params); -0162 -0163 prob.csense = renameparams(prob.csense, {'L','G','E'}, {'U','L','S'}); +0120 resG = gurobi(prob,solverparams); +0121 +0122 try +0123 % Name output fields the same as COBRA does +0124 res.full = resG.x; +0125 res.obj = resG.objval; +0126 res.origStat = resG.status; +0127 if isfield(resG,{'pi','rc'}) +0128 res.dual = -resG.pi*osense; +0129 res.rcost = -resG.rc*osense; +0130 end +0131 if milp && strcmp(resG.status, 'TIME_LIMIT') +0132 % If res has the objval field, it succeeded, regardless of +0133 % time_limit status +0134 resG.status = 'OPTIMAL'; +0135 end +0136 switch resG.status +0137 case 'OPTIMAL' +0138 res.stat = 1; +0139 case 'UNBOUNDED' +0140 res.stat = 2; +0141 otherwise +0142 res.stat = 0; +0143 end +0144 if ~milp +0145 res.vbasis = resG.vbasis; +0146 res.cbasis = resG.cbasis; +0147 else +0148 res.mipgap = resG.mipgap; +0149 end +0150 catch +0151 res.stat = 0; +0152 res.origStat = resG.status; % useful information to have +0153 end +0154 %% Use GLPK using RAVEN-provided binary +0155 case 'glpk' +0156 solverparams.scale = 1; % Auto scaling +0157 %solverparams.tmlim = defaultparams.timeLimit; +0158 solverparams.tolbnd = defaultparams.feasTol; +0159 solverparams.toldj = defaultparams.optTol; +0160 solverparams.tolint = defaultparams.intTol; +0161 solverparams.tolobj = defaultparams.objTol; +0162 solverparams.msglev = 0; % Level of verbosity +0163 solverparams = structUpdate(solverparams,params); 0164 -0165 if milp -0166 solverparams.tmlim = solverparams.tmlim*10; -0167 solverparams.msglev = 1; % Level of verbosity -0168 disp('Issues have been observed when using GLPK for MILP solving. Be advised to carefully observe the results, or us another solver.') -0169 end -0170 -0171 % Ensure that RAVEN glpk binary is used, return to original -0172 % directory afterwards -0173 [ravenDir,currDir]=findRAVENroot(); -0174 cd(fullfile(ravenDir,'software','GLPKmex')) -0175 [xopt, fmin, errnum, extra] = glpk(prob.c, prob.A, prob.b, prob.lb, prob.ub, prob.csense, prob.vartype, prob.osense, solverparams); -0176 cd(currDir) -0177 -0178 switch errnum % 1 = undefined; 2 = feasible; 3 = infeasible; 4 = no feasible solution; 5 = optimal; 6 = no unbounded solution -0179 case 5 -0180 res.stat = 1; % Optimal -0181 case 2 -0182 res.stat = 2; % Feasible, but not optimal -0183 otherwise -0184 res.stat = 0; -0185 end -0186 res.origStat = errnum; -0187 res.full = xopt; -0188 res.obj = fmin; -0189 res.dual = -extra.lambda*prob.osense; -0190 res.rcost = -extra.redcosts*prob.osense; -0191 %% Use scip -0192 case {'soplex','scip'} % Old 'soplex' option also allowed -0193 [xopt,fval,exitflag] = scip([], prob.c, prob.A,-prob.b, prob.b, prob.lb, prob.ub, prob.vartype); -0194 -0195 % [x,fval,exitflag,stats] = scip(H, f, A, rl, ru, lb, ub, xtype, sos, qc, nl, x0, opts) -0196 % -0197 % Input arguments*: -0198 % H - quadratic objective matrix (sparse, optional [NOT TRIL / TRIU]) -0199 % f - linear objective vector -0200 % A - linear constraint matrix (sparse) -0201 % rl - linear constraint lhs -0202 % ru - linear constraint rhs -0203 % lb - decision variable lower bounds -0204 % ub - decision variable upper bounds -0205 % xtype - string of variable integrality ('c' continuous, 'i' integer, 'b' binary) -0206 % sos - SOS structure with fields type, index and weight (see below) -0207 % qc - Quadratic Constraints structure with fields Q, l, qrl and qru (see below) -0208 % nl - Nonlinear Objective and Constraints structure (see below) -0209 % x0 - primal solution -0210 % opts - solver options (see below) -0211 % -0212 % Return arguments: -0213 % x - solution vector -0214 % fval - objective value at the solution -0215 % exitflag - exit status (see below) -0216 % stats - statistics structure -0217 % -0218 % Option Fields (all optional, see also optiset for a list): -0219 % solverOpts - specific SCIP options (list of pairs of parameter names and values) -0220 % maxiter - maximum LP solver iterations -0221 % maxnodes - maximum nodes to explore -0222 % maxtime - maximum execution time [s] -0223 % tolrfun - primal feasibility tolerance -0224 % display - solver display level [0-5] -0225 % probfile - write problem to given file -0226 % presolvedfile - write presolved problem to file -0227 % -0228 % Return Status: -0229 % 0 - Unknown -0230 % 1 - User Interrupted -0231 % 2 - Node Limit Reached -0232 % 3 - Total Node Limit Reached -0233 % 4 - Stall Node Limit Reached -0234 % 5 - Time Limit Reached -0235 % 6 - Memory Limit Reached -0236 % 7 - Gap Limit Reached -0237 % 8 - Solution Limit Reached -0238 % 9 - Solution Improvement Limit Reached -0239 % 10 - Restart Limit Reached -0240 % 11 - Problem Solved to Optimality -0241 % 12 - Problem is Infeasible -0242 % 13 - Problem is Unbounded -0243 % 14 - Problem is Either Infeasible or Unbounded -0244 -0245 res.origStat = exitflag; -0246 res.full = xopt; -0247 res.obj = fval; -0248 -0249 switch exitflag -0250 case 11 -0251 res.stat = 1; -0252 case {1, 5, 6, 7, 8, 9, 10, 13} % If user-interrupted, not sure if optimal -0253 res.stat = 2; -0254 otherwise -0255 res.stat = 0; -0256 end -0257 otherwise -0258 error('RAVEN solver not defined or unknown. Try using setRavenSolver(''solver'').'); -0259 end -0260 if res.stat>0 -0261 res.full=res.full(1:size(prob.a,2)); -0262 end -0263 end -0264 -0265 function s_merged=structUpdate(s_old,s_new) -0266 %Remove overlapping fields from first struct; -0267 %Obtain all unique names of remaining fields; -0268 %Merge both structs -0269 s_merged = rmfield(s_old, intersect(fieldnames(s_old), fieldnames(s_new))); -0270 names = [fieldnames(s_merged); fieldnames(s_new)]; -0271 s_merged = cell2struct([struct2cell(s_merged); struct2cell(s_new)], names, 1); -0272 end -0273 -0274 function paramlist = renameparams(paramlist,old,new) -0275 if ~iscell(paramlist) -0276 wasNoCell = true; -0277 paramlist={paramlist}; -0278 else -0279 wasNoCell = false; -0280 end -0281 for i=1:numel(old) -0282 paramlist = regexprep(paramlist,old{i},new{i}); -0283 end -0284 if wasNoCell -0285 paramlist=paramlist{1}; -0286 end -0287 end +0165 prob.csense = renameparams(prob.csense, {'L','G','E'}, {'U','L','S'}); +0166 +0167 if milp +0168 solverparams.tmlim = solverparams.tmlim*10; +0169 solverparams.msglev = 1; % Level of verbosity +0170 disp('Issues have been observed when using GLPK for MILP solving. Be advised to carefully observe the results, or us another solver.') +0171 end +0172 +0173 % Ensure that RAVEN glpk binary is used, return to original +0174 % directory afterwards +0175 [ravenDir,currDir]=findRAVENroot(); +0176 cd(fullfile(ravenDir,'software','GLPKmex')) +0177 [xopt, fmin, errnum, extra] = glpk(prob.c, prob.A, prob.b, prob.lb, prob.ub, prob.csense, prob.vartype, prob.osense, solverparams); +0178 cd(currDir) +0179 +0180 switch errnum % 1 = undefined; 2 = feasible; 3 = infeasible; 4 = no feasible solution; 5 = optimal; 6 = no unbounded solution +0181 case 5 +0182 res.stat = 1; % Optimal +0183 case 2 +0184 res.stat = 2; % Feasible, but not optimal +0185 otherwise +0186 res.stat = 0; +0187 end +0188 res.origStat = errnum; +0189 res.full = xopt; +0190 res.obj = fmin; +0191 res.dual = -extra.lambda*prob.osense; +0192 res.rcost = -extra.redcosts*prob.osense; +0193 %% Use scip +0194 case {'soplex','scip'} % Old 'soplex' option also allowed +0195 [xopt,fval,exitflag] = scip([], prob.c, prob.A,-prob.b, prob.b, prob.lb, prob.ub, prob.vartype); +0196 +0197 % [x,fval,exitflag,stats] = scip(H, f, A, rl, ru, lb, ub, xtype, sos, qc, nl, x0, opts) +0198 % +0199 % Input arguments*: +0200 % H - quadratic objective matrix (sparse, optional [NOT TRIL / TRIU]) +0201 % f - linear objective vector +0202 % A - linear constraint matrix (sparse) +0203 % rl - linear constraint lhs +0204 % ru - linear constraint rhs +0205 % lb - decision variable lower bounds +0206 % ub - decision variable upper bounds +0207 % xtype - string of variable integrality ('c' continuous, 'i' integer, 'b' binary) +0208 % sos - SOS structure with fields type, index and weight (see below) +0209 % qc - Quadratic Constraints structure with fields Q, l, qrl and qru (see below) +0210 % nl - Nonlinear Objective and Constraints structure (see below) +0211 % x0 - primal solution +0212 % opts - solver options (see below) +0213 % +0214 % Return arguments: +0215 % x - solution vector +0216 % fval - objective value at the solution +0217 % exitflag - exit status (see below) +0218 % stats - statistics structure +0219 % +0220 % Option Fields (all optional, see also optiset for a list): +0221 % solverOpts - specific SCIP options (list of pairs of parameter names and values) +0222 % maxiter - maximum LP solver iterations +0223 % maxnodes - maximum nodes to explore +0224 % maxtime - maximum execution time [s] +0225 % tolrfun - primal feasibility tolerance +0226 % display - solver display level [0-5] +0227 % probfile - write problem to given file +0228 % presolvedfile - write presolved problem to file +0229 % +0230 % Return Status: +0231 % 0 - Unknown +0232 % 1 - User Interrupted +0233 % 2 - Node Limit Reached +0234 % 3 - Total Node Limit Reached +0235 % 4 - Stall Node Limit Reached +0236 % 5 - Time Limit Reached +0237 % 6 - Memory Limit Reached +0238 % 7 - Gap Limit Reached +0239 % 8 - Solution Limit Reached +0240 % 9 - Solution Improvement Limit Reached +0241 % 10 - Restart Limit Reached +0242 % 11 - Problem Solved to Optimality +0243 % 12 - Problem is Infeasible +0244 % 13 - Problem is Unbounded +0245 % 14 - Problem is Either Infeasible or Unbounded +0246 +0247 res.origStat = exitflag; +0248 res.full = xopt; +0249 res.obj = fval; +0250 +0251 switch exitflag +0252 case 11 +0253 res.stat = 1; +0254 case {1, 5, 6, 7, 8, 9, 10, 13} % If user-interrupted, not sure if optimal +0255 res.stat = 2; +0256 otherwise +0257 res.stat = 0; +0258 end +0259 otherwise +0260 error('RAVEN solver not defined or unknown. Try using setRavenSolver(''solver'').'); +0261 end +0262 if res.stat>0 +0263 res.full=res.full(1:size(prob.a,2)); +0264 end +0265 end +0266 +0267 function s_merged=structUpdate(s_old,s_new) +0268 %Remove overlapping fields from first struct; +0269 %Obtain all unique names of remaining fields; +0270 %Merge both structs +0271 s_merged = rmfield(s_old, intersect(fieldnames(s_old), fieldnames(s_new))); +0272 names = [fieldnames(s_merged); fieldnames(s_new)]; +0273 s_merged = cell2struct([struct2cell(s_merged); struct2cell(s_new)], names, 1); +0274 end +0275 +0276 function paramlist = renameparams(paramlist,old,new) +0277 if ~iscell(paramlist) +0278 wasNoCell = true; +0279 paramlist={paramlist}; +0280 else +0281 wasNoCell = false; +0282 end +0283 for i=1:numel(old) +0284 paramlist = regexprep(paramlist,old{i},new{i}); +0285 end +0286 if wasNoCell +0287 paramlist=paramlist{1}; +0288 end +0289 end
Generated by m2html © 2005
\ No newline at end of file diff --git a/solver/optimizeProb.m b/solver/optimizeProb.m index f2279e62d..bcb137e98 100755 --- a/solver/optimizeProb.m +++ b/solver/optimizeProb.m @@ -92,10 +92,12 @@ solverparams.Presolve = 2; % If run in parallel, then one thread per gurobi. getCurrentTask % requires the Parallel Computing Toolbox. - try - inParallel = ~isempty(getCurrentTask); - catch - inParallel = false; + inParallel = false; + if license('test','Distrib_Computing_Toolbox') + try + inParallel = ~isempty(getCurrentTask); + catch + end end if inParallel solverparams.Threads=1;