diff --git a/CHANGELOG.md b/CHANGELOG.md index f197f7a1..cb5d234a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,6 +57,10 @@ case, `&`, `&&`, `|`, `||`, operators as whole words, so `G1&G2` is one gene id), and that a malformed rule raises `RAVEN:badGrRule`. +### Documentation + +* Help blocks of 176 files are rewritten in impersonal, present-tense wording with British spelling; the code is unchanged. Statements that differed from the code are corrected, for example `simplifyModel` `deleteDuplicates` (first occurrence kept), `removeBadRxns` `refModel`, `replaceMets` outputs, `getMinNrFluxes` `params`, `checkRaven` `developMode` and the `downloadRavenBinaries` offline bundle. `reverseRxns` has the RAVEN 3 help structure. + ## 3.0.0b1 — 2026-09-07 First beta toward 3.0. Changes below are relative to RAVEN 2.9.3, the last 2.x release: diff --git a/checkInstallation.m b/checkInstallation.m index 298453cc..8bfe180b 100644 --- a/checkInstallation.m +++ b/checkInstallation.m @@ -3,10 +3,10 @@ % % Forwards all arguments and outputs to checkRaven. % -% NOTE: this function is run before RAVEN has been added to the MATLAB -% path, so it must not call any other RAVEN functions until checkRaven has -% added RAVEN to the path itself. It cannot use the shared -% utils/deprecationWarning for the same reason. +% This function runs before RAVEN is on the MATLAB path. It therefore +% calls no other RAVEN function until checkRaven has added RAVEN to the +% path, and it does not use the shared deprecationWarning function in +% the utils folder. % % Usage: [currVer, installType] = checkInstallation(developMode, checkBinaries) diff --git a/checkRaven.m b/checkRaven.m index a0963f89..380c1e2f 100755 --- a/checkRaven.m +++ b/checkRaven.m @@ -1,35 +1,34 @@ function [currVer, installType] = checkRaven(developMode, checkBinaries) -% checkRaven -% Checks that 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 +% checkRaven Check the RAVEN installation and set up the MATLAB path. % -% NOTE: this function is run before RAVEN has been added to the MATLAB -% path, so it must not call any other RAVEN functions until it has added -% RAVEN to the path itself. Its arguments are therefore parsed directly -% rather than via parseRAVENargs. +% Reports the installation type and RAVEN version, adds RAVEN to the +% MATLAB path, tests model import and export, the LP solvers and the +% binary executables, and checks for functions with overlapping names +% between RAVEN and other toolboxes or user-defined functions on the +% MATLAB path. +% +% This function runs before RAVEN is on the MATLAB path. It therefore +% calls no other RAVEN function until it has added RAVEN to the path, and +% it parses its arguments without parseRAVENargs. % % Parameters % ---------- -% developMode logical indicating development mode, which includes -% testing of binaries that are required to update KEGG -% HMMs (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. +% developMode 'versionOnly' to return the version in currVer without +% any further installation check or test. Any other +% value runs all checks. Default false. +% checkBinaries logical, true to test that the BLAST+, DIAMOND and +% HMMER binaries execute. If false, the binary check is +% skipped. Default true. % % Output: % currVer current RAVEN version % installType how RAVEN is installed -% 0: via git (as .git folder is found) +% 0: via git (a .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: +% 2: direct download of a ZIP file +% The values correspond to the installation types +% Advanced (0), Easy (1) and Medium (2) described at % https://raven-docs.readthedocs.io/en/latest/installation/raven.html -% 0 = advanced / 1 = easy / 2 = medium % % Usage: [currVer, installType] = checkRaven(developMode) diff --git a/src/INIT/INITStepDesc.m b/src/INIT/INITStepDesc.m index 6bc3acb7..5f9fce4d 100644 --- a/src/INIT/INITStepDesc.m +++ b/src/INIT/INITStepDesc.m @@ -1,6 +1,6 @@ classdef INITStepDesc % Describes a step in the ftINIT algorithm. A cell array of objects of this -% class is used as input to ftINIT to specify how the algorithm should be run. +% class is the input to ftINIT that specifies how the algorithm is run. properties PosRevOff %If true, positive-scored reversible reactions are removed %from the MILP problem (used in step 1 of ftINIT) @@ -21,7 +21,7 @@ % b8 - All rxns without GPRs MetsToIgnore % Structure describing mets that can be removed from the model - % before running ftINIT, such as water etc. + % before running ftINIT, such as water and other ubiquitous metabolites. % .simpleMets % .mets Names of metabolites to remove % .compsToKeep Compartments for which metabolites should be kept. diff --git a/src/INIT/ftINIT.m b/src/INIT/ftINIT.m index 61de0623..6b5ba6e4 100644 --- a/src/INIT/ftINIT.m +++ b/src/INIT/ftINIT.m @@ -1,132 +1,147 @@ function [model, metProduction, addedRxnsForTasks, deletedRxnsInINIT, fullMipRes] = ftINIT(prepData, tissue, celltype, hpaData, varargin) % ftINIT Generate a model using the ftINIT algorithm. % -% Main function for generating 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 needs 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 +% Generates a model from proteomics, transcriptomics, metabolomics and +% metabolic tasks, in any combination except metabolomics alone. The function +% prepINITModel must be run first on the template model (such as the generic +% Human-GEM). It runs once per template and precalculates the parts that are +% independent of the omics data. Its output, prepData, is the input to this % function. % % Parameters % ---------- % prepData : struct -% the prepData for the model. +% the prepData for the model, as returned by prepINITModel. % tissue : char -% tissue to score for. Should exist in either hpaData.tissues or +% tissue to score for. Must exist in hpaData.tissues or % transcrData.tissues. % celltype : char -% cell type to score for. Should exist in either hpaData.celltypes or -% transcrData.celltypes for this tissue (default is to use the max values -% among all the cell types for the tissue). +% cell type to score for. Must exist in hpaData.celltypes or +% transcrData.celltypes for this tissue. If empty, the maximum value +% among all the cell types of the tissue is used. % hpaData : struct -% HPA data structure from parseHPA (optional if transcrData is supplied, -% default []). +% HPA data structure from parseHPA (required if transcrData is not +% supplied, default []). % % Name-Value Arguments % -------------------- % transcrData : struct -% gene expression data structure (optional if hpaData is supplied, default -% []). With fields: +% gene expression data structure (required if hpaData is not supplied, +% default []). With fields: % % - 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. +% - tissues : cell array with the tissue names. The list can contain +% duplicates, 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. +% each tissue and cell type. NaN marks a gene that was not measured. % - threshold : a single value or a vector of gene expression thresholds, -% above which genes are considered to be "expressed". (default 1; 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 (default []). -% - plotResults : true if single cell probability distributions should be -% plotted (default false). +% above which genes are considered to be "expressed". If omitted, the +% mean expression level of each gene across all tissues in transcrData +% is used as the threshold. % metabolomicsData : cell % cell array with metabolite names that the model should produce (default % []). % INITSteps : cell % specifies the steps in the algorithm. For more info, see INITStepDesc and -% getINITSteps (default getINITSteps(), which is the standard ftINIT). +% getINITSteps (default getINITSteps([],'1+1'), the standard ftINIT). % removeGenes : logical -% if true, low-abundance genes will be removed from grRules, unless they +% if true, low-score genes are 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 (default -% true). +% grRules are not modified; genes that were associated only with removed +% reactions are not present in the final model (default true). % useScoresForTasks : logical -% true if the calculated reaction scores should be used as weights when -% fitting to tasks (default true). +% true if the calculated reaction scores are used as weights when +% fitting to tasks. Scores above -0.1 are set to -0.1 for this step +% (default true). % paramsFT : struct -% *obsolete option*. +% solver parameters for the gap-filling step that fits the tasks, passed +% to fitTasks as params (default []). % verbose : logical -% if true, the MILP progression will be shown (default false). +% if true, the MILP progression is shown (default false). % resolveTies : logical -% if true, pin each step's degenerate MILP to a canonical answer instead -% of relying on the solver Seed alone: hold the score objective at its -% optimum, then minimise the count of removable ("on") reactions, then, -% among the sparsest, minimise their summed reaction-id rank. This -% applies to every main-extraction step and to the final gap-filling -% step (fitTasks' resolveTies) -- see raven-gecko-parity#104 and -% raven-toolbox's resolve_ties. In each main-extraction step but the -% last (ftINITInternalAlg) the fluxes, which set the direction and -% magnitude a reaction is forced at in the next step, then come from the -% least-total-flux solution for that on/off state and, among those, from -% the one with the least id-rank-weighted backward flux (a merged -% reaction ranked by the smallest original id in its group). The last -% step skips these flux phases, as no step reads its fluxes. A step -% whose primary solve stops at the time limit keeps its primary -% solution without any of these phases; the count and id-rank phases -% get half of the step's TimeLimit each, and a warning -% names each phase that does not prove optimal or finds no solution -% (default false). +% if true, the degenerate MILP of each step is solved to a canonical +% answer in addition to the solver Seed: the score objective is held at +% its optimum, then the count of removable ("on") reactions is +% minimised, then, among the sparsest solutions, their summed +% reaction-id rank is minimised. This applies to every main-extraction +% step and to the final gap-filling step (resolveTies of fitTasks); see +% raven-gecko-parity#104 and resolve_ties in raven-toolbox. In each +% main-extraction step except the last (ftINITInternalAlg), the fluxes +% set the direction and magnitude at which a reaction is forced in the +% next step. They are taken from the least-total-flux solution for that +% on/off state and, among those, from the solution with the least +% id-rank-weighted backward flux (a merged reaction is ranked by the +% smallest original id in its group). The last step skips these flux +% phases, as no later step reads its fluxes. A step whose primary solve +% stops at the time limit keeps its primary solution without any of +% these phases. The count and id-rank phases get half of the step's +% TimeLimit each. A warning names each phase that does not prove optimal +% or finds no solution. Measured with raven-toolbox's ftinit, whose phase +% handling differs from ftINIT, on one cell line (Human-GEM v2.0.0-38, +% seeds 1234 and 7, time limit 1800 s): two seeds with the default +% escalation differ by 110 reactions and 17 predicted essential genes, +% and with resolveTies alone by 41 reactions and 1 gene, at about 3.6 +% times the run time (about 14 min against 4 min) (default false). % proveAbsGap : double -% if set, prove each step to this fixed *absolute* MILP gap in a single -% solve, instead of the relative-gap escalation below (stp.MILPParams). -% The escalation's final near-zero-objective run otherwise accepts an -% arbitrary within-gap incumbent -- measured on genome-scale Human-GEM to -% return a solution 2.0-4.0 objective units below the true optimum (see -% raven-toolbox's prove_abs_gap and the ftINIT reproducibility study on -% raven-docs). 1.0 is the recommended value: tighter (down to 0.05) -% proves nothing further and costs substantially more runtime. Pairs -% naturally with resolveTies (default [], i.e. use the escalation). +% if set, each step is proven to this fixed absolute MILP gap in a single +% solve, replacing the relative-gap escalation in stp.MILPParams. The +% final near-zero-objective run of the escalation accepts an arbitrary +% incumbent within the gap. A warning is raised when a step reaches the +% time limit before the proof. The figures below were measured with +% raven-toolbox's ftinit, whose phase handling differs from ftINIT, on one +% cell line (Human-GEM v2.0.0-38, time limit 1800 s) with resolveTies on +% and without gap-filling, in a sweep over four seeds (1234, 7, 1 and 2). +% The step 1 objective of the escalation ended 4.0 to 12.0 units below the +% proven optimum; with seeds 1234 and 7 alone it ended 7.0 and 12.0 +% below. A value of 5.0 stopped 2.0 below the optimum for one seed (seed +% 2), and values from 2.0 to 0.05 reached it for all four seeds and gave +% the same models. Every primary solve of the steps (48 solves) ended +% optimal; the flux phases phase2c-minflux (3 of 4 seeds) and +% phase2d-direction (4 of 4 seeds) reached the time limit and were adopted +% as unproven incumbents. With 1.0 and resolveTies the models of two seeds +% differ by 1 reaction and 0 predicted essential genes, at about 26 times +% the run time of the default escalation (about 100 min against 4 min); +% the mean of a whole build was 5766 s at 0.05 and 5641 s at 1.0. The +% study recommends 1.0 together with resolveTies when the variation of +% resolveTies alone is too large and the run time is acceptable. Its +% full-pipeline runs used a time limit of 600 s per step and its +% determinism builds 1800 s (default [], which uses the escalation). % % Returns % ------- % model : struct % the resulting model structure. -% metProduction : double -% 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 canExchange: -% -% - -2 : metabolite name not found in model. -% - -1 : metabolite found, but it could not be produced. -% - 1 : metabolite could be produced. +% metProduction : logical +% array from the last MILP step that indicates which of the metabolites in +% metabolomicsData could be produced (true) or not (false). Metabolites +% with a producing reaction that is essential are not part of the MILP +% and are not in the array. The array is determined before the +% gap-filling for the defined tasks. To see which metabolites can be +% produced in the final model, use canExchange. % addedRxnsForTasks : cell % cell array of the reactions which were added in order to perform the % tasks. % deletedRxnsInINIT : cell -% cell array of reactions deleted because they could not carry flux (INIT -% requires a functional input model). +% cell array of the reactions of the template model that are not in the +% final model, excluding exchange reactions (these are all kept). It +% contains the reactions removed by the MILP steps that gap-filling did +% not add back. % fullMipRes : struct % the solver results from the last MILP step run. % % Notes % ----- -% 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 +% The template model keeps its exchange metabolites, +% since checkTasks and fitTasks put specific constraints on them for each +% task. The INIT algorithm removes exchange metabolites if any are % present. Use importModel(file,false) to import a model with exchange % metabolites remaining. % +% ftINIT passes a prodWeight of 5 (the reward for each produced metabolite of +% metabolomicsData) to ftINITInternalAlg, whose own default is 0.5. +% p=parseRAVENargs(varargin, {'transcrData',[]; 'metabolomicsData',[]; 'INITSteps',[]; 'removeGenes',[]; 'useScoresForTasks',[]; 'paramsFT',[]; 'verbose',false; 'resolveTies',false; 'proveAbsGap',[]}); transcrData=p.transcrData; diff --git a/src/INIT/ftINITInternalAlg.m b/src/INIT/ftINITInternalAlg.m index af29c682..1665b356 100644 --- a/src/INIT/ftINITInternalAlg.m +++ b/src/INIT/ftINITInternalAlg.m @@ -1,55 +1,61 @@ function [deletedRxns,metProduction,res,turnedOnRxns,fluxes]=ftINITInternalAlg(model,rxnScores,metData,essentialRxns,prodWeight,allowExcretion,remPosRev,params,startVals,fluxes,verbose,forceOn,resolveTies,rankKeys,pinFluxes) % ftINITInternalAlg -% This function runs the MILP for a step in ftINIT. +% Run the MILP for one step of 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. +% scores are reactions to exclude. Reactions with score 0 +% are not part of 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. +% have to be in the resulting model. ftINIT passes the +% reactions that the tasks require (see fitTasks) +% prodWeight a reward for each detected metabolite that has at least +% one producing reaction turned on; net production is not +% checked. The sum of these rewards and the scores for the +% reactions is optimised. The reward gives a reason for +% including reactions with a negative score for +% connectivity reasons, which gives a more functional +% network (default 0.5) +% allowExcretion true if excretion of all metabolites is 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 +% dead-ends, but not every reaction in the resulting model +% can 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 +% input model lacks exchange reactions, set it to true; +% with false a large part of the model is 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. +% startVals Start values for the MILP. ftINIT passes the result of +% the previous run when it reruns the MILP with a higher +% MIPGap +% fluxes Fluxes from the last run. The flux of an essential +% irreversible reaction is forced to at least +% min(0.99*|flux|, 0.1), clamped to the reaction's capacity +% in the forced direction (its upper bound, as ftINIT +% passes reactions in the forward direction) +% verbose If true, the MILP progression is shown. % forceOn minimum flux magnitude enforced through a reaction once % it is turned on in the MILP (optional, default 0.1) -% resolveTies if true, pin the MILP's degenerate optimum to a canonical -% answer instead of relying on the solver Seed alone: hold -% the score objective at its optimum, then minimise the -% count of "on" removable (negative-score) reactions, then, -% among the sparsest, minimise their summed reaction-id -% rank. Positive-score reactions carry a continuous, not a -% free binary, on/off variable (pinned near 1 by the score -% objective), so only the negative-score ones are a genuine -% tie to resolve. The fluxes are then taken from the +% resolveTies if true, the MILP's degenerate optimum is solved to a +% canonical answer in addition to the solver Seed: the +% score objective is held at its optimum, then the count +% of "on" removable (negative-score) reactions is +% minimised, then, among the sparsest solutions, their +% summed reaction-id rank is minimised. Positive-score +% reactions have a continuous on/off variable (pinned near +% 1 by the score objective) and only the negative-score +% ones have a binary on/off variable, so only these are +% tied. The fluxes are then taken from the % least-total-flux solution for that on/off state and, % among those, from the one with the least id-rank-weighted % backward flux, so the directions and forced magnitudes -% the next ftINIT step reads from them are pinned too -- -% matches raven-toolbox's resolve_ties +% the next ftINIT step reads from them are fixed too. +% This follows resolve_ties in raven-toolbox % (raven-gecko-parity#104). The phases are skipped when % the primary solve stops at params.TimeLimit, and the % primary solution is kept. Phases 2a and 2b get half of @@ -71,22 +77,22 @@ % % 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 +% metProduction logical array that indicates which of the metabolites in +% metData could be produced (true) or not (false). +% Metabolites with a producing reaction that is essential +% are not part of the MILP and are not in the array % 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 +% This function is the 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) +% Usage: [deletedRxns,metProduction,res,turnedOnRxns,fluxes]=ftINITInternalAlg(model,... +% rxnScores,metData,essentialRxns,prodWeight,allowExcretion,... +% remPosRev,params,startVals,fluxes,verbose,forceOn,resolveTies,... +% rankKeys,pinFluxes) if nargin < 12 || isempty(forceOn) forceOn = 0.1; diff --git a/src/INIT/getINITSteps.m b/src/INIT/getINITSteps.m index 7cbcdff1..afa7e051 100644 --- a/src/INIT/getINITSteps.m +++ b/src/INIT/getINITSteps.m @@ -1,38 +1,36 @@ function steps = getINITSteps(varargin) % getINITSteps Define the steps used as input to ftINIT. % -% Defines the steps in the way ftINIT is run. Note that all combinations of -% steps will not work. Avoid "exclude" if you want to define new -% ways to run the algorithm. +% Defines the steps in the way ftINIT is run. Not all combinations of steps +% work. A new series that sets the HowToUsePrevResults option to "exclude", +% which no predefined series uses, may not work. % % Name-Value Arguments % -------------------- % metsToIgnore : struct % structure describing mets that can be removed from the model before -% running ftINIT, such as water etc. With fields: +% running ftINIT, such as water and other ubiquitous metabolites. With fields: % % - simpleMets.mets : names of metabolites to remove. % - simpleMets.compsToKeep : compartments for which metabolites are kept. % -% (default []). +% (default []). Ignored for series "full". % series : char % describes the way to run ftINIT (default "1+1"): % -% - "1+1" : standard behavior. Step 1 and 2 described in the paper are +% - "1+1" : standard behaviour. 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 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 does not really add -% any extra information. Faster than "1+1 steps". -% - "2+0" : same as "2+1 steps", but skips step 3 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. +% slightly less accurate than "1+1". +% - "1+0" : same as "1+1", but skips step 3 described in the paper. +% The model includes many reactions without GPRs. The series suits +% structural comparison, because the reactions removed in step 3 can +% be arbitrary and add no information. Faster than "1+1". +% - "2+0" : same as "2+1", but skips step 3 described in the paper. +% Faster and slightly less accurate than "1+0", with similar results. +% - "full" : 1-step run, similar to tINIT, without the model +% simplifications that ftINIT applies in the other series. Accurate, but +% slow. This series is used for testing. % % Returns % ------- diff --git a/src/INIT/groupRxnScores.m b/src/INIT/groupRxnScores.m index 453af242..28e01e05 100644 --- a/src/INIT/groupRxnScores.m +++ b/src/INIT/groupRxnScores.m @@ -1,8 +1,8 @@ function newRxnScores = groupRxnScores(model, origRxnScores, origRxnIds, groupIds, origRxnsToZero) % groupRxnScores -% This function sums up the reaction scores for all reactions that were merged -% into one by the linear merge. -% +% Sums the reaction scores of 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. @@ -11,10 +11,11 @@ % the reaction was not merged with any other reaction. A % non-zero integer means the reaction was merged with all % other rxns sharing the same integer. -% origRxnsToZero A logical vector saying which of the original rxns that should not +% origRxnsToZero A logical vector saying which of the original rxns should not % be part of the problem; the score for these reactions is set to 0. -% To keep 0 uniquely meaning "excluded", any genuine rxnScore that is -% (or sums to) exactly 0 is nudged to 0.01 instead. +% Since 0 means "excluded", an original score of 0 and a group +% score that sums to 0 while at least one score of the group +% is not 0 are set to 0.01. newRxnScores = zeros(length(model.rxns),1); diff --git a/src/INIT/mergeLinear.m b/src/INIT/mergeLinear.m index 66847e98..cf08d8ac 100644 --- a/src/INIT/mergeLinear.m +++ b/src/INIT/mergeLinear.m @@ -1,10 +1,10 @@ function [reducedModel,origRxnIds,groupIds,reversedRxns]=mergeLinear(model, noMergeRxns) % 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. +% Simplifies a model by merging rxns with linear dependencies. It differs +% from the grouping in simplifyModel in two ways: +% 1) It returns which reactions were merged. +% 2) It also merges reversible reactions. +% The reduced model has no genes and empty grRules. % % model a model structure % noMergeRxns Cell array with reaction IDs that are not allowed to be @@ -17,7 +17,7 @@ % in the order of their first reaction in origRxnIds. % reversedRxns Vector of booleans, saying for each rxn if it is reversed in the combined rxns. % -% Usage: [reducedModel,origRxnIds,groupIds]=mergeLinear(model,noMergeRxns) +% Usage: [reducedModel,origRxnIds,groupIds,reversedRxns]=mergeLinear(model,noMergeRxns) reducedModel=model; diff --git a/src/INIT/parseHPA.m b/src/INIT/parseHPA.m index 1207f49e..5baf8c2f 100755 --- a/src/INIT/parseHPA.m +++ b/src/INIT/parseHPA.m @@ -10,8 +10,7 @@ % Name-Value Arguments % -------------------- % version : double -% accepted for backward compatibility but ignored; the format is now -% inferred from the column headers (default 19). +% ignored; the format is inferred from the column headers (default 19). % % Returns % ------- @@ -20,7 +19,7 @@ % % - genes : cell array with the unique gene IDs (Ensembl in v>=18) % - geneNames : cell array with the gene symbols (present in v>=18 only) -% - tissues : cell array with the tissue names (may not be unique; one +% - tissues : cell array with the tissue names (can repeat; one % entry per tissue-cell-type combination) % - celltypes : cell array with the cell type names for each tissue % - levels : cell array with the unique expression level labels diff --git a/src/INIT/parseHPArna.m b/src/INIT/parseHPArna.m index 3d6e7631..a955cbdf 100755 --- a/src/INIT/parseHPArna.m +++ b/src/INIT/parseHPArna.m @@ -10,8 +10,7 @@ % Name-Value Arguments % -------------------- % version : double -% accepted for backward compatibility but ignored; the format is now -% inferred from the column headers (default 19). +% ignored; the format is inferred from the column headers (default 19). % % Returns % ------- diff --git a/src/INIT/prepINITModel.m b/src/INIT/prepINITModel.m index e129778c..d2f96933 100644 --- a/src/INIT/prepINITModel.m +++ b/src/INIT/prepINITModel.m @@ -1,16 +1,15 @@ function prepData = prepINITModel(origRefModel, taskStruct, varargin) % prepINITModel Precompute omics-independent data for ftINIT. % -% Runs time-consuming calculation steps that are not dependent on the RNA-Seq -% data. +% Runs the calculation steps that do not depend on the omics data, once per +% template model. % % Parameters % ---------- % origRefModel : struct -% the model to use. Expected to be something such as Human-GEM, Mouse-GEM, -% etc. +% the template model, such as Human-GEM or Mouse-GEM. % taskStruct : struct -% the essential tasks. Can be loaded with for example +% the essential tasks, for example loaded with % taskStruct = parseTaskList('../data/metabolicTasks_Essential.txt'). % The task ids must be character vectors: a non-text id or a missing id % field raises RAVEN:badInput. Ids may repeat (for example as category @@ -23,31 +22,34 @@ % the spontaneous rxns (default {}). % convertGenes : logical % if true the genes are converted to gene names (from ENSEMBL). This -% relies on translateGrRules, which is distributed with Human-GEM rather -% than with RAVEN, so Human-GEM has to be on the MATLAB path (default -% false). +% uses translateGrRules, which is distributed with Human-GEM and not with +% RAVEN, so Human-GEM must be on the MATLAB path (default false). % customRxnsToIgnore : cell -% these reactions can be ignored in the ignore mask (specifying b7=1) -% (default {}). +% reactions that are left outside the MILP when bit b7 of the +% RxnsToIgnoreMask of INITStepDesc is 1 (default {}). % extComp : char -% name of the external compartment, typically 's' or 'e'. This is used for -% identifying exch and import rxns (default 'e'). +% name of the external compartment, such as 's' or 'e'. This is used for +% identifying exchange and import reactions (default 'e'). % skipScaling : logical -% 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 false). +% if true the scaling step is not run on the minimal model. The scaling +% removes large differences between the stoichiometric coefficients +% within a reaction (see rescaleModelForINIT), since such differences +% create numerical issues in the ftINIT algorithm due to limitations in +% solver resolution. The scaling changes the stoichiometry of the +% reactions with large differences, and some reactions can become unable +% to carry flux, which can make the solution infeasible. If the solution +% is infeasible, turning the scaling off may help; the bounds then stay as in +% the template and the MILP caps the per-reaction big-M at 1000 (bigMCap +% in ftINITInternalAlg). In raven-toolbox's ftinit on Human-GEM (one cell +% line, big_m 1000) the pipeline without scaling was feasible but took +% 157 s against 83 s with scaling. The bounds of the scaled model are set to 1000 where the upper bound is above 0 and +% to -1000 where the lower bound is below 0; zero bounds stay 0. Only the +% minModel is scaled; the scaling is not present in the final model +% (default false). % runParallel : logical -% true to run the task-essentiality check in Step 3 (checkTasks) across -% parallel workers, since each task is independent of the others (see -% parallelWorkersRAVEN). Default false, matching the previous (serial) -% behaviour. +% true to run the task-essentiality check (checkTasks) across parallel +% workers, since each task is independent of the others (see +% parallelWorkersRAVEN) (default false, serial). % % Returns % ------- diff --git a/src/INIT/rescaleModelForINIT.m b/src/INIT/rescaleModelForINIT.m index 4082b70e..f0b02d37 100644 --- a/src/INIT/rescaleModelForINIT.m +++ b/src/INIT/rescaleModelForINIT.m @@ -1,21 +1,24 @@ function model=rescaleModelForINIT(model, varargin) % rescaleModelForINIT Rescale a model to avoid large stoichiometric differences. % -% Rescales 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. +% Rescales the stoichiometric matrix for the MILP problem in ftINIT to reduce +% differences in flux magnitudes between reactions. Such differences cause, +% among other effects, difficulties with the tolerances for integer variables. +% In each reaction, each coefficient with an absolute value above +% maxStoichDiff times the smallest absolute coefficient of the reaction is +% set to that limit (keeping its sign). The reaction is then multiplied by a +% factor that sets the mean absolute coefficient to 1. % % Parameters % ---------- % model : struct -% the model to be modified (input and output). +% a model structure. % % Name-Value Arguments % -------------------- % maxStoichDiff : double -% all reactions with a stoichiometric coefficient higher than this will be -% scaled down (default 25). +% largest allowed ratio between the largest and the smallest absolute +% stoichiometric coefficient in a reaction (default 25). % % Returns % ------- diff --git a/src/INIT/scoreModel.m b/src/INIT/scoreModel.m index 60380615..cd0ee606 100644 --- a/src/INIT/scoreModel.m +++ b/src/INIT/scoreModel.m @@ -2,11 +2,8 @@ % scoreModel Score reactions and genes in a model with complex gene rules. % % 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 -% scoreModel. +% based on expression data from HPA, gene arrays or both. The model grRules +% should be standardised with standardizeGrRules before scoring. % % Parameters % ---------- @@ -20,26 +17,27 @@ % []). With fields: % % - 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. +% - tissues : cell array with the tissue names. The list can contain +% duplicates, 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. +% each tissue and cell type. NaN marks a gene that was not measured. % - 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). +% above which genes are considered to be "expressed". If omitted, the +% mean expression level of each gene across all tissues in arrayData +% is used as the threshold. % tissue : char -% tissue to score for. Should exist in either hpaData.tissues or -% arrayData.tissues. +% tissue to score for. Must exist in either hpaData.tissues or +% arrayData.tissues (matched without regard to case); otherwise an error +% is raised. % % Name-Value Arguments % -------------------- % celltype : char -% cell type to score for. Should exist in either hpaData.celltypes or -% arrayData.celltypes for this tissue (default is to use the max values -% among all the cell types for the tissue). +% cell type to score for. Must exist in either hpaData.celltypes or +% arrayData.celltypes (matched without regard to case); otherwise an error +% is raised (default [], which uses all cell types of the tissue, +% combined as set by multipleCellScoring). % noGeneScore : double % score for reactions without genes (default -2). % isozymeScoring : char @@ -55,8 +53,9 @@ % ("max" or "average") (default "max"). % hpaLevelScores : struct % structure with numerical scores for the expression level categories from -% HPA. The structure should have a "names" and a "scores" field (default, -% see code for default scores). +% HPA. The structure has a "names" and a "scores" field. The default names +% are High, Medium, Low, None, Strong, Moderate, Weak, Negative and Not +% detected, with the scores 20, 15, 10, -8, 20, 15, 10, -8 and -8. % dataPrecedence : char % how hpaData takes precedence over arrayData when both are supplied % (default "gene"): @@ -73,8 +72,9 @@ % scores for each of the reactions in model. % geneScores : double % scores for each of the genes in model. Genes which are not in the -% dataset(s) have NaN as scores, which removeLowScoreGenes reads as "no -% evidence" and leaves in place, where a negative score would be pruned. +% dataset(s) have NaN as scores. removeLowScoreGenes reads NaN as "no +% evidence" and leaves the gene in place, and prunes genes with a +% negative score. % hpaScores : double % 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. diff --git a/src/INIT/tINIT/getINITModel.m b/src/INIT/tINIT/getINITModel.m index e2bd52db..c7f3551f 100644 --- a/src/INIT/tINIT/getINITModel.m +++ b/src/INIT/tINIT/getINITModel.m @@ -1,36 +1,36 @@ function [model, metProduction, essentialRxnsForTasks, addedRxnsForTasks, deletedDeadEndRxns, deletedRxnsInINIT, taskReport]=getINITModel(refModel, tissue, varargin) % getINITModel Generate a model using the original tINIT algorithm. % -% Generates a model using the tINIT algorithm, based on proteomics and/or -% transcriptomics and/or metabolomics and/or metabolic tasks (PLoS Comput Biol. -% 2012;8(5):e1002518, Mol Syst Biol. 2014;10:721). +% Generates a model using the tINIT algorithm, from proteomics, +% transcriptomics, metabolomics and metabolic tasks in any combination (PLoS +% Comput Biol. 2012;8(5):e1002518, Mol Syst Biol. 2014;10:721). % -% ftINIT is the recommended method for context-specific model extraction. Use -% this function to reproduce models built with the original tINIT. It remains -% supported, and issues a RAVEN:legacyMethod notice once per session, which +% ftINIT replaces this function for context-specific model extraction. This +% function is kept to reproduce models built with the original tINIT. It +% issues a RAVEN:legacyMethod notice once per session, which % warning('off','RAVEN:legacyMethod') silences. % -% Not all settings are reachable through this function; runINIT and fitTasks -% can be called individually for the ones that are not. +% Not all settings are available through this function; runINIT and fitTasks +% can be called individually to set the others. % % Parameters % ---------- % refModel : struct -% 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: +% a model structure in the closed form (no exchange reactions open), +% imported with importModel(filename,false). A model that is not loaded +% with importModel can lack the "unconstrained" field, and the function +% then raises RAVEN:badInput. The field can be added with % model.unconstrained=false(numel(model.mets),1). % tissue : char -% tissue to score for. Should exist in either hpaData.tissues or -% arrayData.tissues. +% tissue to score for. Must exist in either hpaData.tissues or +% arrayData.tissues (scoreModel raises an error otherwise). % % Name-Value Arguments % -------------------- % celltype : char -% cell type to score for. Should exist in either hpaData.celltypes or -% arrayData.celltypes for this tissue (default is to use the best values -% among all the cell types for the tissue). +% cell type to score for. Must exist in either hpaData.celltypes or +% arrayData.celltypes (scoreModel raises an error otherwise). The default +% is to use the maximum values among all the cell types for the tissue. % hpaData : struct % HPA data structure from parseHPA (optional if arrayData is supplied, % default []). @@ -39,20 +39,19 @@ % []). With fields: % % - 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. +% - tissues : cell array with the tissue names. The list can contain +% duplicates, 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. +% each tissue and cell type. NaN marks a gene that was not measured. % - threshold : a single value or a vector of gene expression thresholds, -% above which genes are considered to be "expressed". (default, by -% default the mean expression levels of each gene across all tissues in -% arrayData will be used as the threshold values). +% above which genes are considered to be "expressed". If omitted, the +% mean expression level of each gene across all tissues in arrayData +% is used as the threshold. % - singleCells : binary value selecting whether to use the single-cell -% algorithm to identify expressed genes. If used, specify cell -% subpopulations in CELLTYPES (default []). -% - plotResults : true if single cell probability distributions should be +% algorithm to identify expressed genes. If used, the cell +% subpopulations are specified in celltypes (default []). +% - plotResults : true if single cell probability distributions are % plotted (default false). % metabolomicsData : cell % cell array with metabolite names that the model should produce (default @@ -60,33 +59,32 @@ % taskFile : char % a task list in Excel format. See parseTaskList for details (default []). % useScoresForTasks : logical -% true if the calculated reaction scores should be used as weights in the -% fitting to tasks (default true). +% true if the calculated reaction scores are used as weights in the +% fitting to tasks. Scores above -0.1 are set to -0.1 (default true). % printReport : logical -% true if a report should be printed to the screen (default true). +% true if a report is printed to the screen (default true). % taskStructure : struct -% task structure as from parseTaskList. Can be used as an alternative way -% to define tasks when Excel sheets are not suitable. Overrides taskFile -% (default []). +% task structure as returned by parseTaskList. It defines the tasks when +% Excel sheets are not used and overrides taskFile (default []). % params : struct % parameter structure for use by the INIT solver (default []). % paramsFT : struct % parameter structure for the fitTasks step (default []). % seed : double -% seed for the random number generator used to break ties among -% genes with equally uninformative (-Inf) scores, so which gene is -% kept is reproducible across runs (default: current rng state is -% left untouched). +% seed for the random number generator used to break ties among genes +% with equal uninformative (-Inf) scores, which makes the choice of the +% kept gene reproducible across runs (default [], which leaves the rng +% state unchanged). % % Returns % ------- % model : struct % the resulting model structure. % metProduction : double -% 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 canExchange: +% array that indicates which of the metabolites in metabolomicsData could +% be produced. The array is determined before the gap-filling for the +% defined tasks. To see which metabolites can be produced in the final +% model, use canExchange: % % - -2 : metabolite name not found in model. % - -1 : metabolite found, but it could not be produced. @@ -114,13 +112,13 @@ % % Notes % ----- -% 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. +% The model keeps its exchange metabolites, since checkTasks +% and fitTasks put specific constraints on them for each task. The INIT +% algorithm removes exchange metabolites if any are present. Use +% importModel(file,false) to import a model with exchange metabolites +% remaining. % -% See Also +% See also % -------- % ftINIT, prepINITModel, runINIT, scoreModel diff --git a/src/INIT/tINIT/runINIT.m b/src/INIT/tINIT/runINIT.m index 0d6824b4..fb0d705c 100644 --- a/src/INIT/tINIT/runINIT.m +++ b/src/INIT/tINIT/runINIT.m @@ -1,15 +1,16 @@ function [outModel, deletedRxns, metProduction, fValue]=runINIT(model,varargin) % runINIT Solve the MILP of the original INIT algorithm. % -% Generates a model using the INIT algorithm, based on proteomics and/or -% transcriptomics and/or metabolomics and/or metabolic tasks. This function is -% the actual implementation of the algorithm; see getINITModel for the +% Generates a model using the INIT algorithm, from proteomics, +% transcriptomics, metabolomics and metabolic tasks in any combination. This +% function is the implementation of the algorithm; see getINITModel for the % higher-level reconstruction function, and PLoS Comput Biol. 2012;8(5):e1002518 % for the formulation. % -% ftINIT is the recommended method for context-specific model extraction, and -% solves a different MILP in ftINITInternalAlg. This function remains -% supported, and issues a RAVEN:legacyMethod notice once per session, which +% ftINIT replaces this function for context-specific model extraction and +% solves a different MILP in ftINITInternalAlg. This function is kept to +% reproduce models built with the original INIT. It issues a +% RAVEN:legacyMethod notice once per session, which % warning('off','RAVEN:legacyMethod') silences. % % Parameters @@ -28,31 +29,35 @@ % (default []). % essentialRxns : cell % 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) (default []). +% resulting model. fitTasks passes the reactions that the tasks require +% (default []). % prodWeight : double -% 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 (default 0.5). +% a score for each metabolite that has net production. The sum of these +% weights and the scores for the reactions is optimised. Net production +% of metabolites gives a reason for including reactions with a negative +% score for connectivity reasons, which gives a more functional network +% (default 0.5). % allowExcretion : logical -% 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 +% true if excretion of all metabolites is allowed. This results in +% fewer reactions being considered dead-ends, but not every reaction in the +% resulting model can 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 +% lacks exchange reactions, set it to true; with false a large part of +% the model is excluded for connectivity reasons % (default false). % noRevLoops : logical -% 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) (default false). +% true if reversible reactions are constrained to carry flux in only one +% direction. This prevents reversible reactions from being assigned as +% connected wrongly (the forward and backward reactions can form a loop +% and therefore appear connected). It adds two binary variables per +% reversible reaction to the problem, which makes the MILP larger and more +% computationally intensive (default false). % params : struct % parameter structure for use by optimizeProb. +% eps : double +% the lower flux bound of a reaction that is turned on, which also +% applies to the essential reactions (capped by their upper bound) +% (default 1). % % Returns % ------- @@ -71,7 +76,7 @@ % objective value (sum of (the negative of) reaction scores for the % included reactions and prodWeight*number of produced metabolites). % -% See Also +% See also % -------- % getINITModel, ftINITInternalAlg, ftINIT diff --git a/src/analysis/FSEOF.m b/src/analysis/FSEOF.m index 627cfebf..85437177 100755 --- a/src/analysis/FSEOF.m +++ b/src/analysis/FSEOF.m @@ -3,10 +3,10 @@ % % Implements the Flux Scanning based on Enforced Objective Flux algorithm. % This function writes a tab-delimited file or prints to the 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. +% window. If an output is specified (targets), it also returns a structure +% indicating for each model reaction whether FSEOF identifies it as a target +% and the slope of the reaction when switching from biomass formation to +% product formation. % % Parameters % ---------- @@ -20,33 +20,35 @@ % Name-Value Arguments % -------------------- % iterations : double -% number of iterations (default 10). +% number of enforced target flux levels, equally spaced up to coefficient +% times the maximum target flux (default 10). % coefficient : double -% ratio of optimal target reaction flux, must be less than 1 -% (default 0.9). +% ratio of the maximum target reaction flux that is enforced at the last +% iteration, less than 1 (default 0.9). % outputFile : char % output filename (default prints to command window). % corrThreshold : double -% minimum absolute Pearson correlation coefficient between a -% reaction absolute flux and the enforced product flux for the -% reaction to be selected as a target. Values in [0, 1]; higher -% values require a more linear response and suppress LP alternative- -% optima noise (default 0.9). +% minimum absolute Pearson correlation coefficient between the absolute +% flux of a reaction and the enforced product flux for the reaction to be +% selected as a target. Values are in [0, 1]. The filter keeps reactions +% whose flux is close to linear in the enforced product flux, and a higher +% value keeps fewer reactions (default 0.9). % % Returns % ------- % targets : struct % structure with information for identified targets, with fields: % -% - logical : logical array, true for amplification targets (backward -% compatible alias for amplify). +% - logical : logical array, true for amplification targets (identical to +% amplify). % - amplify : logical array, reactions whose absolute flux increases % with enforced product flux. -% - knockdown : logical array, reactions driven toward but not to zero. -% - knockout : logical array, reactions driven to zero at max product. +% - knockdown : logical array, reactions whose absolute flux decreases but +% stays above zero at the highest enforced product flux. +% - knockout : logical array, reactions whose absolute flux decreases to +% zero at the highest enforced product flux. % - slope : numeric array with per-reaction regression slopes of -% absolute flux versus enforced product flux (all reactions, not -% just targets). +% absolute flux versus enforced product flux (for all reactions). % % Examples % -------- diff --git a/src/analysis/analyzeSampling.m b/src/analysis/analyzeSampling.m index 56d52d34..d5da5e7c 100755 --- a/src/analysis/analyzeSampling.m +++ b/src/analysis/analyzeSampling.m @@ -8,14 +8,12 @@ % ---------- % Tex : double % 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). +% reaction. The score is the Student t between the two conditions, or +% is calculated from a p-value by the inverse of the error function. +% Transcripts that increased in expression level have positive values +% and transcripts that decreased have negative values. A p-value does +% not give the direction of the change, so a score calculated from a +% p-value takes its sign from the direction of the expression change. % df : double % the degrees of freedom in the t-test. % solutionsA : double @@ -28,8 +26,8 @@ % Name-Value Arguments % -------------------- % printResults : logical -% prints the most significant reactions in each category -% (default false). +% true to print the 10 reactions with the highest probability in each +% category (default false). % % Returns % ------- diff --git a/src/analysis/compareFluxes.m b/src/analysis/compareFluxes.m index 4e9e303b..26361dfa 100644 --- a/src/analysis/compareFluxes.m +++ b/src/analysis/compareFluxes.m @@ -1,5 +1,5 @@ function result = compareFluxes(model, fluxes1, fluxes2, varargin) -% compareFluxes Find the most significant flux changes between two conditions. +% compareFluxes Find the reactions whose flux differs between two flux vectors. % % Compares two flux vectors from the same model and returns all reactions % that changed, sorted by absolute flux difference. Classifies reactions as @@ -8,22 +8,23 @@ % Parameters % ---------- % model : struct -% RAVEN model structure. +% a model structure. % fluxes1 : double -% reference flux vector (condition A, e.g. wild-type). +% reference flux vector (condition A, such as wild-type). % fluxes2 : double -% comparison flux vector (condition B, e.g. mutant or knockin). +% comparison flux vector (condition B, such as a mutant or knock-in). % % Name-Value Arguments % -------------------- % cutoff : double -% minimum |flux| to consider a reaction active (default 1e-8). +% minimum |flux| for a reaction to be active, and minimum |flux2 - flux1| +% for a reaction to be changed (default 1e-8). % metaboliteList : cell % cell array of metabolite names. Only reactions involving at least one -% of these metabolites are compared; every other reaction is left out of -% the result entirely. Matching is against model.metNames and is case -% insensitive. A name that matches no metabolite is reported as a warning -% rather than an error (default all reactions). +% of these metabolites are compared; all other reactions are excluded +% from every field of the result. Matching is against model.metNames and +% is case insensitive. A name that matches no metabolite is reported as +% a warning (default all reactions). % nMax : double % maximum rows printed in the summary table (default 20). % verbose : logical @@ -32,18 +33,25 @@ % Returns % ------- % result : struct -% .turnedOn — cell, rxn IDs newly active in fluxes2 -% .turnedOff — cell, rxn IDs silenced in fluxes2 -% .flipped — cell, rxn IDs that reversed sign between conditions -% .changed — struct with fields (all reactions with |dflux|>cutoff, -% sorted by |dflux| descending): -% .rxn — cell of reaction IDs -% .flux1 — double, flux in condition A -% .flux2 — double, flux in condition B -% .absDelta — double, |flux2 - flux1| -% .relChange — double, (flux2-flux1)/|flux1|; NaN when -% flux1 is near-zero (reaction emerged) -% .type — cell, 'on'|'off'|'flip'|'' per reaction +% structure with fields: +% +% - turnedOn : cell array with the IDs of reactions that are active in +% fluxes2 and not in fluxes1. +% - turnedOff : cell array with the IDs of reactions that are active in +% fluxes1 and not in fluxes2. +% - flipped : cell array with the IDs of reactions that are active in +% both conditions and change sign. +% - changed : struct with fields for all reactions with |flux2 - flux1| +% above cutoff, sorted by |flux2 - flux1| descending: +% +% - rxn : cell array with the reaction IDs. +% - flux1 : double array with the flux in condition A. +% - flux2 : double array with the flux in condition B. +% - absDelta : double array with |flux2 - flux1|. +% - relChange : double array with (flux2 - flux1)/|flux1|. NaN when +% |flux1| is below cutoff. +% - type : cell array with 'on', 'off', 'flip' or '' (changed +% magnitude) for each reaction. % % Examples % -------- @@ -55,7 +63,8 @@ % result = compareFluxes(model, solA.x, solB.x, 'metaboliteList', {'ATP','NADH'}) % % See also -% walkFluxes, traceFluxPath, modelSummary +% -------- +% walkFluxes, traceFluxPath, modelSummary p = parseRAVENargs(varargin, {'cutoff',1e-8; 'metaboliteList',[]; 'nMax',20; 'verbose',true}); cutoff = p.cutoff; diff --git a/src/analysis/findGeneDeletions.m b/src/analysis/findGeneDeletions.m index 14f4c0fa..9ad6d278 100755 --- a/src/analysis/findGeneDeletions.m +++ b/src/analysis/findGeneDeletions.m @@ -1,8 +1,9 @@ function [genes, fluxes, originalGenes, details, grRatioMuts]=findGeneDeletions(model,varargin) % findGeneDeletions Delete genes and track the resulting fluxes. % -% Deletes genes, optimizes the model by FBA, and keeps track of the -% resulting fluxes. This is used for identifying gene deletion targets. +% Deletes single genes or gene pairs, solves the model by FBA after each +% deletion, and returns the resulting fluxes. The output identifies gene +% deletion targets. % % Parameters % ---------- @@ -12,7 +13,7 @@ % Name-Value Arguments % -------------------- % testType : char -% single/double gene deletion (default "sgd"): +% type of gene deletion (default "sgd"): % % - "sgd" : single gene deletion % - "dgd" : double gene deletion @@ -20,7 +21,7 @@ % Returns % ------- % genes : double -% a matrix with the genes that were deleted in each optimization (the +% a matrix with the genes that were deleted in each simulation (the % gene indexes in originalGenes). Each row corresponds to a column in % fluxes. % fluxes : double @@ -28,25 +29,23 @@ % an unsolvable problem have all zero flux. Single deletions that % result in an unsolvable problem are indicated in details instead. % originalGenes : cell -% simply the genes in the input model. Included for simple -% presentation of the output. +% the genes in the input model. % details : double -% 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: +% a vector with one element per gene in originalGenes that states +% whether the gene was deleted and why. Genes that only belong to +% dead-end reactions, for example, are not deleted: % -% - 1 : was deleted, and the problem was solved (a lethal deletion +% - 1 : deleted, and the problem was solved (a lethal deletion % with zero growth also gets 1) % - 2 : the single-deletion problem had no optimal solution % (infeasible or failed); fluxes and grRatioMuts are 0 -% - 3 : redundant, no longer used +% - 3 : redundant (not assigned) % - 4 : involved in dead-end reaction % grRatioMuts : double % growth rate ratio between mutated strain and wild type, matching 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: +% originalGenes(genes) mutants. The elements do not map directly to +% model.genes, unlike the output of COBRA getEssentialGenes. The +% mapping to model.genes is obtained with: % % grRatio=zeros(1,numel(model.genes)); % grRatio(genes)=grRatioMuts; diff --git a/src/analysis/getAllSubGraphs.m b/src/analysis/getAllSubGraphs.m index e8a869ef..17f6cdac 100755 --- a/src/analysis/getAllSubGraphs.m +++ b/src/analysis/getAllSubGraphs.m @@ -11,9 +11,9 @@ % Returns % ------- % subGraphs : logical -% 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. +% a logical matrix with one row per metabolite and one column per +% subgraph. An element is true if the metabolite belongs to the +% subgraph. The columns are ordered by decreasing subgraph size. % % Examples % -------- diff --git a/src/analysis/getAllowedBounds.m b/src/analysis/getAllowedBounds.m index 41d9b08e..68a88805 100755 --- a/src/analysis/getAllowedBounds.m +++ b/src/analysis/getAllowedBounds.m @@ -13,12 +13,11 @@ % number of elements as reactions in the model, or a vector of % reaction indexes (default model.rxns). % runParallel : logical -% 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 of what is -% indicated as runParallel (default true). +% run the calculations in parallel (default true). Parallel processing +% requires the MATLAB Parallel Computing Toolbox; without it, the +% calculations run serially regardless of this setting. For a few +% reactions, the overhead of parallel processing exceeds the time it +% saves. % % Returns % ------- @@ -27,8 +26,9 @@ % maxFluxes : double % maximal allowed fluxes. % exitFlags : double -% exit flags for min/max for each of the reactions. True if it was -% possible to calculate a flux. +% a matrix with one row per reaction. Column 1 holds the solver status +% of the minimisation and column 2 the status of the maximisation +% (1 if a flux could be calculated). % % Notes % ----- diff --git a/src/analysis/getFluxZ.m b/src/analysis/getFluxZ.m index f705cfe3..3f28155d 100755 --- a/src/analysis/getFluxZ.m +++ b/src/analysis/getFluxZ.m @@ -13,9 +13,12 @@ % Returns % ------- % Z : double -% 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. +% a vector with one Z-score per reaction: the difference between the +% mean fluxes of solutionsB and solutionsA, divided by the square root +% of the sum of their variances. A positive sign indicates an increase +% of the flux in the second condition with respect to the first, a +% negative sign a decrease. Values are limited to the range -100 to +% 100. % % Examples % -------- diff --git a/src/analysis/getMinimalMedium.m b/src/analysis/getMinimalMedium.m index 186f044b..b4c7c496 100644 --- a/src/analysis/getMinimalMedium.m +++ b/src/analysis/getMinimalMedium.m @@ -2,21 +2,22 @@ % getMinimalMedium Find the minimal set of uptake reactions for growth. % % Uses MILP to find the smallest set of exchange reactions that can carry -% uptake flux (lb < 0) while still allowing the model to achieve a target -% growth rate. Unlike iterative heuristics, the MILP formulation finds the -% globally minimal medium. +% uptake flux (lb < 0) while the model achieves a target growth rate. The +% MILP formulation gives a medium with the globally minimal number of +% uptake reactions. % % Parameters % ---------- % model : struct -% RAVEN model structure. +% a model structure. % % Name-Value Arguments % -------------------- % minGrowth : double -% minimum objective value (growth rate) the medium must support. -% Defaults to 10 % of the unconstrained optimum computed automatically. -% Set explicitly to avoid an extra FBA call (e.g. 'minGrowth', 0.1). +% minimum objective value (growth rate) the medium must support. If +% empty, 10 % of the optimum objective value under the current bounds, +% which requires one extra FBA call. A value given explicitly avoids +% that call (for example 'minGrowth', 0.1) (default empty). % verbose : logical % print the resulting minimal medium (default true). % @@ -36,9 +37,8 @@ % % Notes % ----- -% Only exchange reactions with lb < 0 are considered as candidate uptake -% reactions. Exchange reactions that are always secretion-only (lb >= 0) or -% that are completely blocked are not included. +% Only exchange reactions with lb < 0 are candidate uptake reactions. +% Exchange reactions with lb >= 0 are not included. % % The MILP formulation: % minimise sum(y_i) @@ -51,15 +51,15 @@ % A y_i = 0 forces reaction i to carry non-negative flux (no net uptake); % y_i = 1 allows it to carry flux as low as lb_i. % -% The minimal number of uptakes is guaranteed, but the medium itself need -% not be unique: when several media of the same size support the growth -% rate, the solver returns one of them, and another solver or solver -% version can return a different one. +% The number of uptake reactions is minimal, but the medium is not +% necessarily unique: when several media of the same size support the +% growth rate, the solver returns one of them, and another solver or +% solver version can return a different one. % % The MILP is solved with the solver set by setRavenSolver. RAVEN's bundled -% GLPK solves it for small models (with a RAVEN:glpkMILP warning); for -% larger models Gurobi is much faster and more reliable -% (setRavenSolver('gurobi')). +% GLPK solves it for small models. The RAVEN:glpkMILP warning issued with +% GLPK states that GLPK works for small problems and that Gurobi is much +% faster and more reliable for larger ones (setRavenSolver('gurobi')). p = parseRAVENargs(varargin, {'minGrowth',[]; 'verbose',true}); minGrowth = p.minGrowth; diff --git a/src/analysis/haveFlux.m b/src/analysis/haveFlux.m index fc04d630..c76a020a 100755 --- a/src/analysis/haveFlux.m +++ b/src/analysis/haveFlux.m @@ -2,9 +2,10 @@ % haveFlux Check which reactions can carry a flux. % % Checks which reactions can carry a (positive or negative) flux under the -% model's current bounds; other media or bounds are not explored. Is used -% as a faster version of getAllowedBounds if it is only interesting whether -% the reactions can carry a flux or not. +% model's current bounds; other media or bounds are not explored. Unlike +% getAllowedBounds, which minimises and maximises every reaction, it skips a +% reaction once an earlier solution has given it a flux, and minimises only +% reversible reactions that still have none. % % Parameters % ---------- @@ -14,16 +15,16 @@ % Name-Value Arguments % -------------------- % cutOff : double -% the flux value that a reaction has to carry to be identified as -% positive (default 10^-6). +% the absolute flux value that a reaction has to exceed to be identified +% as carrying flux (default 10^-6). % rxns : cell or logical or double % 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 (default +% elements as reactions in the model, or a vector of indexes (default % model.rxns). % seed : double -% seed for the random number generator used to shuffle the order in -% which reactions are tested, so that order is reproducible across -% runs (default: current rng state is left untouched). +% seed for the random number generator that shuffles the order in +% which reactions are tested. The order is then reproducible across +% runs (default: the current rng state is left untouched). % % Returns % ------- @@ -37,8 +38,7 @@ % % Notes % ----- -% If a model has +/- Inf bounds then those are replaced with an arbitary -% large value of +/- 10000 prior to solving. +% Bounds of +/- Inf are replaced with +/- 10000 before solving. % % Dead-end reactions are removed (simplifyModel) before solving. A dead-end % reaction with a forced flux (lb > 0 or ub < 0) makes the model infeasible, diff --git a/src/analysis/randomSampling.m b/src/analysis/randomSampling.m index 8d3347fe..2f1360dd 100755 --- a/src/analysis/randomSampling.m +++ b/src/analysis/randomSampling.m @@ -5,18 +5,19 @@ % 'achr' (default) Artificially Centered Hit-and-Run; near-uniform MCMC % sampling of the polytope interior (see sampleACHR). % 'chrr' Coordinate Hit-and-Run with Rounding; near-uniform MCMC -% with maximum-volume-ellipsoid rounding, for better mixing -% on thin/ill-conditioned polytopes such as enzyme- -% constrained models (see sampleCHRR). +% with maximum-volume-ellipsoid rounding, which improves +% mixing on thin or ill-conditioned polytopes such as +% enzyme-constrained models (see sampleCHRR). % 'randomObjective' the random-objective vertex method of Bordel et al. (2010) % PLoS Comput Biol (doi:10.1371/journal.pcbi.1000859): each -% sample maximises a small random objective, returning a -% polytope vertex. +% sample optimises a random objective of nObjectives +% reactions with random weights, returning a polytope +% vertex. % -% The 'achr'/'chrr' methods draw the (near-)uniform interior distribution; the -% 'randomObjective' method draws diverse vertices. Arguments below marked -% [randomObjective] apply only to that method; 'thinning'/'nBurnin' apply only -% to the MCMC methods. +% The 'achr' and 'chrr' methods draw from the (near-)uniform distribution +% over the interior; the 'randomObjective' method draws vertices. Arguments +% below marked [randomObjective] apply only to that method; 'thinning' and +% 'nBurnin' apply only to the MCMC methods. % % Parameters % ---------- @@ -30,35 +31,36 @@ % method : char % sampling method: 'achr' (default), 'chrr', or 'randomObjective'. % thinning : double -% MCMC steps between recorded samples for 'achr'/'chrr' (default 100). +% MCMC steps between recorded samples for 'achr' and 'chrr' (default 100). % nBurnin : double % burn-in steps discarded before the first sample for 'chrr' (default 1000). % replaceBoundsWithInf : logical % [randomObjective] % replace the largest upper bounds with Inf and the smallest lower -% bounds with -Inf. This is needed to get solutions without loops if -% your model has, for example, 1000/-1000 as arbitrarily large bounds. -% If your model only has "biologically relevant" bounds, then set this -% to false (default true). +% bounds with -Inf (the latter only if the smallest lower bound is +% negative). This is required to get solutions without loops if the +% model has arbitrarily large bounds, for example 1000 and -1000. A +% model with only biologically relevant bounds can use false +% (default true). % supressErrors : logical -% 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) (default false). +% if false, randomSampling raises an error after 99 consecutive failed +% attempts to find a non-zero solution that is not involved in loops. +% Failures can result from constraints that are too relaxed (such as +% unlimited glucose uptake) or too strict (such as many narrow +% constraints). If true, the attempts continue without an error +% (default false). % runParallel : logical -% speed up calculations by parallel processing. Requires the MATLAB -% Parallel Computing Toolbox. If this is not installed, the calculations -% will not be parallelized, regardless of what is indicated as -% runParallel (default true). +% run the calculations in parallel (default true). Requires the MATLAB +% Parallel Computing Toolbox; without it, the calculations run serially +% regardless of this setting. % 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 (default empty). % minFlux : logical -% determines if a second optimization should be performed for each -% random sample, to minimize the number of fluxes and thereby prevent -% loops. Typically, loops are averaged out when a large number of -% samples are taken, but this is not always the case (default false). +% determines if a second optimisation is performed for each random +% sample, which minimises the sum of absolute fluxes to prevent loops +% (default false). % nObjectives : double % number of reactions included in the random objective function per % sample iteration (default 2). @@ -81,16 +83,17 @@ % % Notes % ----- -% With 'randomObjective', the solutions are generated by maximizing (with -% random weights) for a random set of nObjectives reactions (default 2). -% For reversible reactions it randomly chooses between maximizing and -% minimizing. The default 'achr' and the 'chrr' methods use no random -% objectives; they take hit-and-run steps through the interior of the -% solution space. +% With 'randomObjective', the solutions are generated by optimising (with +% random weights) a random set of nObjectives reactions (default 2). The +% sign of each weight is chosen at random, which selects maximisation or +% minimisation of the reaction; reactions with an upper bound below 0 always +% receive a positive weight. The default 'achr' and the 'chrr' methods use +% no random objectives; they take hit-and-run steps through the interior of +% the solution space. % % 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. +% selected as random objectives; the objectives are drawn from the +% metabolic reactions. % % Examples % -------- @@ -98,7 +101,7 @@ % solutions = randomSampling(model, 1000); % % Coordinate hit-and-run with rounding: % solutions = randomSampling(model, 1000, 'method', 'chrr', 'seed', 1); -% % Historical random-objective vertex method: +% % Random-objective vertex method: % solutions = randomSampling(model, 1000, 'method', 'randomObjective'); % % See also diff --git a/src/analysis/reporterMetabolites.m b/src/analysis/reporterMetabolites.m index 47256351..209d3cc6 100755 --- a/src/analysis/reporterMetabolites.m +++ b/src/analysis/reporterMetabolites.m @@ -1,15 +1,15 @@ function repMets=reporterMetabolites(model,genes,genePValues,varargin) % reporterMetabolites Identify metabolites around which transcriptional changes occur. % -% The Reporter Metabolites algorithm for identifying metabolites around -% which transcriptional changes occur. +% Applies the Reporter Metabolites algorithm, which scores each metabolite +% by the differential expression of the genes around it. % % Parameters % ---------- % model : struct % a model structure. % genes : cell -% a cell array of gene names (should match with model.genes). +% a cell array of gene names (matching model.genes). % genePValues : double % P-values for differential expression of the genes. Values must lie in % [0, 1]; NaN values are ignored, any other value raises an error. @@ -17,14 +17,15 @@ % Name-Value Arguments % -------------------- % printResults : logical -% true if the top 20 Reporter Metabolites should be printed to the -% screen (default false). +% true to print the top 20 Reporter Metabolites to the screen +% (default false). % outputFile : char % the results are printed to this file (default none). % geneFoldChanges : double -% 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 (default none). +% log-fold changes for the genes. If supplied, Reporter Metabolites are +% also calculated for the upregulated genes (fold change >= 0) alone and +% for the downregulated genes (fold change < 0) alone, in addition to +% the full test (default none). % % Returns % ------- @@ -32,11 +33,13 @@ % an array of structures with the following fields: % % - test : a string that describes the genes used to calculate the -% Reporter Metabolites ("all", "only up", or "only down"). The two -% latter structures are only calculated if geneFoldChanges are +% Reporter Metabolites ("all", "only up", or "only down"). The tests +% "only up" and "only down" are only calculated if geneFoldChanges is % supplied. % - mets : a cell array of metabolite IDs for the metabolites for which % a score could be calculated. +% - metNames : a cell array with the names of the metabolites in +% "mets". % - metZScores : background-corrected Z-scores for differential % expression around each metabolite in "mets". The entries of all % fields are sorted by this score, highest first. diff --git a/src/analysis/runDynamicFBA.m b/src/analysis/runDynamicFBA.m index f07d466b..088539f6 100755 --- a/src/analysis/runDynamicFBA.m +++ b/src/analysis/runDynamicFBA.m @@ -1,5 +1,5 @@ function [concentrationMatrix, excRxnNames, timeVec, biomassVec] = runDynamicFBA(model, substrateRxns, initConcentrations, initBiomass, timeStep, nSteps, plotRxns, exclUptakeRxns) -% runDynamicFBA Perform dynamic FBA using the static optimization approach. +% runDynamicFBA Perform dynamic FBA using the static optimisation approach. % % Parameters % ---------- @@ -7,8 +7,8 @@ % a model structure. % substrateRxns : cell % cell array with exchange reaction identifiers for substrates that are -% initially in the media, whose concentration may change (e.g. not h2o -% or co2). +% initially in the media, whose concentration may change (for example +% not h2o or co2). % initConcentrations : double % initial concentrations of substrates (matching substrateRxns). % initBiomass : double @@ -22,7 +22,7 @@ % concentration should be plotted. % exclUptakeRxns : cell % cell array with exchange reaction identifiers for substrates whose -% concentration does not change (e.g. co2, o2, h2o, h). +% concentration does not change (for example co2, o2, h2o, h). % % Returns % ------- @@ -45,12 +45,11 @@ % Notes % ----- % 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. +% uptake in the model (that is, model.lb < 0), the initial concentration is set +% to 1000. If the uptake bound calculated from the concentration exceeds +% the maximum uptake rate specified in the model for that nutrient, and the +% maximum uptake rate specified is > 0, the maximum uptake rate specified +% in the model is used as the uptake bound. % % Modified from COBRA Toolbox dynamicFBA.m. diff --git a/src/analysis/runProductionEnvelope.m b/src/analysis/runProductionEnvelope.m index a4fa966b..238437ca 100755 --- a/src/analysis/runProductionEnvelope.m +++ b/src/analysis/runProductionEnvelope.m @@ -13,14 +13,18 @@ % Name-Value Arguments % -------------------- % nPts : double -% number of points in the plot (default 20). +% number of biomass values at which the target bounds are calculated +% (default 20). % % Returns % ------- % biomassValues : double -% biomass values for plotting. +% nPts biomass values, evenly spaced from the minimum to the maximum +% biomass flux. % targetValues : double -% target upper and lower bounds for plotting. +% a matrix with two rows: the lower bounds (row 1) and the upper bounds +% (row 2) of the target reaction flux at each biomass value. NaN where +% the problem has no solution. % % Examples % -------- diff --git a/src/analysis/runRobustnessAnalysis.m b/src/analysis/runRobustnessAnalysis.m index c80c8299..032ffceb 100755 --- a/src/analysis/runRobustnessAnalysis.m +++ b/src/analysis/runRobustnessAnalysis.m @@ -1,8 +1,9 @@ function [controlFlux, objFlux] = runRobustnessAnalysis(model, controlRxn, varargin) % runRobustnessAnalysis Perform robustness analysis for a reaction and objective. % -% Performs robustness analysis for a reaction of interest and an objective -% of interest. +% Varies the flux of a reaction of interest from its minimum to its maximum +% and calculates the optimal value of an objective of interest at each +% flux. % % Parameters % ---------- @@ -14,12 +15,13 @@ % Name-Value Arguments % -------------------- % nPoints : double -% number of points to show on plot (default 20). +% number of control flux values (default 20). % objRxn : char -% reaction identifier of objective to be maximized (default uses the +% reaction identifier of the objective to be maximised (default: the % objective defined in the model). % plotRedCost : logical -% whether reduced cost should also be plotted (default false). +% whether the reduced cost of the control reaction is also plotted on +% the right axis (default false). % % Returns % ------- diff --git a/src/analysis/runSimpleOptKnock.m b/src/analysis/runSimpleOptKnock.m index b3fd9346..173505cd 100755 --- a/src/analysis/runSimpleOptKnock.m +++ b/src/analysis/runSimpleOptKnock.m @@ -1,10 +1,14 @@ function out = runSimpleOptKnock(model, targetRxn, biomassRxn, varargin) -% runSimpleOptKnock Simple OptKnock for growth-coupled production. +% runSimpleOptKnock Find deletions that couple metabolite production to growth. % -% 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). +% Checks all gene or reaction deletions for growth-coupled metabolite +% production, by testing combinations of up to maxNumKO deletions. It tries +% a deeper deletion only after a deletion whose growth rate is above +% minGrowth. A combination is reported if the growth rate exceeds +% minGrowth and the product of growth rate and production rate exceeds the +% value without the last added deletion (the wild type for the first +% deletion) by more than 1 %. The method is not defined as a MILP and is +% therefore slow. % % Parameters % ---------- @@ -37,6 +41,7 @@ % - 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. +% - score : vector with the product of growth rate and production rate. % % Examples % -------- diff --git a/src/analysis/sampleACHR.m b/src/analysis/sampleACHR.m index 355a06cb..124843b6 100644 --- a/src/analysis/sampleACHR.m +++ b/src/analysis/sampleACHR.m @@ -3,8 +3,9 @@ % % Draws nSamples flux vectors approximately uniformly from the flux polytope % {v : S*v = 0, lb <= v <= ub}, using the ACHR algorithm (Kaufman & Smith 1998). -% No rounding is performed, so on strongly elongated polytopes (e.g. -% enzyme-constrained models) mixing is slower than sampleCHRR; prefer CHRR there. +% No rounding is performed, so on strongly elongated polytopes (for example +% enzyme-constrained models) mixing is slower than with sampleCHRR, which +% rounds the polytope. % Reactions whose bounds or warmup values coincide never move. The remaining % reactions are corrected towards S*v = 0 every few steps and before each % recorded sample, with a sparse Cholesky factor of the row-normalised S*S' @@ -18,7 +19,7 @@ % Parameters % ---------- % model : struct -% a RAVEN model structure. +% a model structure. % nSamples : double % number of flux vectors to return (default 1000). % thinning : double diff --git a/src/analysis/sampleCHRR.m b/src/analysis/sampleCHRR.m index fe81ad59..53a9548d 100644 --- a/src/analysis/sampleCHRR.m +++ b/src/analysis/sampleCHRR.m @@ -3,17 +3,18 @@ % % Draws nSamples flux vectors approximately uniformly from the flux polytope % {v : S*v = 0, lb <= v <= ub}, using the CHRR algorithm (Haraldsdottir et al. -% 2017, Bioinformatics 33:1741). The polytope is rounded before sampling, so -% mixing stays fast even on strongly elongated polytopes (e.g. -% enzyme-constrained models), unlike sampleACHR. +% 2017, Bioinformatics 33:1741). The polytope is rounded before sampling, +% which improves mixing on strongly elongated polytopes (for example +% enzyme-constrained models) in comparison with sampleACHR, which does not +% round. % -% Set any constraints you want to condition on (e.g. a biomass lower bound or -% measured exchange fluxes) on the model before calling. +% Constraints to condition on (for example a biomass lower bound or measured +% exchange fluxes) are set on the model before the call. % % Parameters % ---------- % model : struct -% a RAVEN model structure. +% a model structure. % nSamples : double % number of flux vectors to return (default 1000). % thinning : double @@ -24,17 +25,18 @@ % random seed for reproducibility (default: current RNG state). % fixedWidthTol : double % a reaction whose allowed flux range is narrower than this is treated as -% stoichiometrically fixed and folded into the equality system, keeping the -% reduced polytope full-dimensional (default 1e-7). +% stoichiometrically fixed and added to the equality system at the middle +% of its range, which keeps the reduced polytope full-dimensional +% (default 1e-7). % % Returns % ------- % solutions : double % nRxns-by-nSamples matrix of sampled flux distributions. % info : struct -% .nDimensions — dimension of the sampled flux polytope -% .mveConverged — whether MVE rounding reached tolerance -% .fixedRxns — IDs of reactions folded in as fixed +% .nDimensions : dimension of the sampled flux polytope +% .mveConverged : whether MVE rounding reached tolerance +% .fixedRxns : IDs of reactions added to the equality system as fixed % % See also % -------- diff --git a/src/analysis/sampleMaxVolEllipse.m b/src/analysis/sampleMaxVolEllipse.m index 314e6630..ac2259e4 100644 --- a/src/analysis/sampleMaxVolEllipse.m +++ b/src/analysis/sampleMaxVolEllipse.m @@ -6,7 +6,7 @@ % {z : A*z <= b}, using the Zhang & Gao (2003) primal-dual interior-point % method (the regularised variant used in COBRA's CHRR sampler). This is the % rounding step of sampleCHRR: the returned transform E maps the polytope to a -% well-conditioned body in which coordinate hit-and-run mixes rapidly. +% well-conditioned body in which coordinate hit-and-run samples. % % This function is pure linear algebra (no LP solver) except when x0 is empty, % in which case a Chebyshev centre is obtained via sampleChebyshevCenter. @@ -26,8 +26,8 @@ % tol : double (optional) % convergence tolerance (default 1e-6). % reg : double (optional) -% diagonal / Levenberg regularisation keeping the Newton solves -% well-conditioned (default 1e-8). +% diagonal (Levenberg) regularisation of the Newton solves +% (default 1e-8). % % Returns % ------- @@ -37,14 +37,15 @@ % n-by-n lower-triangular rounding transform with E*E' = E2 (the SPD % ellipsoid matrix). The rounding substitution is z = x + E*y. % converged : logical -% whether tol was reached within maxiter. A false value is not fatal — -% the last iterate is still a valid (if looser) rounding. +% whether tol was reached within maxiter. If false, the last iterate +% is returned as the centre and transform, which is a valid but looser +% rounding. % % Notes % ----- -% Validated against analytic cases: a box maps to the unit ball (E = I); a -% sheared box {z : -1 <= M*z <= 1} gives E*E' = inv(M)*inv(M)'; a triangle -% gives its Steiner inellipse. +% Analytic cases, tested in tSampling: a box maps to the unit ball (E = I); +% a sheared box {z : -1 <= M*z <= 1} gives E*E' = inv(M)*inv(M)'; a +% triangle gives its Steiner inellipse. % % Based on Y. Zhang & L. Gao (2003), SIAM J. Optim. 14:53-76; as used in % Haraldsdottir et al. (2017) Bioinformatics 33:1741 (CHRR). diff --git a/src/analysis/sampleWarmupPoints.m b/src/analysis/sampleWarmupPoints.m index 6edff507..688e7fff 100644 --- a/src/analysis/sampleWarmupPoints.m +++ b/src/analysis/sampleWarmupPoints.m @@ -3,18 +3,19 @@ % % Generates warmup points for sampleACHR by maximising and minimising each % reaction in turn and storing the full flux distribution at each optimum. -% These vertices span the flux polytope and seed the hit-and-run directions. +% These vertices span the flux polytope and define the hit-and-run +% directions. % % Parameters % ---------- % model : struct -% a RAVEN model structure. +% a model structure. % % Name-Value Arguments % -------------------- % runParallel : logical -% speed up calculations by parallel processing, as in getAllowedBounds, -% which solves the same per-reaction min/max LPs (default true). +% run the calculations in parallel, as in getAllowedBounds, which solves +% the same per-reaction minimisation and maximisation LPs (default true). % % Returns % ------- diff --git a/src/analysis/traceFluxPath.m b/src/analysis/traceFluxPath.m index 45b01bce..1ea425a9 100644 --- a/src/analysis/traceFluxPath.m +++ b/src/analysis/traceFluxPath.m @@ -5,16 +5,16 @@ % network, quantifying what fraction of the source reaction's flux reaches % the target. At each metabolite junction the flux is split proportionally % among all consuming reactions; the path with the highest cumulative -% fraction is returned and printed. +% fraction is returned, and printed if verbose is true. % -% By default the search excludes currency metabolites (ATP, NAD, H2O, etc.) -% so the returned path represents material (carbon-skeleton) flow rather -% than cofactor shortcuts. Set traceMaterial=false to disable this. +% By default the search excludes currency metabolites (for example ATP, +% NAD, H2O), which makes the returned path follow material flow. The +% setting traceMaterial=false disables this. % % Parameters % ---------- % model : struct -% RAVEN model structure. +% a model structure. % fluxes : double % flux vector (length = numel(model.rxns)). % fromRxn : char @@ -25,25 +25,27 @@ % Name-Value Arguments % -------------------- % cutoff : double -% minimum |flux| for a reaction to be considered flux-carrying -% (default 1e-8). +% minimum net flux through a metabolite (|S_ij * v_j|) for a consuming +% reaction to be considered (default 1e-8). % maxHops : double -% maximum number of reactions in the path; longer paths are pruned -% (default 30). +% paths of more than maxHops reactions are not extended further, so a +% returned path has at most maxHops + 1 reactions (default 30). % verbose : logical % print the path to the command window (default true). % traceMaterial : logical -% exclude common currency/cofactor metabolites (ATP, ADP, NAD, NADH, -% H2O, CoA, Pi, CO2, …) so the path follows material (carbon-skeleton) -% flux rather than energy-carrier shortcuts (default true). +% exclude common currency and cofactor metabolites (ATP, ADP, NAD, NADH, +% H2O, CoA, Pi, CO2 and others); the path then follows material flux +% (default true). % carbonOnly : logical % additionally require each intermediate metabolite to contain at least % one carbon atom, inferred from model.metFormulas. Drops H+, H2O, Pi, -% O2, NH3, CO2 that are not already caught by the currency list. -% Silently ignored when model.metFormulas is absent (default false). +% O2, NH3, CO2 that are not already caught by the currency list. Ignored +% with a warning when model.metFormulas is absent or empty +% (default false). % excludeMets : cell of char % extra metabolite names or IDs (after stripping compartment suffix) to -% exclude, in addition to the built-in currency list (default {}). +% exclude, in addition to the built-in currency list (which applies when +% traceMaterial is true) (default {}). % % Returns % ------- @@ -53,13 +55,13 @@ % pathMets : cell % metabolite IDs at each junction (numel = numel(pathRxns)-1). % cumFrac : double -% fraction of fromRxn's flux that routes through this exact path +% fraction of fromRxn's flux that passes through this exact path % (0 = no path found, 1 = all flux reaches toRxn directly). % % Examples % -------- % [p, m, f] = traceFluxPath(model, sol.x, 'PFK', 'ATPS4rpp') -% % disable material filter to see all connections including ATP/ADP: +% % disable material filter to see all connections including ATP and ADP: % [p, m, f] = traceFluxPath(model, sol.x, 'PFK', 'ATPS4rpp', 'traceMaterial', false) % % add model-specific cofactors to the exclusion list: % [p, m, f] = traceFluxPath(model, sol.x, 'PFK', 'CS', 'excludeMets', {'acetyl-CoA'}) @@ -67,12 +69,12 @@ % Notes % ----- % The algorithm follows metabolites in the forward direction only: it -% traces the metabolites that fromRxn PRODUCES and finds which consuming +% traces the metabolites that fromRxn produces and finds which consuming % reactions eventually reach toRxn. If fromRxn and toRxn are not connected -% in the forward flux direction (e.g. they are in parallel branches), an -% empty path is returned. A best-first (greedy) search ensures the -% highest-fraction path is found efficiently; a visited set prevents -% revisiting reactions. +% in the forward flux direction (for example they are in parallel branches), an +% empty path is returned. A best-first search, which expands the entry with +% the highest cumulative fraction first, finds the highest-fraction path; +% a path does not revisit a reaction. p = parseRAVENargs(varargin, {'cutoff',1e-8; 'maxHops',30; 'verbose',true; ... 'traceMaterial',true; 'carbonOnly',false; 'excludeMets',{}}); diff --git a/src/analysis/walkFluxes.m b/src/analysis/walkFluxes.m index 3ec9cc93..7e27ebe6 100644 --- a/src/analysis/walkFluxes.m +++ b/src/analysis/walkFluxes.m @@ -1,26 +1,30 @@ function walkFluxes(model, fluxes, startRxn, varargin) % walkFluxes Interactively navigate a flux distribution reaction by reaction. % -% Starting from a chosen reaction, displays all flux-carrying reactions +% Starting from a chosen reaction, displays the flux-carrying reactions % connected through shared metabolites, grouped by metabolite and labelled -% with each neighbour's role (produces / consumes). Select a neighbour by -% number to step to it; build a history and rewind with 'b'. +% with each neighbour's role (produces or consumes). Entering the number of +% a neighbour steps to it. The visited reactions are kept in a history, and +% 'b' steps back through it. % % Parameters % ---------- % model : struct -% RAVEN model structure. +% a model structure. % fluxes : double % flux vector (length = numel(model.rxns)). % startRxn : char or double -% starting reaction ID (string) or column index. +% starting reaction ID (string) or reaction index. % % Name-Value Arguments % -------------------- % cutoff : double -% minimum |flux| to display a reaction as a neighbour (default 1e-8). +% minimum net flux through a metabolite (|S_ij * v_j|) for the metabolite +% to be listed for the current reaction and for a reaction to be +% displayed as a neighbour (default 1e-8). % maxPerMet : double -% maximum neighbour reactions displayed per metabolite (default 8). +% maximum neighbour reactions displayed per metabolite, selected by +% decreasing absolute flux (default 8). % % Examples % -------- @@ -31,14 +35,12 @@ function walkFluxes(model, fluxes, startRxn, varargin) % Notes % ----- % Navigation commands: -% — step to that neighbour reaction -% b — go back to the previous reaction -% q — quit +% : step to that neighbour reaction +% b : go back to the previous reaction +% q : quit % -% This function is interactive and reads from the terminal at every step; -% it errors immediately under -batch, in deployed code, or otherwise without -% a real terminal, rather than blocking forever waiting for input that will -% never arrive. +% This function is interactive and reads from the terminal at every step. +% It raises an error under -batch and in deployed code. isBatch = false; try diff --git a/src/annotation/assignSBOterms.m b/src/annotation/assignSBOterms.m index d2a42190..ab071724 100644 --- a/src/annotation/assignSBOterms.m +++ b/src/annotation/assignSBOterms.m @@ -1,26 +1,26 @@ function model = assignSBOterms(model, varargin) % assignSBOterms Assign SBO terms to metabolites and reactions. % -% Assign SBO terms to metabolites and reactions following a generic rule -% set. The MATLAB counterpart of yeast-GEM's legacy addSBOterms; -% organism-agnostic, parameterised entirely by opts. +% Assigns SBO terms to metabolites and reactions following a generic rule +% set that opts parameterises. The function is the MATLAB counterpart of +% yeast-GEM's addSBOterms. % -% SBO is written via editMiriam(..., 'fill') so pre-existing SBO -% annotations are preserved. The terms are stored in model.metMiriams and +% SBO is written via editMiriam(..., 'fill'), which preserves pre-existing +% SBO annotations. The terms are stored in model.metMiriams and % model.rxnMiriams under the namespace 'sbo' (there is no separate SBO -% field); read them with extractMiriam(model.rxnMiriams, 'sbo'). +% field); they can be read with extractMiriam(model.rxnMiriams, 'sbo'). % exportModel writes them as the SBML sboTerm attribute. % % Parameters % ---------- % model : struct -% RAVEN model struct. +% a model structure. % % Name-Value Arguments % -------------------- % opts : struct -% Struct with any of the following fields. Missing fields take the -% defaults shown: +% structure with any of the following fields. Missing or empty fields +% take the defaults shown: % % - biomassMetNames : {'biomass','DNA','RNA','protein','carbohydrate', % 'lipid','cofactor','ion'} @@ -28,15 +28,19 @@ % - biomassRxnName : 'biomass pseudoreaction' % - ngamRxnName : 'non-growth associated maintenance reaction' % - pseudoreactionSubstrings : {'pseudoreaction','SLIME rxn'} -% - onlyLastReactionForPseudo : false. yeast-GEM bug-compat flag that -% replicates the legacy `for i=numel(...)` typo (pseudoreaction SBOs -% applied only to the last reaction). Off by default; turn ON for -% byte-equivalent yeast-GEM output. +% - onlyLastReactionForPseudo : false. If true, the biomass, NGAM and +% pseudoreaction terms are applied only to the last reaction of the +% model. This reproduces yeast-GEM's addSBOterms.m, which applies the +% pseudoreaction rule to the last reaction only, because of a typo in +% the loop header (for i=numel(...)). +% - transportRxnIdxs : indexes of the transport reactions (default: +% the reactions identified by getTransportRxns). % % Returns % ------- % model : struct -% Modified model. +% model structure with the SBO terms added to model.metMiriams and +% model.rxnMiriams. % % Examples % -------- @@ -47,22 +51,21 @@ % ----- % Metabolites: % -% SBO:0000649 (Biomass) when met.name is in opts.biomassMetNames, or -% ends with any of opts.biomassMetSuffixes. Otherwise SBO:0000247 -% (Simple chemical). +% SBO:0000649 (Biomass) when the metabolite name is in +% opts.biomassMetNames, or ends with any of opts.biomassMetSuffixes. +% Otherwise SBO:0000247 (Simple chemical). % % Reactions (default → override → pseudoreaction override): % % SBO:0000176 (Metabolic reaction) default. % Single-reactant reactions become: % SBO:0000627 (exchange) if the lone metabolite is extracellular -% (compartment 'e' or compartment name containing -% 'extracellular'), +% (compartment 'e' or compartment name 'extracellular'), % SBO:0000632 (sink) if coef < 0, % SBO:0000628 (demand) otherwise. -% Transport reactions (detected by opts.transportDetector or the -% default heuristic: same metName in ≥ 2 compartments in a single -% reaction) → SBO:0000655. +% Transport reactions (opts.transportRxnIdxs or, by default, the +% reactions identified by getTransportRxns: the same metabolite +% name more than once in a single reaction) → SBO:0000655. % Reactions whose name matches opts.biomassRxnName → SBO:0000629. % Reactions whose name matches opts.ngamRxnName → SBO:0000630. % Reactions whose name contains any of opts.pseudoreactionSubstrings diff --git a/src/annotation/editMiriam.m b/src/annotation/editMiriam.m index b287573e..66ea9a89 100755 --- a/src/annotation/editMiriam.m +++ b/src/annotation/editMiriam.m @@ -4,34 +4,32 @@ % Parameters % ---------- % model : struct -% model structure. +% a model structure. % type : char -% 'met', 'rxn', 'gene' or 'comp' dependent on which objects the -% annotations should be assigned to. +% 'met', 'rxn', 'gene' or 'comp', the type of object that the +% annotations are assigned to. % object : cell or logical or double or char % 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, +% elements as objects of that type in the model, a vector of indexes, % or 'all'. % miriamName : char % 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). +% 'bigg.metabolite'. A valid prefix from identifiers.org is expected +% (for example https://registry.identifiers.org/registry/bigg.metabolite). % miriams : char or cell -% string or cell array of strings with annotation identifiers, e.g. +% string or cell array of strings with annotation identifiers, for example % '12dgr161'. % keep : char % one of the following strings, specifying what should be done if an % object already has 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. +% - 'replace' : discard all existing annotations with the same +% miriamName; they are overwritten, even if the new annotation is an +% empty field. +% - 'fill' : add annotations only to those objects that have no +% annotation with that miriamName. Otherwise, the existing annotation +% is kept, even if it differs from the new annotation. % - 'add' : keep all existing annotations, and add any new % annotations, after removing duplicates. % - 'remove' : remove all annotations with the given miriamName from diff --git a/src/annotation/extractMiriam.m b/src/annotation/extractMiriam.m index cafab891..be509d11 100755 --- a/src/annotation/extractMiriam.m +++ b/src/annotation/extractMiriam.m @@ -1,32 +1,28 @@ function [miriams,extractedMiriamNames]=extractMiriam(modelMiriams,varargin) -% extractMiriam Unpack MIRIAM annotations into a human-readable table. +% extractMiriam Unpack MIRIAM annotations into a table. % -% Unpacks metMiriams, rxnMiriams, geneMiriams or compMiriams into a -% human-readable cell array, formatted as in Excel, with the columns split -% so each miriam name gets its own column. +% Unpacks metMiriams, rxnMiriams, geneMiriams or compMiriams into a cell +% array with one column per miriam name. % % Parameters % ---------- % modelMiriams : cell -% a miriam structure (e.g. model.metMiriams) for one or multiple -% metabolites. +% a miriam structure (for example model.metMiriams) for one or more +% metabolites, reactions, genes or compartments. % % Name-Value Arguments % -------------------- % miriamNames : cell or char -% cell array with miriam names to be extracted (default 'all', meaning -% that annotation for all miriam names found in modelMiriams will be -% extracted). +% cell array with miriam names to be extracted (default 'all', which +% extracts the annotation for all miriam names found in modelMiriams). % % Returns % ------- % miriams : cell -% 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 columns represents the number -% of unique miriam names per entity. +% a cell array with extracted miriams, with one row per entity and one +% column per extracted miriam name. If several ids are available for +% the same entity (metabolite, gene, reaction or compartment) and miriam +% name, they are concatenated into one cell, separated by '; '. % extractedMiriamNames : cell % cell array with extracted miriam names. % diff --git a/src/annotation/loadDeltaGCSV.m b/src/annotation/loadDeltaGCSV.m index af787ec5..fe488c07 100644 --- a/src/annotation/loadDeltaGCSV.m +++ b/src/annotation/loadDeltaGCSV.m @@ -2,29 +2,30 @@ % loadDeltaGCSV Load metDeltaG and rxnDeltaG from CSV files. % % Each CSV is a two-column table: identifier, deltaG. On load, rows whose -% identifier is not in the model are silently skipped, and every matched -% value is stored exactly as it appears in the CSV -- including yeast-GEM's -% own "no measurement" placeholder (10000000.0). Callers that need to treat -% a particular value as absent should filter it themselves after loading; -% this function does not interpret CSV values. Pass '' for either metCsv -% or rxnCsv to skip that side. +% identifier is not in the model are skipped without a message, and every +% matched value is stored as it appears in the CSV, including yeast-GEM's +% "no measurement" placeholder (10000000.0). The function does not +% interpret CSV values, so a value that is to be treated as absent has to +% be filtered after loading. An empty string ('') for metCsv or rxnCsv +% skips that side. % % Parameters % ---------- % model : struct -% RAVEN model struct. +% a model structure. % % Name-Value Arguments % -------------------- % metCsv : char -% Path to the metabolite deltaG CSV, or '' to skip. +% path to the metabolite deltaG CSV, or '' to skip (default ''). % rxnCsv : char -% Path to the reaction deltaG CSV, or '' to skip. +% path to the reaction deltaG CSV, or '' to skip (default ''). % % Returns % ------- % model : struct -% Updated model struct. +% model structure. The metDeltaG field is set only if metCsv is given and +% the rxnDeltaG field only if rxnCsv is given. % % Examples % -------- diff --git a/src/annotation/saveDeltaGCSV.m b/src/annotation/saveDeltaGCSV.m index b205d1fc..af2a6e6b 100644 --- a/src/annotation/saveDeltaGCSV.m +++ b/src/annotation/saveDeltaGCSV.m @@ -1,11 +1,11 @@ function saveDeltaGCSV(model, varargin) % saveDeltaGCSV Save metDeltaG and rxnDeltaG to CSV files. % -% Writes a two-column table (identifier, deltaG) per side, one row per -% entity, in model order. An entity with no value stored is written as -% NaN, unchanged from whatever the model field holds -- this function does -% not interpret or substitute values. Pass '' for either metCsv or rxnCsv -% to skip that side. +% Writes a two-column table (identifier, deltaG) for metabolites and one for +% reactions, one row per entity, in model order. Values are written as the +% model field holds them, so an entity with no value stored is written as +% NaN. A file is skipped when its path is '' or when the model lacks the +% corresponding field. % % Parameters % ---------- diff --git a/src/biomass/fitParameters.m b/src/biomass/fitParameters.m index 65670b3a..7965a91a 100755 --- a/src/biomass/fitParameters.m +++ b/src/biomass/fitParameters.m @@ -5,10 +5,11 @@ % between the fluxes the model predicts and the measured ones, using % fminsearch (Nelder-Mead). Each candidate parameter set is written into the % S matrix at the positions given by parameterPositions, and the model is -% solved once per data point. +% solved once per data point with the xRxns bounds fixed to the values in +% xValues. The fitted parameters are returned as absolute values. % -% Use this to *derive* a value from measurements; use setGAM to *apply* a -% known growth-associated maintenance value to a biomass pseudoreaction. +% The function derives a value from measurements. To apply a known +% growth-associated maintenance value to a biomass pseudoreaction, use setGAM. % % Parameters % ---------- @@ -32,30 +33,33 @@ % - 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) +% that position is set to the negative of the fitted value (to +% distinguish production from consumption) % % Name-Value Arguments % -------------------- % fitToRatio : logical -% 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 an impact (default true). +% true to fit the ratio of simulated to measured values, false to fit +% the absolute difference. The ratio limits the influence of large +% fluxes on the residual sum of squares (default true). % initialGuess : double % initial guess of the parameters (default ones). % plotFitting : logical -% true if the resulting fitting should be plotted (default false). +% true to plot the measured values and the fitted fluxes against +% xValues (default false). % % Returns % ------- % parameters : double -% fitted parameters in the same order as in parameterPositions. +% fitted parameters (absolute values) in the same order as in +% parameterPositions. % fitnessScore : double % the corresponding residual sum of squares. % exitFlag : double % exit status returned by fminsearch. % newModel : struct -% updated model structure with the fitted parameters. +% updated model structure with the fitted parameters. It is assigned +% only when plotFitting is true. % % Examples % -------- diff --git a/src/biomass/getBiomassFractions.m b/src/biomass/getBiomassFractions.m index 70ba89f1..6e8f2d5e 100644 --- a/src/biomass/getBiomassFractions.m +++ b/src/biomass/getBiomassFractions.m @@ -4,9 +4,16 @@ % Compute the mass fraction (g/gDW) per biomass component plus the total. % The MATLAB counterpart of yeast-GEM's legacy sumBioMass. % -% The biomassConfig struct describes the per-organism biomass layout — see -% Parameters below. Components whose pseudoreaction is missing from the -% model contribute 0. +% The biomassConfig struct describes the per-organism biomass layout (see +% Parameters). A component contributes 0 when its pseudoreaction is missing +% from the model or has no substrates. For a component whose pseudoreaction +% exists and has substrates, and whose mass_strategy is not 'grams', an error +% is raised when the molecular weight of a substrate is 0 (an empty +% metFormula field, or a formula that consists only of R), when its formula +% contains an element outside the built-in element table, or when +% mass_strategy is unknown. A component with an unknown mass_strategy whose +% pseudoreaction is missing or has no substrates contributes 0 without an +% error. % % Parameters % ---------- @@ -16,21 +23,22 @@ % Struct describing the biomass layout, with fields: % % - biomass_rxn : rxn id of the top-level biomass pseudoreaction. -% - proton_met : met id of cytosolic H+ (used only by -% rescalePseudoreaction; may be unused here). +% - proton_met : met id of cytosolic H+ (used by +% scaleBiomassPseudoreaction, not by getBiomassFractions). % - components : cell array of component structs, each with fields: % -% - name : component name (e.g. 'protein'). +% - name : component name (for example 'protein'). % - pseudoreaction_name : model.rxnNames entry to identify the % pseudoreaction. -% - mass_strategy : 'mw' | 'mw_minus_2h' | 'mw_minus_water' | -% 'grams' — see Notes below. +% - mass_strategy : 'mw', 'mw_minus_2h', 'mw_minus_water' or +% 'grams' (see Notes). % % Returns % ------- % fractions : struct -% Struct keyed by component name plus 'total': fractions.protein, -% fractions.RNA, ... etc. All values are in g/gDW. +% Struct with one field per component name and a field 'total' +% (for example fractions.protein and fractions.RNA). All values are in +% g/gDW. % % Examples % -------- @@ -41,11 +49,11 @@ % mass_strategy values: % % 'mw' MW from chemical formula -% 'mw_minus_2h' MW − 2.016 g/mol (two protons released per charged -% tRNA — protein-pseudoreaction substrates) -% 'mw_minus_water' MW − 18.015 g/mol (water released per -% polymerisation step — RNA / DNA) -% 'grams' stoichiometry already in g/gDW (lipid backbone) +% 'mw_minus_2h' MW - 2.016 g/mol (two protons released per charged +% tRNA; protein pseudoreaction substrates) +% 'mw_minus_water' MW - 18.015 g/mol (water released per +% polymerisation step; RNA and DNA) +% 'grams' stoichiometry is already in g/gDW (lipid backbone) fractions = struct(); total = 0; diff --git a/src/biomass/scaleBiomassFraction.m b/src/biomass/scaleBiomassFraction.m index 8881f07d..79a9e55a 100644 --- a/src/biomass/scaleBiomassFraction.m +++ b/src/biomass/scaleBiomassFraction.m @@ -11,9 +11,10 @@ % model : struct % RAVEN model struct. % biomassConfig : struct -% Struct (see getBiomassFractions). +% Biomass layout struct, as described in getBiomassFractions. % componentName : char -% Component to rescale. +% Name of the component to rescale. An error is raised if its current +% fraction is 0. % newValue : double % Target fraction in g/gDW. % @@ -21,9 +22,9 @@ % -------------------- % balanceOut : char % Second component name to adjust so the biomass total becomes -% targetTotal. It must be large enough to absorb the change: an error -% is raised if its fraction would become zero or negative, or if it is -% 0 to begin with. Empty / omit to skip balancing. +% targetTotal. An error is raised if its fraction would become zero or +% negative, or if it is 0 to begin with. No balancing is done when +% empty or omitted (default ''). % targetTotal : double % Biomass total in g/gDW that balanceOut brings the components to % (default 1). @@ -31,7 +32,7 @@ % Returns % ------- % model : struct -% Modified model. +% Model with the rescaled pseudoreactions. % % Examples % -------- diff --git a/src/biomass/scaleBiomassPseudoreaction.m b/src/biomass/scaleBiomassPseudoreaction.m index e50649f9..996bca00 100644 --- a/src/biomass/scaleBiomassPseudoreaction.m +++ b/src/biomass/scaleBiomassPseudoreaction.m @@ -6,10 +6,12 @@ % The MATLAB counterpart of yeast-GEM's legacy rescalePseudoReaction. % % "Substrate" means every metabolite in the pseudoreaction whose -% metabolite name does NOT match the component name (the component's -% product is left untouched). After rescaling, the coefficient of -% biomassConfig.proton_met is recomputed so the pseudoreaction's total -% ionic charge sums to zero. +% metabolite name differs from the component name; the coefficient of the +% component's product is unchanged. After rescaling, the coefficient of +% biomassConfig.proton_met is recomputed so that the total charge of the +% pseudoreaction is zero. An error is raised if the model has no +% metCharges field or if a metabolite other than proton_met in the +% pseudoreaction has an undefined (NaN) charge. % % Parameters % ---------- @@ -18,12 +20,11 @@ % biomassConfig : struct % Struct (see getBiomassFractions). % componentName : char -% Name of the component to rescale (must match -% biomassConfig.components{i}.name for some i, AND be the -% model.metNames of the produced metabolite in the matching -% pseudoreaction). +% Name of the component to rescale. It must match +% biomassConfig.components{i}.name for some i and the model.metNames +% entry of the produced metabolite in the matching pseudoreaction. % factor : double -% Multiplicative factor. +% Factor by which the substrate coefficients are multiplied. % % Returns % ------- diff --git a/src/biomass/setGAM.m b/src/biomass/setGAM.m index c0c492e0..0c99bc98 100644 --- a/src/biomass/setGAM.m +++ b/src/biomass/setGAM.m @@ -8,11 +8,11 @@ % % For every metabolite in the biomass pseudoreaction whose model.metNames % entry is in cofactorMetNames, the stoichiometric coefficient is set to -% ±value preserving the sign of the current coefficient. An error is raised +% value with the sign of the current coefficient. An error is raised % before the model is changed if ngamRxn is given and is not in the model, % and if ngamValue is given without ngamRxn (RAVEN:badInput). -% Yeast-GEM scales ATP, ADP, H2O, H+ and phosphate (with ATP and H2O on the -% substrate side, ADP / H+ / phosphate on the product side). +% For yeast-GEM, the cofactors are ATP, ADP, H2O, H+ and phosphate (ATP and +% H2O are substrates; ADP, H+ and phosphate are products). % % Parameters % ---------- @@ -23,7 +23,8 @@ % biomassRxn : char % Reaction id of the biomass pseudoreaction. % cofactorMetNames : cell -% Cell array of metabolite NAMES (not IDs) to rescale, e.g. +% Cell array of metabolite names (matched against model.metNames, not +% metabolite ids) to rescale, for example % {'ATP','ADP','H2O','H+','phosphate'}. % % Name-Value Arguments @@ -31,8 +32,8 @@ % ngamRxn : char % NGAM reaction id. Required when ngamValue is supplied. % ngamValue : double -% NGAM flux to fix. Sets the NGAM reaction's bounds to (ngamValue, -% ngamValue). +% NGAM flux to fix. Both bounds of the NGAM reaction are set to +% ngamValue. % % Returns % ------- @@ -45,8 +46,8 @@ % % See also % -------- -% fitParameters : estimates such a value from measured fluxes instead of -% applying a known one. The two are complementary - fit first, then set. +% fitParameters : derives such a value from measured fluxes; setGAM then +% applies it. if nargin < 4 error('setGAM:missingArgs', ... diff --git a/src/comparison/compareMultipleModels.m b/src/comparison/compareMultipleModels.m index 6407a403..147338c3 100755 --- a/src/comparison/compareMultipleModels.m +++ b/src/comparison/compareMultipleModels.m @@ -3,10 +3,10 @@ % % Compares two or more models on overlap of reactions, metabolites, genes, % EC-codes, metabolite names and reaction equations (with and without -% compartmentalization), and on high-dimensional comparisons in the -% reaction-space: subsystem utilization, structural similarity, an optional -% low-dimensional structural projection, and an optional functional -% (task-based) comparison. +% compartmentalisation), and on high-dimensional comparisons of the +% reaction content: subsystem coverage, structural similarity, a +% low-dimensional structural projection (skipped when neither tsne nor +% mdscale is available), and an optional functional (task-based) comparison. % % Parameters % ---------- @@ -16,18 +16,19 @@ % Name-Value Arguments % -------------------- % printResults : logical -% true if the results should be printed on the screen (default false). +% true to print the results to the command window (default false). % plotResults : logical -% true if the results should be plotted (default false). +% true to plot the results (default false). % groupVector : double or cell -% numeric vector or cell array for grouping similar models, i.e. by -% tissue (default all models ungrouped). +% numeric vector or cell array that assigns each model to a group, for +% example by tissue. The groups colour the points of the structural +% projection plot (default [], no grouping). % funcCompare : logical -% should a functional comparison be run (default false). +% true to run the functional comparison, which requires taskFile +% (default false). % taskFile : char -% 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). +% name of the task file for the functional comparison, in a format that +% parseTaskList reads. Required when funcCompare is true. % % Returns % ------- @@ -40,24 +41,28 @@ % row indicates which models are included in the comparison) and % nElements (vector with the number of elements for each comparison). % "equ" are the reaction equations after sorting and "uEqu" are the -% equations when not taking compartmentalization into account. These -% are the only fields of the seven that use EC-code, metabolite name or -% reaction equation to compare models that do not share an id -% convention; the rest compare by identifier only. +% equations without compartments. The fields rxns, mets and genes +% compare identifiers; eccodes, metNames, equ and uEqu compare EC +% codes, metabolite names and reaction equations, which allows +% overlap between models that use different identifiers. % - subsystems : substructure containing subsystem information, with -% fields matrix (matrix with comparison of number of rxns per -% subsystem) and ID (vector consisting of names of all subsystems) +% fields matrix (number of reactions per subsystem, subsystems in rows +% and models in columns) and ID (cell array with the names of all +% subsystems). Only the first subsystem of each reaction is counted. +% The field is absent when a model lacks the subSystems field. % - reactions : substructure containing reaction information, with -% fields matrix (binary matrix composed of reactions (rows) in each -% model (column), used as the input for the model comparisons) and IDs +% fields matrix (binary matrix with reactions in rows and models in +% columns, used as the input for the model comparisons) and IDs % (list of the reactions contained in the reaction matrix) % - 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 +% based on (1 - Hamming distance) between models +% - structCompMap : matrix with the 3D tSNE (or MDS) mapping of model +% structures based on Hamming distances. It is empty when neither +% tsne nor mdscale is available. % - funcComp : substructure containing function comparison results, with -% fields matrix (matrix with PASS / FAIL (1 / 0) values for each task) -% and tasks (vector containing names of all tasks) +% fields matrix (1 for a passed task and 0 for a failed task, tasks in +% rows and models in columns) and tasks (the descriptions of all +% tasks). It is present only when funcCompare is true. % % Examples % -------- @@ -71,9 +76,8 @@ % % See also % -------- -% diffModels : takes exactly two models and reports the differing *values* -% (stoichiometry, bounds, grRules), where this reports overlap counts, -% similarity and clustering. +% diffModels : reports the differing values (stoichiometry, bounds, grRules) +% between two models. %% Set up input defaults p=parseRAVENargs(varargin, {'printResults',false; 'plotResults',false; 'groupVector',[]; 'funcCompare',false; 'taskFile',[]}); @@ -429,10 +433,11 @@ function printList(models,toCheck,nElements) % % clust_dist Distance metric to be used for clustering, ignored if % clust_dim is "none". Options are the same as those for -% distance in, e.g., PDIST ("euclidean", "hamming", etc.). +% distance in pdist (for example "euclidean", "hamming" and +% other metrics). % (DEFAULT = "euclidean") % -% col_map Colormap, provided as string (e.g., "parula", "hot", "etc.") +% col_map Colormap, provided as string (for example "parula" or "hot") % or an Nx3 RGB matrix of N colors. % (DEFAULT = "hot") % diff --git a/src/comparison/diffModels.m b/src/comparison/diffModels.m index 00aed406..1b1f91e0 100644 --- a/src/comparison/diffModels.m +++ b/src/comparison/diffModels.m @@ -1,20 +1,17 @@ function report = diffModels(modelA, modelB, varargin) % diffModels Report the semantic differences between two models. % -% Compares two models entry by entry, keyed by identifier, and returns a report listing -% every difference found. Reactions, metabolites and genes are matched by -% id; for the ids present in both models the reaction stoichiometry, bounds, -% objective coefficient, grRule, EC codes, and the metabolite formula, -% charge and compartment are compared. This is the structured -% added/removed/changed diff that compareMultipleModels (which reports -% overlap counts, similarity and clustering across N models) does not -% provide. +% Compares two models entry by entry, keyed by identifier, and returns a +% report listing every difference found. Reactions, metabolites and genes +% are matched by id and reported when present in only one model. For the +% ids present in both models, the reaction stoichiometry, bounds, +% objective coefficient, grRule and EC codes, and the metabolite formula, +% charge and compartment are compared. % -% grRules are compared for logical equality rather than as strings: each -% rule is expanded to disjunctive normal form and the genes within each -% isozyme, and the isozymes themselves, are sorted before comparison, so -% "a and b" equals "b and a" and "(a or b)" equals "(b or a)". This is -% stronger than a case/whitespace string match. +% grRules are compared by logical content: each rule is expanded to +% disjunctive normal form, and the genes within each isozyme and the +% isozymes themselves are sorted before comparison, so "a and b" equals +% "b and a" and "(a or b)" equals "(b or a)". % % Parameters % ---------- @@ -29,10 +26,11 @@ % absolute tolerance for stoichiometric coefficient differences % (default 1e-9). % maxPerCategory : double -% the maximum number of differences reported per category before the -% rest are truncated with a single summary line (default 50). +% maximum number of entries in report.differences per category. Further +% differences of that category are replaced by a single summary line +% (default 50). % printResults : logical -% print the report to the command window (default false). +% true to print the report to the command window (default false). % % Returns % ------- @@ -41,19 +39,18 @@ % % - equal : true if no differences were found. % - differences : cell array of human-readable difference strings, each -% naming the category and the entity affected. -% - rxnsOnlyInA / rxnsOnlyInB : reaction ids present in only one model. -% - metsOnlyInA / metsOnlyInB : metabolite ids present in only one model. -% - genesOnlyInA / genesOnlyInB : gene ids present in only one model. -% -% Usage: report = diffModels(modelA, modelB, ...) +% naming the entity affected. +% - rxnsOnlyInA and rxnsOnlyInB : reaction ids present in only one +% model. +% - metsOnlyInA and metsOnlyInB : metabolite ids present in only one +% model. +% - genesOnlyInA and genesOnlyInB : gene ids present in only one model. +% Both are empty when either model lacks the genes field. % % See also % -------- -% compareMultipleModels : N models, set membership across seven identity -% notions (ids, EC codes, metabolite names, equations), similarity -% matrix, clustering and an optional task-based functional comparison -- -% no values. +% compareMultipleModels : overlap counts, similarity and clustering across +% two or more models. p = parseRAVENargs(varargin, {'stoichTol', 1e-9; 'maxPerCategory', 50; ... 'printResults', false}); diff --git a/src/conditions/applyCondition.m b/src/conditions/applyCondition.m index 02ad2456..0b8ae844 100644 --- a/src/conditions/applyCondition.m +++ b/src/conditions/applyCondition.m @@ -1,28 +1,39 @@ function model = applyCondition(model, condition) % applyCondition Apply a deterministic condition to a model. % -% Apply a deterministic "condition" to a model: a prelude that resets -% exchange bounds, optional metabolite removals + automatic charge -% rebalancing of a pseudoreaction, optional biomass-stoichiometry delta, -% and a per-reaction bounds diff. The schema is intentionally narrow so a -% condition can be reviewed as data. +% The steps of a condition are applied in this order: a prelude that resets +% exchange bounds, metabolite removals from a pseudoreaction with automatic +% charge rebalancing, a change of biomass stoichiometry, and per-reaction +% bound changes. A final check compares the number of uptake bounds with an +% expected count. The schema covers only these steps, so a condition can be +% reviewed as data. % -% The same schema works for any GEM that keeps its condition presets as -% data rather than as code. Project-specific extensions (e.g. yeast-GEM's amino_acid_ratio step that -% rewrites a protein pseudoreaction's stoichiometry from a side-car TSV) -% are handled by the caller before / after this function — kept -% upstream-narrow on purpose. +% The schema applies to any GEM whose condition presets are kept as data. +% Project-specific extensions, for example yeast-GEM's amino_acid_ratio +% step that rewrites the stoichiometry of a protein pseudoreaction from a +% separate TSV file, are applied by the caller before or after this +% function. % % Parameters % ---------- % model : struct % RAVEN model struct. % condition : char or struct -% Either a path to a YAML condition file or a struct already produced -% by parseYAML. The expected schema (all keys optional): +% Path to a YAML condition file, or a struct as produced by parseYAML. +% The schema is as follows (all keys optional). reset_exchanges is +% passed as the reaction type to getExchangeRxns; the lower bound of +% the matching reactions is set to 0 and the upper bound to 1000. +% charge_balance_met receives the coefficient that makes the charge of +% rxn_id zero, which requires the metCharges field; a participant of +% rxn_id other than charge_balance_met with a NaN charge raises +% applyCondition:unknownCharge. add entries are +% added to the existing coefficients. A bounds entry whose rxn is not +% in the model is skipped with a warning. expected_uptake_count is +% compared with the number of bounds entries with lb of -1000, and a +% warning is issued when they differ. % % prelude: -% reset_exchanges: out % truthy -> reset all +% reset_exchanges: out % % cofactor_pseudoreaction: % rxn_id: r_4598 @@ -47,7 +58,7 @@ % Returns % ------- % model : struct -% Modified model. +% Model with the condition applied. % % Examples % -------- diff --git a/src/conversion/addIdentifierPrefix.m b/src/conversion/addIdentifierPrefix.m index cf6b205f..8267d2e2 100644 --- a/src/conversion/addIdentifierPrefix.m +++ b/src/conversion/addIdentifierPrefix.m @@ -1,13 +1,13 @@ function [model, hasChanged]=addIdentifierPrefix(model,varargin) % addIdentifierPrefix Add identifier prefixes required by SBML. % -% 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. +% If any reaction, metabolite, compartment, gene or model identifier does +% not start with a letter or _, which conflicts with SBML specifications, +% a prefix is added to all identifiers in the respective model field. % The prefixes are: % % "R_" for model.rxns, -% "M_" for model.mets, +% "M_" for model.mets and model.id, % "C_" for model.comps; % "G_" for model.genes (and also represented in model.grRules) % @@ -19,16 +19,17 @@ % Name-Value Arguments % -------------------- % fields : cell -% cell array with model field names that should be checked if prefixes -% should be added, possible values: 'rxns', 'mets', 'comps', 'genes', -% 'id' (default all listed model fields will be checked). +% cell array with the names of the model fields to check for the need +% of a prefix, possible values: 'rxns', 'mets', 'comps', 'genes', 'id' +% (default all of these fields). % % Returns % ------- % model : struct % modified model. % hasChanged : cell -% cell array with fields and prefixes that are added. +% cell array of char with one entry per field that received a prefix, +% for example 'model.rxns (R_ prefix)'. % % Examples % -------- diff --git a/src/conversion/ravenCobraWrapper.m b/src/conversion/ravenCobraWrapper.m index f82048df..1fba8ee9 100755 --- a/src/conversion/ravenCobraWrapper.m +++ b/src/conversion/ravenCobraWrapper.m @@ -1,19 +1,21 @@ function newModel=ravenCobraWrapper(model) % ravenCobraWrapper Convert between RAVEN and COBRA structures. % -% Recognises a COBRA structure by checking for the field 'rules', found -% only in a COBRA Toolbox structure. If the COBRA model also has a grRules -% field, that is used instead of parsing rules. +% A structure with the field 'rules' is treated as a COBRA Toolbox +% structure and converted to RAVEN; a structure without it is treated as a +% RAVEN structure and converted to COBRA. If a COBRA structure also has a +% grRules field, that field is used and rules is not parsed. % % Parameters % ---------- % model : struct -% a RAVEN/COBRA-compatible model structure. +% a RAVEN or COBRA model structure. % % Returns % ------- % newModel : struct -% a COBRA/RAVEN-compatible model structure. +% the model structure in the other format: COBRA for a RAVEN input and +% RAVEN for a COBRA input. % % Examples % -------- @@ -24,17 +26,18 @@ % During the RAVEN -> COBRA -> RAVEN conversion cycle the following fields % are lost: annotation, compOutside, compMiriams, rxnComps, geneComps, % unconstrained. Boundary metabolites are lost, because the 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 is -% reconstructed based on lower bound reaction values. +% structure has no boundary metabolites, and are removed using +% simplifyModel before the RAVEN -> COBRA conversion. The field 'rev' is +% also partially lost; during the COBRA -> RAVEN conversion it is +% reconstructed from the lower bounds (a reaction is reversible if its +% lower bound is below zero). % % During the COBRA -> RAVEN -> COBRA conversion cycle the following fields % are lost: geneEntrezID, modelVersion, proteins. % % The information about mandatory RAVEN fields was taken from the % checkModelStruct function, whereas the corresponding information about -% COBRA fields was fetched from the verifyModel function. +% COBRA fields was taken from the verifyModel function. if isfield(model,'rules') isRaven=false; diff --git a/src/conversion/removeIdentifierPrefix.m b/src/conversion/removeIdentifierPrefix.m index 72b951a2..f7905939 100644 --- a/src/conversion/removeIdentifierPrefix.m +++ b/src/conversion/removeIdentifierPrefix.m @@ -3,15 +3,15 @@ % % Removes identifier prefixes: % -% "R_" for model.rxns, model.rxnNames and model.id, -% "M_" for model.mets and model.metNames, +% "R_" for model.rxns and model.rxnNames, +% "M_" for model.mets, model.metNames and model.id, % "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 have 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. +% field have the prefix. The prefixes are required when one or more +% identifiers do not start with a letter or _, which conflicts with SBML +% specifications. % % Parameters % ---------- @@ -21,20 +21,20 @@ % Name-Value Arguments % -------------------- % fields : cell -% cell array with model field names from which the identifiers should -% be removed, possible values: 'rxns', 'mets', 'comps', 'genes', -% 'metNames', 'rxnNames', 'id' (default all listed model fields will -% be checked). +% cell array with the names of the model fields from which the prefix +% is removed, possible values: 'rxns', 'mets', 'comps', 'genes', +% 'metNames', 'rxnNames', 'id' (default all of these fields). % forceRemove : logical -% if prefixes should be removed even if not all entries in a model -% field have the prefix (default false). +% true to remove the prefix from the entries that have it when not all +% entries in a model field have the prefix (default false). % % Returns % ------- % model : struct % modified model. % hasChanged : cell -% cell array with fields and prefixes that are removed. +% cell array of char with one entry per field from which a prefix is +% removed, for example 'model.rxns (R_ prefix)'. % % Examples % -------- diff --git a/src/conversion/standardizeModelFieldOrder.m b/src/conversion/standardizeModelFieldOrder.m index acc29029..38134d26 100755 --- a/src/conversion/standardizeModelFieldOrder.m +++ b/src/conversion/standardizeModelFieldOrder.m @@ -1,12 +1,15 @@ function orderedModel=standardizeModelFieldOrder(model) % standardizeModelFieldOrder Order RAVEN model structure fields. % -% Orders fields of a RAVEN model structure as specified at +% Orders the fields of a RAVEN or COBRA model structure. The RAVEN order is +% the one listed in orderRavenFields.csv, described at % https://raven-docs.readthedocs.io/en/latest/guide/model-structure.html +% A structure with the field 'rules' is ordered as a COBRA structure, using +% COBRA_structure_fields.csv. Fields that are not listed in the file are +% placed last, in alphabetical order. % -% The model fields themselves are not changed, only the order is modified. -% For changing model fields between RAVEN and COBRA format, use -% ravenCobraWrapper(). +% The content of the fields is unchanged. To convert model fields between +% RAVEN and COBRA format, use ravenCobraWrapper(). % % Parameters % ---------- diff --git a/src/curation/curateModelFromTables.m b/src/curation/curateModelFromTables.m index 8ef9aba9..62469ff5 100644 --- a/src/curation/curateModelFromTables.m +++ b/src/curation/curateModelFromTables.m @@ -1,17 +1,16 @@ function newModel=curateModelFromTables(model,metsInfo,varargin) % curateModelFromTables Curate or add mets, rxns and genes from tables. % -% Curate existing and/or add new metabolites, reactions and genes from +% Curates existing metabolites, reactions and genes and adds new ones from % tabular data files. % -% If the *.tsv files contain metabolites, reactions and/or genes that are -% already present in the model, then information in the model will be -% overwritten. Note that this includes empty annotations in the *.tsv -% files, unless 'overwriteWithEmpty' is false! Metabolites are matched by -% metaboliteName[comp]; reactions by the stoichiometry of its reactants and -% products; genes by their gene name. -% This function can therefore be used to add new entities in the model, or -% curate those already existing in the model. +% If the *.tsv files contain metabolites, reactions or genes that are +% already present in the model, the information in the model is +% overwritten. This includes empty annotations in the *.tsv files, unless +% 'overwriteWithEmpty' is false. Metabolites are matched by +% metaboliteName[comp]; reactions by the stoichiometry of their reactants +% and products; genes by their gene name. Entities that are not present in +% the model are added. % % Columns are identified by their header (case-insensitive, and spaces around % a header are ignored, also inside its quotes), so their order @@ -49,27 +48,30 @@ % Path to a *.tsv file with reaction information, or 'none'. Columns: % rxnIdx (or index), rxnNames (both required), grRules, lb, ub, rev, % subSystems, eccodes, rxnNotes, rxnReferences, rxnConfidenceScores, -% and MIRIAM. Each rxnIdx may be used by one row only (the rxnsCoeffs -% file has one row per metabolite of the reaction and repeats it). +% and MIRIAM. An index appears in at most one row of this table, +% otherwise RAVEN:badInput is raised (the rxnsCoeffs file has one row per +% metabolite of the reaction and repeats it). The two reaction tables +% are matched on index and name, and reactions or indices that appear +% in only one of them raise RAVEN:badInput. % metPrefix : char -% Prefix used to mint fresh metabolite ids (e.g. 's_' for yeast-GEM, -% 'M_' for the BiGG default) (default 'M_'). +% Prefix used to create new metabolite ids (for example 's_' for +% yeast-GEM, 'M_' for the BiGG default) (default 'M_'). % rxnPrefix : char -% Prefix used to mint fresh reaction ids (default 'R_'). +% Prefix used to create new reaction ids (default 'R_'). % overwriteWithEmpty : logical % if true, an empty cell in a row of an existing metabolite, gene or % reaction empties the corresponding field of the model. If false, an % empty cell leaves the existing value unchanged and only the cells with a % value are written (default true; [] also means the default). Must be a -% scalar logical or 0/1. A cell with only blanks counts as empty in both +% scalar logical, 0 or 1. A cell with only blanks counts as empty in both % modes. Empty grRules cells never overwrite. An empty or NaN lb, ub or % rev cell always keeps the existing value. For the charge and the % confidence score, an empty or NaN cell is treated alike: when % overwriteWithEmpty is true and at least one other row of the column has % a value, it becomes 0; a column in which no row has a value is not % written, and the existing values stay. The same holds for a MIRIAM -% column: a column in which no row has a value does not clear the -% annotations of existing entities. +% column: a column in which no row of an existing entity has a value +% does not clear the annotations. % % Returns % ------- @@ -99,11 +101,12 @@ % given; for new reactions the reversibility is derived from lb and ub. % % Gene rules: a grRules cell must be a well-formed gene rule (genes joined by -% and/or in any case, or by &, &&, | and ||, with balanced parentheses); a -% rule with an operator that lacks an operand, empty parentheses or two genes -% without an operator between them raises RAVEN:badInput before the model is -% changed. A valid rule is stored in RAVEN's standard format. Whether the -% genes exist is checked when the rule is applied. +% the words and or or in any case, or by &, &&, | or ||, with balanced +% parentheses); a rule with an operator that lacks an operand, empty +% parentheses or two genes without an operator between them raises +% RAVEN:badInput before the model is changed. A valid rule is stored in +% RAVEN's standard format. Whether the genes exist is checked when the rule +% is applied. % % Genes: a gene id that the genesInfo table lists more than once raises % RAVEN:badInput, whether the model has the gene or not. @@ -117,9 +120,9 @@ % rxnIdx and a coefficient that is a finite number other than 0. A row of % the rxnsInfo table without any value is ignored; a row with a value needs % a rxnIdx. A rxnIdx is a whole number of at least 1; the indices (and -% names) of the two reaction tables must match exactly, compared by their -% numeric value (1, 1.0 and 1e0 are the same index). Otherwise RAVEN:badInput -% is raised. +% names) of the two reaction tables must match, with indices compared by +% their numeric value (1, 1.0 and 1e0 are the same index). Otherwise +% RAVEN:badInput is raised. p=parseRAVENargs(varargin, {'genesInfo','none'; 'rxnsCoeffs','none'; 'rxnsInfo','none'; 'metPrefix',[]; 'rxnPrefix',[]; 'overwriteWithEmpty',true}); overwriteWithEmpty=p.overwriteWithEmpty; diff --git a/src/curation/downloadGenomeData.m b/src/curation/downloadGenomeData.m index 72877d1b..6f54ae09 100644 --- a/src/curation/downloadGenomeData.m +++ b/src/curation/downloadGenomeData.m @@ -1,16 +1,17 @@ function [gffFile, faaFile] = downloadGenomeData(accession, varargin) % downloadGenomeData Download genome annotation files from NCBI. % -% Retrieves the GFF3 annotation and protein FASTA (.faa) files for a given -% NCBI genome assembly accession using the NCBI Datasets v2 API, which -% returns both files in a single archive. The files are saved locally and -% can be used directly by getGeneData to build a gene-mapping table. +% Downloads the GFF3 annotation and protein FASTA (.faa) files for an NCBI +% genome assembly accession using the NCBI Datasets v2 API, which returns +% both files in a single archive. The files are saved as +% _genomic.gff and _protein.faa in outputDir. They +% are input files for getGeneData. % % Parameters % ---------- % accession : char -% NCBI genome assembly accession, e.g. 'GCF_000002595.2'. -% Both RefSeq (GCF_) and GenBank (GCA_) prefixes are accepted. +% NCBI genome assembly accession, for example 'GCF_000002595.2'. The +% prefix is 'GCF_' (RefSeq) or 'GCA_' (GenBank). % % Name-Value Arguments % -------------------- @@ -40,8 +41,10 @@ % % Notes % ----- -% Requires an active internet connection. Files already present in -% outputDir are not re-fetched; delete them manually to force a refresh. +% An internet connection is required. When both files are already present +% in outputDir, no download takes place; deleting them forces a new +% download. An error is raised when NCBI Datasets does not return both a +% GFF3 file and a protein FASTA file for the accession. if nargin < 1 || isempty(accession) error('downloadGenomeData:missingInput', ... diff --git a/src/curation/getGeneData.m b/src/curation/getGeneData.m index 3f852c7c..497c3c88 100644 --- a/src/curation/getGeneData.m +++ b/src/curation/getGeneData.m @@ -1,39 +1,46 @@ function geneTable = getGeneData(accession, varargin) % getGeneData Build a gene-mapping table from NCBI genome annotation files. % -% Parses the GFF3 annotation and protein FASTA (.faa) files for a given -% NCBI genome assembly and produces a table mapping locus tags to gene -% symbols, protein IDs, and other identifiers. The resulting table can be -% passed directly to renameModelGenes to update gene identifiers in a -% RAVEN model. If no local files are provided, downloadGenomeData is -% called automatically to fetch them. +% Parses the GFF3 annotation file of an NCBI genome assembly and produces +% a table mapping locus tags to gene symbols, protein IDs and other +% identifiers. The table can be passed to renameModelGenes to change gene +% identifiers in a RAVEN model. If the input is an assembly accession, +% downloadGenomeData downloads the GFF3 and protein FASTA (.faa) files to +% downloadDir, unless both are already present there. % % Parameters % ---------- % accession : char -% NCBI genome assembly accession, e.g. 'GCF_000002595.2', or a path to a -% local GFF3 annotation file. +% NCBI genome assembly accession, for example 'GCF_000002595.2', or the +% path to a local GFF3 annotation file. An error is raised if the +% input is neither an existing file nor an accession of the form +% 'GCF_' or 'GCA_' followed by digits and an optional version. % % Name-Value Arguments % -------------------- % outputFile : char -% Path to save the resulting table as a tab-delimited .tsv file. If -% omitted or empty, no file is written and the table is only returned. +% Path of the tab-delimited .tsv file to which the table is written. +% No file is written if omitted or empty (default ''). % downloadDir : char -% Directory where genome files are downloaded if not already present -% (default: current working directory). +% Directory where genome files are downloaded if not already present. +% Only used when the input is an accession (default: current working +% directory). % % Returns % ------- % geneTable : table -% MATLAB table with one row per gene containing: -% locus_tag — stable locus identifier (e.g. 'Cre01.g000001') -% old_locus_tag — previous locus identifier when available -% GeneID — NCBI Gene ID (e.g. '5723799') -% gene_name — common gene symbol when available (e.g. 'rbcL') -% GenBank_protein — protein accession (e.g. 'XP_001698190.2'), matching -% the protein FASTA headers -% UniProt — UniProt accession from Dbxref when available +% MATLAB table with one row per distinct combination of gene and +% protein accession (a CDS feature with a protein accession, repeated +% CDS rows are merged), with the columns below. A column entry is empty +% when the annotation lacks the value. +% +% - locus_tag : locus identifier (for example 'Cre01.g000001') +% - old_locus_tag : earlier locus identifier +% - GeneID : NCBI Gene ID (for example '5723799') +% - gene_name : gene symbol (for example 'rbcL') +% - GenBank_protein : protein accession (for example 'XP_001698190.2'), +% as in the protein FASTA headers +% - UniProt : UniProt accession from the Dbxref attribute of the gene % % Examples % -------- @@ -49,8 +56,9 @@ % Notes % ----- % When outputFile is provided the table is written as UTF-8 encoded -% tab-delimited text with a header row, compatible with readtable and -% renameModelGenes. Rows without a locus_tag are silently discarded. +% tab-delimited text with a header row, which readtable and +% renameModelGenes can read. A CDS whose gene has no locus_tag, or whose +% gene feature is missing, gives a row with an empty locus_tag. if nargin < 1 || isempty(accession) error('getGeneData:missingInput', ... diff --git a/src/curation/processProteinFastaFile.m b/src/curation/processProteinFastaFile.m index eeebf5b4..a5518bfe 100644 --- a/src/curation/processProteinFastaFile.m +++ b/src/curation/processProteinFastaFile.m @@ -1,11 +1,13 @@ function processedFaaFile = processProteinFastaFile(faaFile, geneTable, headerCol, varargin) % processProteinFastaFile Rename protein FASTA headers using a gene mapping table. % -% Reads a protein FASTA file (as downloaded by downloadGenomeData) and -% replaces each sequence header with the value from the specified geneTable -% column, matched via the GenBank_protein accession present in the original -% FASTA header. Sequences whose accession is not found in geneTable are -% kept with their original header unchanged. +% Reads a protein FASTA file (such as one downloaded by downloadGenomeData) +% and replaces each sequence header with the value from the specified +% geneTable column. A sequence is matched to a row through the +% GenBank_protein accession, which is the first token of the original +% FASTA header. Sequences whose accession is not found in geneTable keep +% their original header. The numbers of renamed and kept sequences are +% printed. % % Parameters % ---------- @@ -13,18 +15,19 @@ % Path to the protein FASTA file (.faa) to process. % geneTable : char | table % Either a path to a tab-delimited .tsv file produced by getGeneData, -% or a MATLAB table variable. Must contain at least the columns +% or a MATLAB table variable. It must contain the columns % 'GenBank_protein' and the column named by headerCol. % headerCol : char % Name of the geneTable column whose values will replace each FASTA -% header (e.g. 'locus_tag', 'gene_name', 'GenBank_protein'). +% header (for example 'locus_tag', 'gene_name', 'GenBank_protein'). % % Name-Value Arguments % -------------------- % outputDir : char -% Directory where the processed FASTA file is saved. The output file -% name is the original base name with '_processed' appended before the -% extension (default: current working directory). +% Directory where the processed FASTA file is saved. It is created if +% missing. The output file name is the original base name with +% '_processed' appended before the extension (default: current working +% directory). % % Returns % ------- @@ -46,10 +49,11 @@ % % Notes % ----- -% GenBank_protein must contain accessions matching the first token of each -% FASTA header (after '>'). For prokaryotes this is the protein_id -% (e.g. WP_012345678.1); for eukaryotes it is the GenBank accession stored -% in the GFF3 annotation by getGeneData. +% GenBank_protein must contain accessions equal to the first +% whitespace-delimited token of each FASTA header (after '>'), for example +% WP_012345678.1. getGeneData takes the accession from the protein_id +% attribute of the CDS features of the GFF3 annotation, or from a GenBank +% entry of the Dbxref attribute when protein_id is empty. if nargin < 1 || isempty(faaFile) error('processProteinFastaFile:missingInput', ... diff --git a/src/curation/renameModelGenes.m b/src/curation/renameModelGenes.m index 6a7c8660..9dc2a32f 100644 --- a/src/curation/renameModelGenes.m +++ b/src/curation/renameModelGenes.m @@ -1,34 +1,35 @@ function model = renameModelGenes(model, geneTable, fromCol, toCol) % renameModelGenes Replace gene identifiers in a RAVEN model. % -% Updates model.genes and model.grRules by substituting the identifiers -% currently used in the model (fromCol) with new identifiers (toCol) from -% a mapping table produced by getGeneData or supplied manually. After -% renaming, model.rxnGeneMat is rebuilt automatically. +% Replaces the identifiers in model.genes and model.grRules that are listed +% in column fromCol of a mapping table with the identifiers in column +% toCol. The table is produced by getGeneData or supplied manually. After +% renaming, model.rxnGeneMat is rebuilt. % % Parameters % ---------- % model : struct -% RAVEN model struct. Must contain model.genes and model.grRules; -% model.rxnGeneMat is rebuilt automatically. +% RAVEN model struct. It must contain model.genes and model.grRules. % geneTable : table | char -% Gene-mapping table. Can be supplied as: -% (a) A MATLAB table variable already loaded in the workspace, or -% (b) A path to a tab-delimited .tsv file — loaded automatically. +% Gene-mapping table, either +% (a) a MATLAB table variable, or +% (b) the path to a tab-delimited .tsv file, which is read with +% readtable. % fromCol : char -% Column in geneTable whose values match the identifiers currently in -% model.genes (e.g. 'locus_tag'). +% Name of the column in geneTable whose values match the identifiers +% in model.genes (for example 'locus_tag'). % toCol : char -% Column in geneTable whose values will replace the current -% identifiers (e.g. 'gene_name'). +% Name of the column in geneTable with the new identifiers (for +% example 'gene_name'). % % Returns % ------- % model : struct -% Updated model struct with: -% model.genes — renamed gene list. -% model.grRules — gene-reaction rules using new identifiers. -% model.rxnGeneMat — rebuilt sparse matrix matching the new gene list. +% Model struct with these fields changed: +% +% - model.genes : gene list with the new identifiers. +% - model.grRules : gene-reaction rules with the new identifiers. +% - model.rxnGeneMat : sparse matrix rebuilt for the new gene list. % % Examples % -------- @@ -42,11 +43,17 @@ % Notes % ----- % * Genes with no entry in fromCol, or whose toCol value is empty, are left -% unchanged; a warning lists them for investigation. -% * Word-boundary matching prevents partial substitution (e.g. 'gene1' -% is not replaced inside 'gene10'). -% * grRules are standardized via standardizeGrRules before and after -% renaming to ensure consistent formatting. +% unchanged, and a warning lists them. +% * If a fromCol value occurs in several rows, the first row with a +% non-empty toCol value is used. Values are trimmed of surrounding +% whitespace. +% * An identifier is replaced only where it is delimited by whitespace, +% parentheses or the start or end of the rule, so 'gene1' is not +% replaced inside 'gene10'. +% * Unnecessary outer parentheses are removed from the grRules and the +% grRules are standardised with standardizeGrRules before and after +% renaming. A warning is issued when standardizeGrRules reports rules +% with potential issues. if nargin < 1 || isempty(model) error('renameModelGenes:missingInput', ... diff --git a/src/deprecated/canConsume.m b/src/deprecated/canConsume.m index 4ceb625c..e478f2b0 100644 --- a/src/deprecated/canConsume.m +++ b/src/deprecated/canConsume.m @@ -4,7 +4,7 @@ % Deprecated wrapper kept so existing scripts keep working; it will be % removed in the next major release. % -% See Also +% See also % -------- % canExchange diff --git a/src/deprecated/canProduce.m b/src/deprecated/canProduce.m index f3df9ef7..e87c469a 100644 --- a/src/deprecated/canProduce.m +++ b/src/deprecated/canProduce.m @@ -4,7 +4,7 @@ % Deprecated wrapper kept so existing scripts keep working; it will be % removed in the next major release. % -% See Also +% See also % -------- % canExchange diff --git a/src/deprecated/consumeSomething.m b/src/deprecated/consumeSomething.m index 0b468286..71f5736a 100644 --- a/src/deprecated/consumeSomething.m +++ b/src/deprecated/consumeSomething.m @@ -4,16 +4,14 @@ % Deprecated wrapper kept so existing scripts keep working; it will be % removed in the next major release. % -% Its positional argument order predates findLeakMetabolite and is -% preserved here: +% The positional argument order is: % % consumeSomething(model, ignoreMets, isNames, minNrFluxes, params, ignoreIntBounds) % -% findLeakMetabolite inserts allowExcretion (a produce-only option) in -% position 4, so the arguments are translated rather than forwarded -% verbatim. +% findLeakMetabolite takes allowExcretion (a produce-only option) in +% position 4, so the arguments are translated before they are passed on. % -% See Also +% See also % -------- % findLeakMetabolite diff --git a/src/deprecated/makeSomething.m b/src/deprecated/makeSomething.m index b786755e..20d65b8a 100644 --- a/src/deprecated/makeSomething.m +++ b/src/deprecated/makeSomething.m @@ -5,7 +5,7 @@ % removed in the next major release. Its argument order already matches % findLeakMetabolite's, so the arguments are forwarded as they are. % -% See Also +% See also % -------- % findLeakMetabolite diff --git a/src/gapfilling/canExchange.m b/src/gapfilling/canExchange.m index 6dbb0687..8654413a 100644 --- a/src/gapfilling/canExchange.m +++ b/src/gapfilling/canExchange.m @@ -2,12 +2,14 @@ % canExchange Check which metabolites a model can produce or consume. % % Adds an exchange reaction for each of the specified metabolites and -% checks which of them can carry a flux. This is the unified replacement -% for canProduce ('produce') and canConsume ('consume'). +% checks which of them can carry an absolute flux above 1e-5. The direction +% 'produce' corresponds to the deprecated function canProduce and 'consume' +% to canConsume. % -% This is a less advanced but faster version of checkProduction, which -% additionally reports which metabolites must be connected in order to make -% the remaining ones producible. +% canExchange only tests whether each added exchange reaction can carry flux. +% checkProduction also reports which metabolites must be connected in order +% to make the remaining ones producible, which requires further problems to be +% solved. % % Parameters % ---------- diff --git a/src/gapfilling/checkProduction.m b/src/gapfilling/checkProduction.m index a27607f3..157bede6 100755 --- a/src/gapfilling/checkProduction.m +++ b/src/gapfilling/checkProduction.m @@ -1,16 +1,16 @@ function [notProduced, notProducedNames, neededForProductionMat,minToConnect,model]=checkProduction(model,varargin) % checkProduction Check which metabolites can be produced from a model. % -% Checks which metabolites that can be produced from a model using the -% specified constraints. +% Checks which metabolites can be produced from a model under the current +% constraints. % -% 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. +% The function identifies which metabolites must be connected in order to +% have a fully connected network. It first identifies which metabolites +% can have a net production in the network. It then calculates which other +% metabolites must be able to have net production in order to have +% production of all metabolites in the network. If a network contains the +% equations A[external]->B, C->D, and D->E, production of C connects the +% metabolites D and E. % % Parameters % ---------- @@ -20,31 +20,43 @@ % Name-Value Arguments % -------------------- % checkNeededForProduction : logical -% 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 an effect of this (default false). +% true to calculate, for each metabolite that could not be produced, +% which of the other such metabolites can be produced when an uptake +% reaction for it is added (default false). % excretionFromCompartments : cell % cell array with compartment ids from which metabolites can be excreted % (default model.comps). % printDetails : logical -% print details to the screen (default true). +% true to print the metabolites that could not be produced to the command +% window (default true). % % Returns % ------- % notProduced : double -% indices of metabolites that could not be produced. +% indices of metabolites that could not be produced, counted among the +% metabolites in the compartments of excretionFromCompartments, in model +% order. % notProducedNames : cell % cell array with names and compartments for metabolites that could not % be produced. % neededForProductionMat : logical % matrix where n x m is true if metabolite n allows for production of -% metabolite m. +% metabolite m. The rows and columns follow the order of notProduced. +% It is empty if checkNeededForProduction is false. % minToConnect : cell -% 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. +% metabolites that need to be connected in order to be able to produce +% all other metabolites, each with the number of metabolites it +% connects. The metabolites are selected iteratively, each time the one +% that connects the most remaining metabolites, so the number of +% metabolites need not be the global minimum. It is empty if +% checkNeededForProduction is false. % model : struct -% updated model structure with excretion reactions added. +% model structure with an excretion reaction added for each metabolite +% in the compartments of excretionFromCompartments. When +% checkNeededForProduction is true, the excretion reaction of the last +% metabolite in notProduced is returned as an uptake reaction, because +% the loop that flips each reaction into an uptake reaction does not +% reset the last one. % % Examples % -------- diff --git a/src/gapfilling/fillGaps.m b/src/gapfilling/fillGaps.m index 0ebe1605..b0000105 100755 --- a/src/gapfilling/fillGaps.m +++ b/src/gapfilling/fillGaps.m @@ -1,54 +1,57 @@ function [newConnected, cannotConnect, addedRxns, newModel, exitFlag]=fillGaps(model,models,varargin) % fillGaps Use template model(s) to fill gaps in a model. % -% This method works by merging the model with the reference model(s) and -% checking which reactions can carry flux. All reactions that cannot 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 model is merged with the reference model(s). If useModelConstraints +% is false, the reactions of the model that cannot carry flux in the model +% are tested for flux in the merged model. The non-reversible reactions that +% carry flux in the merged model are the newConnected reactions. The other +% reactions are returned as cannotConnect: the reactions that cannot carry +% flux in the merged model and the reversible reactions that can, which are +% left out of the MILP target set. A MILP then minimises the number of +% active reactions from the reference models that are required for flux in +% the reactions that can be connected (newConnected). This requires that +% the input model has exchange reactions for the nutrients that its +% metabolism needs. If useModelConstraints is true, the flux test and the +% split into newConnected and cannotConnect are not run, and the MILP +% includes as few reactions as possible from the reference models to +% satisfy the model constraints. % -% The intended use is that the user can attempt a general gap-filling -% using useModelConstraints=false, or a more targeted gap-filling by -% setting constraints in the model structure and then using -% useModelConstraints=true. For example, to include reactions so that all -% biomass components can be synthesized, the user could define a biomass -% equation and set its 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. +% A general gap-filling uses useModelConstraints=false. A targeted +% gap-filling sets constraints in the model structure and uses +% useModelConstraints=true. For example, a model with a biomass equation +% whose lower bound is set above 0 gets the smallest set of reactions from +% the reference models that allows it to produce biomass. % % Parameters % ---------- % model : struct % a model structure that may contain gaps to be filled. % models : cell or struct -% a cell array of reference models or a model structure. The gaps will -% be filled using reactions from these models. +% a cell array of reference models or a model structure. Reactions +% from these models are used to fill the gaps. % % Name-Value Arguments % -------------------- % allowNetProduction : logical -% 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 cannot be further processed. If true, -% only the first type of unconnectivity is considered (default false). +% true to allow net production of all metabolites. A reaction can be +% unable to carry flux because one of the reactants is unavailable or +% because one of the products cannot be further processed. If true, +% only the first cause is considered (default false). % useModelConstraints : logical -% true if the constraints specified in the model structure should be -% used. If false then reactions are included from the template -% model(s) so that as many reactions as possible in model can carry -% flux (default false). +% true to use the constraints specified in the model structure. If +% false, reactions are included from the template model(s) so that as +% many reactions as possible in model can carry flux (default false). % supressWarnings : logical -% false if warnings should be displayed (default false). +% true to suppress the warning and the note about missing exchange +% reactions (default false). % rxnScores : double or cell -% 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 (default is -1 for all -% reactions). +% scores for each of the reactions in the reference model(s). If more +% than one model is supplied, rxnScores is a cell array of vectors. The +% solver maximises the sum of the scores of the included reactions. +% Used by the 'reference' algorithm (default -1 for all reactions). +% params : struct +% solver parameters passed to getMinNrFluxes (algorithm 'reference') or +% to gapFillMILP (algorithm 'gapfillMILP') (default empty struct). % algorithm : char % gap-filling algorithm to use (default 'reference'): % @@ -62,20 +65,26 @@ % epsilon : double % minimum flux threshold used by fastLP and swiftLP (default 1e-4). % minGrowth : double -% minimum growth rate for gapfillMILP (default [] = 10% of max FBA). +% minimum growth rate for gapfillMILP (default [], which is 10% of the +% maximum growth rate found by FBA on the merged model). % verbose : logical -% print progress messages for new algorithms (default true). +% true to print progress messages for the algorithms other than +% 'reference' (default true). % % Returns % ------- % newConnected : cell -% cell array with the reactions that could be connected. This is not -% calculated if useModelConstraints is true. +% cell array with the non-reversible reactions of model that cannot +% carry flux in model but can in the merged model. Empty if +% useModelConstraints is true or if the algorithm is not 'reference'. % cannotConnect : cell -% cell array with reactions that could not be connected. This is not -% calculated if useModelConstraints is true. +% cell array with the other reactions of model that cannot carry flux +% in model. For the algorithms 'fastLP' and 'swiftLP' it holds the +% reactions that remain blocked after merging (from gapFillFastLP), and +% for 'topological' the ids of the metabolites that cannot be reached. +% Empty if useModelConstraints is true or for 'gapfillMILP'. % addedRxns : cell -% cell array with the reactions that were added from "models". +% cell array with the reactions added from "models". % newModel : struct % the model with reactions added to fill gaps. % exitFlag : double @@ -97,14 +106,15 @@ % ----- % The 'reference' and 'gapfillMILP' algorithms solve a MILP with the % solver set by setRavenSolver. RAVEN's bundled GLPK solves it for small -% models (with a RAVEN:glpkMILP warning); for larger models Gurobi is much -% faster and more reliable (setRavenSolver('gurobi')). +% models. The RAVEN:glpkMILP warning issued with GLPK states that GLPK works +% for small problems and that Gurobi is much faster and more reliable for +% larger ones (setRavenSolver('gurobi')). % -% See Also +% See also % -------- -% ftINITFillGaps : the ftINIT-side counterpart, used when the reference -% model already contains the model's own reactions, so no per-task -% merge is needed. +% ftINITFillGaps : the variant of fillGaps for ftINIT, used when the +% reference model already contains the reactions of the model. No merge +% per task is needed in that case. %If the user only supplied a single template model if ~iscell(models) diff --git a/src/gapfilling/findLeakMetabolite.m b/src/gapfilling/findLeakMetabolite.m index 96c9f7ae..2d6db847 100644 --- a/src/gapfilling/findLeakMetabolite.m +++ b/src/gapfilling/findLeakMetabolite.m @@ -2,10 +2,10 @@ % findLeakMetabolite Find a metabolite that can be freely made or consumed. % % Tests whether the model can produce (excrete) or consume (take up) any -% metabolite without balanced stoichiometric constraints — a sign that the -% model contains a stoichiometric leak, futile cycle, or unconstrained -% exchange. This is the unified replacement for makeSomething ('produce') -% and consumeSomething ('consume'). +% metabolite without balanced stoichiometric constraints. A positive result +% indicates that the model contains a stoichiometric leak, a futile cycle or +% an unconstrained exchange. The direction 'produce' corresponds to the +% deprecated function makeSomething and 'consume' to consumeSomething. % % Parameters % ---------- @@ -22,33 +22,33 @@ % number of elements as metabolites in the model, or a vector of indexes % for metabolites to exclude from this analysis (default []). % isNames : logical -% 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 +% true if the supplied mets are metabolite names and false if they are +% IDs. Names exclude the metabolites of all compartments that carry the +% name, so the exact IDs are not needed. Only works if ignoreMets is a % cell array (default false). % minNrFluxes : logical -% 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 -% (default false). +% true to solve the MILP problem of minimising the number of fluxes. If +% false, the sum of fluxes is minimised. The MILP is slower and applies +% when the sum gives too many fluxes (default false). % allowExcretion : logical -% allow for excretion of all metabolites. Only used when direction is +% true to allow excretion of all metabolites. Only used when direction is % 'produce' (default true). % params : struct -% *obsolete option*. +% solver parameters, passed to solveLP when minNrFluxes is true (default +% a structure with relGap 0.8). % ignoreIntBounds : logical -% 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 (default false). +% true to ignore internal bounds (including reversibility). Exchange +% reactions are not affected. Finds unbalanced solutions that the +% default constraints do not allow (default false). % % Returns % ------- % solution : double % flux vector for the solution. % metabolite : double -% the index of the metabolite(s) which was produced or consumed. If -% possible only one metabolite is reported, but there are situations -% where metabolites can only be exchanged in pairs (or more). +% the index of the metabolite(s) produced or consumed. A single +% metabolite is reported when one suffices; some metabolites can only be +% exchanged in pairs or larger groups. % % Examples % -------- @@ -57,12 +57,12 @@ % % Notes % ----- -% Works by forcing at least 1 unit of "any metabolite" to be produced or -% consumed, then minimising for the sum of fluxes. If more than one -% metabolite is produced/consumed, it tries to find a single metabolite -% that satisfies the constraint on its own. +% The function forces a flux of at least 1 through a pooled exchange of all +% metabolites, then minimises the sum of fluxes. If more than one metabolite +% is produced or consumed, it searches for a single metabolite that +% satisfies the constraint on its own. % -% See Also +% See also % -------- % canExchange diff --git a/src/gapfilling/fitTasks.m b/src/gapfilling/fitTasks.m index d311cbbd..b45beb94 100755 --- a/src/gapfilling/fitTasks.m +++ b/src/gapfilling/fitTasks.m @@ -3,9 +3,9 @@ % % 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. 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. +% tasks are gap-filled one at a time in list order, and the reactions added +% for one task are kept for the following tasks. The order of the tasks can +% therefore influence the result. % % Parameters % ---------- @@ -15,7 +15,7 @@ % reference model from which to include reactions. % inputFile : char, optional % a task list in Excel format. See the function parseTaskList for -% details (optional if taskStructure is supplied). +% details. Optional if taskStructure is supplied. % % Name-Value Arguments % -------------------- @@ -23,17 +23,16 @@ % true if the results of the test should be displayed (default true). % rxnScores : double % 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 (default is -1 for all -% reactions). +% negative scores are allowed. The solver maximises the sum of the +% scores of the included reactions (default is -1 for all reactions). % taskStructure : struct -% structure with the tasks, as from parseTaskList. If supplied then +% structure with the tasks, as returned by parseTaskList. If supplied, % inputFile is ignored. % params : struct -% solver parameters, forwarded to the gap-filling back-end and from there -% to optimizeProb for each per-task MILP (default []). +% solver parameters, passed to the gap-filling function and from there to +% optimizeProb for each per-task MILP (default []). % gapFillMode : char -% which gap-filling back-end to use (default 'merge'): +% which gap-filling function to use (default 'merge'): % % - 'merge' : refModel holds only the candidate reactions, and fillGaps % merges it with the model for every task. @@ -41,12 +40,13 @@ % so no merge is needed per task. The task constraints are written % into refModel as well, and ftINITFillGaps does the gap-filling. % verbose : logical -% if true, the MILP progression will be shown. Only read when -% gapFillMode is 'preMerged' (default false). +% true to show the MILP progression. Only read when gapFillMode is +% 'preMerged' (default false). % resolveTies : logical -% if true, pin the gap-fill MILP's degenerate optimum to a canonical answer -% instead of relying on the solver Seed alone. Only read when gapFillMode is -% 'preMerged' -- see ftINITFillGaps' resolveTies (default false). +% true to fix the degenerate optimum of the gap-fill MILP to a canonical +% answer, which otherwise depends on the solver Seed. Only read when +% gapFillMode is 'preMerged'. See resolveTies of ftINITFillGaps +% (default false). % % Returns % ------- @@ -60,8 +60,8 @@ % failedTasks : logical % Nx1, true for each task that could not be gap-filled, either because % no feasible solution exists using the reference model or because the -% attempt threw. Such tasks add no reactions, so they are otherwise -% indistinguishable from tasks that already worked. +% attempt raised an error. Such tasks add no reactions, and the same +% holds for tasks that are feasible without gap-filling. % % Examples % -------- diff --git a/src/gapfilling/ftINITFillGaps.m b/src/gapfilling/ftINITFillGaps.m index 8c0db5ad..0fe836c6 100644 --- a/src/gapfilling/ftINITFillGaps.m +++ b/src/gapfilling/ftINITFillGaps.m @@ -1,29 +1,29 @@ function [addedRxns, newModel, exitFlag]=ftINITFillGaps(tModel, origModel, tRefModel,allowNetProduction,supressWarnings,rxnScores,params,verbose,resolveTies) % ftINITFillGaps -% Variant of fillGaps specially adapted to speed up generation of ftINIT models. +% Variant of fillGaps adapted to speed up the 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 +% 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) +% products cannot be processed further. If this +% parameter is true, only the first cause of blocked +% flux is considered (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. -% resolveTies if true, pin the gap-fill MILP's degenerate optimum to a -% canonical answer instead of relying on the solver Seed -% alone -- see getMinNrFluxes' resolveTies (optional, -% default false) +% reference tModel. The solver maximises the sum of +% the scores of the included reactions (optional, +% default -1 for all reactions) +% params solver parameters, passed to getMinNrFluxes (optional) +% verbose true to show the MILP progression. +% resolveTies true to fix the degenerate optimum of the gap-fill MILP +% to a canonical answer, which otherwise depends on the +% solver Seed. See resolveTies of getMinNrFluxes +% (optional, default false) % % addedRxns the rxns added % newModel the tModel with reactions added to fill gaps @@ -35,16 +35,18 @@ % because the solver stopped before reaching % optimality % -% 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. It then solves the MILP problem of including -% as few additional reactions as possible from the reference model so -% that the constraints already set on tModel (e.g. a required biomass -% flux, or exchange bounds) can be satisfied. +% This method works on the reference model, which already contains the +% tModel reactions. Reactions constrained to zero flux are removed +% (simplifyModel(tRefModel,false,false,true), deleteZeroInterval). It then +% solves the MILP problem of including as few additional reactions as +% possible from the reference model so that the constraints already set +% on tModel (for example a required biomass flux, or exchange bounds) can +% be satisfied. % -% See also: fillGaps, the tINIT-side counterpart, which merges a -% reference model with the model being gap-filled on every call instead -% of expecting them pre-merged. +% fillGaps merges the reference model with the model on every call, so it +% does not need a pre-merged reference model. +% +% See also: fillGaps % % Usage: [addedRxns, newModel, exitFlag]=... % ftINITFillGaps(tModel,origModel,tRefModel,allowNetProduction,... diff --git a/src/gapfilling/gapFillFastCore.m b/src/gapfilling/gapFillFastCore.m index 9e6c9547..a791cb8e 100644 --- a/src/gapfilling/gapFillFastCore.m +++ b/src/gapfilling/gapFillFastCore.m @@ -2,8 +2,9 @@ % gapFillFastCore L1-norm LP subroutine for fastGapFill. % % Finds the minimum-L1-flux extension of the model that activates all -% reactions in the core set. Any reaction with non-zero flux in the -% solution is "consistent" with the core. Used internally by gapFillFastLP. +% reactions in the core set. Any reaction with a flux of at least +% epsilon / 2 in the solution is "consistent" with the core. gapFillFastLP +% calls this function. % % Based on FASTCORE (Vlassis et al. 2014, PLoS Comput Biol 10:e1003424). % @@ -21,9 +22,10 @@ % Returns % ------- % activeRxns : logical -% logical vector (length numel(model.rxns)) where true indicates the -% reaction carries flux in the L1-minimal solution. Empty if the LP is -% infeasible (core reactions cannot all carry flux simultaneously). +% logical vector (length numel(model.rxns)) where true indicates that the +% reaction carries flux in the L1-minimal solution. All elements are +% false if the LP is infeasible (the core reactions cannot all carry flux +% simultaneously). % % See also % -------- diff --git a/src/gapfilling/gapFillFastLP.m b/src/gapfilling/gapFillFastLP.m index 4b56927b..b86ec965 100644 --- a/src/gapfilling/gapFillFastLP.m +++ b/src/gapfilling/gapFillFastLP.m @@ -1,5 +1,5 @@ function [addedRxns, newModel, cannotConnect] = gapFillFastLP(model, universalModel, varargin) -% gapFillFastLP LP-based gap-filling (fastGapFill / swiftGapFill). +% gapFillFastLP LP-based gap-filling (fastGapFill or swiftGapFill). % % Merges the draft model with a universal reaction database, then for each % blocked draft reaction calls an LP subroutine (FASTCORE or SWIFTCORE) to @@ -15,19 +15,23 @@ % model : struct % draft RAVEN model to be gap-filled. % universalModel : struct -% universal reaction database (RAVEN model). The caller is responsible -% for building this, e.g. via getKEGGModelForOrganism with broad scope. +% universal reaction database (RAVEN model), for example built with +% getKEGGModelForOrganism with broad scope. % -% Optional name-value parameters -% -------------------------------- -% 'epsilon' (default 1e-4) -% minimum flux threshold for a reaction to be considered active. -% 'variant' (default 'fast') -% 'fast' — use FASTCORE L1-norm LP (gapFillFastCore) -% 'swift' — use SWIFTCORE single-LP (gapFillSwiftCore); faster but -% stochastic (results may vary between runs/solvers). -% 'verbose' (default true) -% print progress messages. +% Name-Value Arguments +% -------------------- +% epsilon : double +% minimum flux threshold for a reaction to be considered active +% (default 1e-4). +% variant : char +% the LP subroutine (default 'fast'): +% +% - 'fast' : use the FASTCORE L1-norm LP (gapFillFastCore). +% - 'swift' : use the SWIFTCORE single LP (gapFillSwiftCore), which +% maximises the sum of the non-core fluxes. The LP is degenerate, so +% results can vary between runs and solvers. +% verbose : logical +% true to print progress messages (default true). % % Returns % ------- @@ -37,8 +41,8 @@ % newModel : struct % copy of model with addedRxns incorporated. % cannotConnect : cell -% blocked draft reaction IDs that remain blocked even after augmenting -% with the full universalModel (cannot be rescued by the database). +% IDs of blocked draft reactions that remain blocked after merging with +% the full universalModel (the database cannot rescue them). % % See also % -------- diff --git a/src/gapfilling/gapFillMILP.m b/src/gapfilling/gapFillMILP.m index fb574dbf..f391e4dd 100644 --- a/src/gapfilling/gapFillMILP.m +++ b/src/gapfilling/gapFillMILP.m @@ -5,14 +5,15 @@ % the model's objective (biomass) >= minGrowth, following the database % repair of Kumar et al. 2007 (BMC Bioinformatics 8:212, % doi:10.1186/1471-2105-8-212). Reactions already in the draft model keep -% their bounds: a reaction with the wrong direction is a curation issue and -% is not changed here. +% their bounds, including a wrong reaction direction. % -% The universal model should contain all candidate reactions, including -% exchange and transport reactions if those repair classes are desired. +% The universal model contains all candidate reactions. Exchange and +% transport reactions are candidates only if the universal model includes +% them. % -% This is a single-level MILP. It is computationally more expensive than -% gapFillFastLP but directly optimises for objective feasibility. +% The function solves a single-level MILP that minimises the number of added +% reactions subject to the objective floor. Compared with gapFillFastLP, the +% MILP takes more computation time. % % Parameters % ---------- @@ -21,19 +22,21 @@ % universalModel : struct % universal reaction database (RAVEN model). % -% Optional name-value parameters -% -------------------------------- -% 'minGrowth' (default []) -% minimum objective value to achieve. If empty, runs FBA on the merged -% model and uses 10% of the maximum as the floor. -% 'bigM' (default 1000) +% Name-Value Arguments +% -------------------- +% minGrowth : double +% minimum objective value to achieve. If empty, FBA on the merged model +% gives the maximum objective value and 10% of it is the floor +% (default []). +% bigM : double % Big-M constant for the coupling constraints of universal reactions -% with an infinite bound. A finite bound is used as it is. -% 'params' (default []) +% with an infinite bound. A finite bound is used as it is (default 1000). +% params : struct % solver parameter struct passed to optimizeProb. Fields such as -% params.TimeLimit and params.intTol can be used to tune the MILP. -% 'verbose' (default true) -% print progress messages. +% params.TimeLimit and params.intTol tune the MILP. If empty, intTol is +% 1e-9 and TimeLimit is 600 (default []). +% verbose : logical +% true to print progress messages (default true). % % Returns % ------- @@ -42,13 +45,16 @@ % newModel : struct % model with addedRxns incorporated. % exitFlag : double -% 1 = optimal, -1 = infeasible, -2 = timeout or other failure. +% 1 = the MILP returned a solution, -1 = no gap-filling result: the FBA +% or MILP is infeasible, the objective of the merged model is not +% positive, or the solver stops without a solution. % % Notes % ----- -% The MILP is solved with the solver set by setRavenSolver. RAVEN's bundled GLPK solves it for small -% models (with a RAVEN:glpkMILP warning); for larger models Gurobi is much -% faster and more reliable (setRavenSolver('gurobi')). +% The MILP is solved with the solver set by setRavenSolver. RAVEN's bundled +% GLPK solves it for small models. The RAVEN:glpkMILP warning issued with +% GLPK states that GLPK works for small problems and that Gurobi is much +% faster and more reliable for larger ones (setRavenSolver('gurobi')). % % See also % -------- diff --git a/src/gapfilling/gapFillSwiftCore.m b/src/gapfilling/gapFillSwiftCore.m index 876ee8e4..2ecea6a8 100644 --- a/src/gapfilling/gapFillSwiftCore.m +++ b/src/gapfilling/gapFillSwiftCore.m @@ -3,14 +3,13 @@ % % Single-LP alternative to gapFillFastCore. Maximises the sum of non-core % fluxes while enforcing that every core reaction carries at least epsilon -% flux. Any reaction with non-zero flux in the solution is "consistent" -% with the core. +% flux. Any reaction with a flux of at least epsilon / 2 in the solution is +% "consistent" with the core. % -% Because the maximisation objective makes the LP degenerate (many optima -% exist that differ only in which non-core reactions carry flux), the -% returned active set can vary between LP solvers and between runs with -% slightly different numerical conditions. This is the expected behaviour -% of SWIFTCORE (Tefagh & Boyd 2020). +% The maximisation objective makes the LP degenerate: many optima differ only +% in which non-core reactions carry flux. The returned active set can +% therefore vary between LP solvers and between runs with slightly different +% numerical conditions. % % Based on SWIFTCORE (Tefagh & Boyd 2020, BMC Bioinformatics 21:23). % @@ -28,8 +27,9 @@ % Returns % ------- % activeRxns : logical -% logical vector (length numel(model.rxns)) where true indicates the -% reaction carries flux in the solution. Empty on infeasibility. +% logical vector (length numel(model.rxns)) where true indicates that the +% reaction carries flux in the solution. All elements are false if the LP +% is infeasible. % % See also % -------- diff --git a/src/gapfilling/gapFillTopological.m b/src/gapfilling/gapFillTopological.m index bf832c02..2915866e 100644 --- a/src/gapfilling/gapFillTopological.m +++ b/src/gapfilling/gapFillTopological.m @@ -3,12 +3,11 @@ % % Identifies which metabolites in the draft model cannot be produced from a % given set of seed metabolites (medium), using a graph-based fixed-point -% "scope" computation (no solver required). For each unreachable metabolite, +% "scope" computation that needs no solver. For each unreachable metabolite, % finds candidate reactions in the universal database that produce it % directly. % -% This is a computationally cheap pre-screening step that prunes the -% universal database before a more expensive gap-filling solve. It is +% The step prunes the universal database before a gap-filling solve. It is % inspired by the topological analysis used in Meneco (Prigent et al. 2017, % PLoS Comput Biol). % @@ -27,30 +26,31 @@ % universalModel : struct % universal reaction database (RAVEN model). % -% Optional name-value parameters -% -------------------------------- -% 'seeds' (default []) -% Metabolite IDs (cell array) available from the medium. Default: +% Name-Value Arguments +% -------------------- +% seeds : cell +% metabolite IDs available from the medium. If empty, the seeds are the % metabolites of every exchange reaction whose bounds let it supply the -% metabolite, i.e. getExchangeRxns 'uptake' plus 'reverse'. -% 'targets' (default []) -% Metabolite IDs (cell array) that should be produced. Default: every +% metabolite, that is getExchangeRxns 'uptake' plus 'reverse' +% (default []). +% targets : cell +% metabolite IDs that should be produced. If empty, the targets are every % metabolite of the objective (biomass) reaction, substrates and % products; the first one when there are several objective reactions. % Without targets and without an objective reaction the function raises -% RAVEN:badInput. -% 'verbose' (default true) -% print a summary of the results. +% RAVEN:badInput (default []). +% verbose : logical +% true to print a summary of the results (default true). % % Returns % ------- % result : struct -% .reachableMets — logical vector (length nMets) marking producible mets -% .blockedMets — cell array of metabolite IDs that cannot be reached -% .candidateRxns — n-by-1 cell array of universal rxn ID lists, one -% cell per blocked metabolite (same order as blockedMets) -% .pruningFraction — fraction of universal reactions pruned (not needed -% for any blocked metabolite) +% .reachableMets: logical vector (length nMets) marking producible mets +% .blockedMets: cell array of metabolite IDs that cannot be reached +% .candidateRxns: n-by-1 cell array of universal rxn ID lists, one cell +% per blocked metabolite (same order as blockedMets) +% .pruningFraction: fraction of universal reactions pruned (not +% candidates for any blocked metabolite) % % See also % -------- diff --git a/src/gapfilling/gapReport.m b/src/gapfilling/gapReport.m index 7212a86d..f8a006d4 100755 --- a/src/gapfilling/gapReport.m +++ b/src/gapfilling/gapReport.m @@ -1,16 +1,16 @@ function [noFluxRxns, noFluxRxnsRelaxed, subGraphs, notProducedMets, minToConnect,... neededForProductionMat, canProduceWithoutInput, canConsumeWithoutOutput, ... connectedFromTemplates, addedFromTemplates]=gapReport(model, varargin) -% gapReport Perform a gap analysis and summarize the results. +% gapReport Perform a gap analysis and summarise the results. % -% Runs a series of connectivity checks on the model - which reactions are +% Runs a series of connectivity checks on the model: which reactions are % blocked, how many isolated sub-networks exist, which metabolites cannot % be produced (and the minimal set of metabolites that would need to be -% connected to fix that), and which metabolites can be produced/consumed -% without any input/output, with every boundary reaction closed. If -% templateModels is supplied, it also attempts to gap-fill using those -% models. A formatted report is printed to the command window; the same -% results are returned as outputs for further use. +% connected to fix that), and which metabolites can be produced without any +% input or consumed without any output, with every boundary reaction closed. +% If templateModels is supplied, it also attempts to gap-fill using those +% models. A formatted report is printed to the command window, and the same +% results are returned as outputs. % % Parameters % ---------- @@ -20,8 +20,8 @@ % Name-Value Arguments % -------------------- % templateModels : cell -% a cell array of template models to use for gap filling. If omitted, -% the automated gap-filling section is skipped. +% a cell array of template models used for gap filling. If omitted, the +% automated gap-filling section is skipped. % % Returns % ------- @@ -63,8 +63,8 @@ % % The model must be feasible under its own bounds and with its boundary % closed. Otherwise gapReport stops with a RAVEN:infeasibleModel error that -% names the reactions with a forced flux; set the bounds of ATP maintenance -% and any other forced flux to zero first. +% names the reactions with a forced flux. Such reactions, for example ATP +% maintenance, need bounds that allow zero flux. % % Examples % -------- diff --git a/src/installation/addRavenToUserPath.m b/src/installation/addRavenToUserPath.m index 1b44769c..3ff23a47 100755 --- a/src/installation/addRavenToUserPath.m +++ b/src/installation/addRavenToUserPath.m @@ -1,15 +1,16 @@ function addRavenToUserPath(varargin) % 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 +% all subdirectories except those with .git or doc in their path) to the +% path each time MATLAB is started. +% The function applies when 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. +% rights. The startup.m file in the userpath runs at each MATLAB start and +% loads the paths. % % Name-Value Arguments % -------------------- -% overwrite logical, whether startup.m in the userpath should -% overwritten (otherwise the RAVEN paths are appended) +% overwrite logical, true if startup.m in the userpath is +% overwritten and false if the RAVEN paths are appended % (default true) p=parseRAVENargs(varargin, {'overwrite',true}); diff --git a/src/installation/checkFunctionUniqueness.m b/src/installation/checkFunctionUniqueness.m index e7c02649..ce23ce34 100755 --- a/src/installation/checkFunctionUniqueness.m +++ b/src/installation/checkFunctionUniqueness.m @@ -1,16 +1,18 @@ function status = checkFunctionUniqueness(varargin) % checkFunctionUniqueness % Checks whether RAVEN toolbox functions are unique across other -% toolboxes or user-created functions accessible in Matlab pathlist. +% toolboxes and user-created functions on the MATLAB path. % % Name-Value Arguments % -------------------- -% 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. +% altDirs char with alternative directories with functions, separated +% by the path separator of the platform (';' on Windows, ':' +% otherwise). Specified only when the function checks +% directories other than the RAVEN toolbox. % % Output: -% status true if all functions are unique, otherwise false +% status true if all functions are unique, otherwise false. Without +% an output argument the function prints Pass or Fail. % % Usage: checkFunctionUniqueness() diff --git a/src/installation/downloadRavenBinaries.m b/src/installation/downloadRavenBinaries.m index 8df2e4a7..881bb725 100644 --- a/src/installation/downloadRavenBinaries.m +++ b/src/installation/downloadRavenBinaries.m @@ -1,25 +1,27 @@ function downloadRavenBinaries(tools) % downloadRavenBinaries % Download RAVEN's external command-line binaries on demand from the -% toolbox-assets repository into RAVEN's src/external/ directory. Only the binary -% matching the current platform is fetched, and only when needed. +% toolbox-assets repository into the src/external directory of RAVEN. Only +% the binary matching the current platform is fetched, and only when it is +% missing. % % Input: % tools cell array, subset of {'blast+','diamond','hmmer'} to % download. Defaults to all of them. Tools whose target executable is % already present are skipped. % -% This requires an internet connection. For an offline / air-gapped install, -% download the "*-binaries" RAVEN release (which bundles all binaries) and -% unzip it into the RAVEN software/ directory instead. +% The download requires an internet connection. An offline installation +% uses the offline bundle (RAVEN--full.zip) attached to each RAVEN +% release, which contains the binaries of all platforms in src/external. % % The binaries are hosted as release assets in % https://github.com/CompMetEng/toolbox-assets. % % Usage: downloadRavenBinaries({'blast+','diamond'}) % -% NOTE: lazily invoked by getBlast/getDiamond/getKEGGModelForOrganism and -% offered by checkRaven when a binary is missing. +% getBlast, getDiamond and getKEGGModelForOrganism call this function +% when a binary is missing. checkRaven calls it for all three tools when its +% checkBinaries input is true. if nargin < 1 || isempty(tools) tools = {'blast+','diamond','hmmer'}; diff --git a/src/installation/fetchToolboxAsset.m b/src/installation/fetchToolboxAsset.m index a2a9abe8..cbd3b0bf 100644 --- a/src/installation/fetchToolboxAsset.m +++ b/src/installation/fetchToolboxAsset.m @@ -3,11 +3,10 @@ % % Downloads assetName from the given release tag of % https://github.com/CompMetEng/toolbox-assets into destDir -% and returns its local path. An already-downloaded copy is reused as-is. -% Generic across toolbox-assets' release families (KEGG artefacts, HMM -% libraries, binaries, ...): nothing here is specific to any one of -% them, so callers supply the release tag and asset name rather than -% this function hardcoding either. +% and returns its local path. An already-downloaded copy is reused without a +% new download or checksum test. The function applies to every toolbox-assets +% release family (KEGG artefacts, HMM libraries, binaries), and the caller +% supplies the release tag and the asset name. % % A download is checked against the SHA-256 checksum that the % toolbox-assets manifest (release manifest-v3) lists for it. A file whose @@ -20,9 +19,9 @@ % destDir : char % directory to download into (created if it does not exist yet). % releaseTag : char -% the toolbox-assets release tag, e.g. 'kegg118'. +% the toolbox-assets release tag, for example 'kegg118'. % assetName : char -% the release asset file name, e.g. 'kegg118_core.tar.gz'. +% the release asset file name, for example 'kegg118_core.tar.gz'. % % Returns % ------- diff --git a/src/installation/findRAVENroot.m b/src/installation/findRAVENroot.m index 02334031..567364d6 100755 --- a/src/installation/findRAVENroot.m +++ b/src/installation/findRAVENroot.m @@ -1,17 +1,18 @@ function [ravenPath, prevDir] = findRAVENroot() % findRAVENroot % Finds the root of the RAVEN directory by searching for the path to -% version.txt. 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. +% version.txt. Can also record the current directory, for functions that use +% the ravenPath to navigate to a precise folder and return to the previous +% directory afterwards. See, for example, optimizeProb calling glpk. % -% The resolved path is cached for the rest of the MATLAB session: this is -% called on every solver invocation, and re-reading the RAVEN.ravenPath -% preference from disk every time is both wasteful and, under the sustained -% call volume of a full test run, an intermittent source of failures from -% MATLAB's own preference-file I/O. Run `clear findRAVENroot` after -% changing that preference (checkRaven does this already) to pick -% up the change without restarting MATLAB. +% The RAVEN.ravenPath preference is used if it points to a directory with a +% version.txt file. Otherwise the search starts at the location of this +% function file and moves up the directory tree. +% +% The resolved path is cached for the rest of the MATLAB session, so the +% preference is read once although the function is called on every solver +% invocation. `clear findRAVENroot` drops the cached path after a change of +% the preference (checkRaven does this) without a restart of MATLAB. persistent cachedPath prevDir = pwd(); diff --git a/src/installation/removeRavenFromPath.m b/src/installation/removeRavenFromPath.m index e2738339..c867e62b 100755 --- a/src/installation/removeRavenFromPath.m +++ b/src/installation/removeRavenFromPath.m @@ -1,10 +1,9 @@ function removeRavenFromPath() % 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. +% MATLAB path and saves the path. The RAVEN folder itself is kept. If RAVEN +% is installed as MATLAB Add-On, the function raises an error that +% advises uninstalling RAVEN via the Add-On Manager. % % Usage: removeRavenFromPath() diff --git a/src/installation/updateDocumentation.m b/src/installation/updateDocumentation.m index 97892506..e899f706 100755 --- a/src/installation/updateDocumentation.m +++ b/src/installation/updateDocumentation.m @@ -1,12 +1,12 @@ function updateDocumentation() % updateDocumentation -% Regenerates the HTML documentation in RAVEN's docs/html directory from the -% function help texts. The docs/html directory is deleted and rebuilt, so -% anything hand-edited there is lost. +% Regenerates the HTML documentation in the docs/html directory of RAVEN from +% the function help texts. The docs/html directory is deleted and rebuilt, so +% manual edits there are lost. % -% The Documentation workflow runs this on every push to a release branch -% and commits the result, so docs/html stays in step with the sources without -% anyone running it by hand. Run it locally only to preview. +% The Documentation workflow runs this function on every push to the develop +% or main branch that changes a .m file or the workflow file, and commits the +% result. Running the function locally previews the documentation. % % Usage: updateDocumentation() diff --git a/src/io/checkFileExistence.m b/src/io/checkFileExistence.m index 05d0019d..5244719f 100755 --- a/src/io/checkFileExistence.m +++ b/src/io/checkFileExistence.m @@ -1,14 +1,14 @@ function files=checkFileExistence(files,varargin) % 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. +% A file name without a full path refers to a file in the current folder, +% which is prepended to the file name. % % Parameters % ---------- % files : char or cell -% string or cell array of strings with path to file(s) or path or -% filename(s). +% string or cell array of strings with the path or file name of one or +% more files. % % Name-Value Arguments % -------------------- @@ -20,17 +20,17 @@ % - 2 : copy file(s) to system default temporary folder and return % full path % allowSpace : logical -% whether the 'space' character is allowed in the path (default true). +% true if the space character is allowed in the path (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 (default true). -% Can only be set to false if fullOrTemp is set to 1. +% true if file existence is checked. Setting it to false returns the full +% path to a file that does not exist yet (default true). Can only be set +% to false if fullOrTemp is set to 1. % % Returns % ------- % files : char or cell -% string or cell array of strings with updated paths if fullOrTemp was -% set as 1 or 2, otherwise original paths are returned. +% string or cell array of strings with updated paths if fullOrTemp is 1 +% or 2, otherwise the original paths. % % Examples % -------- diff --git a/src/io/cleanSheet.m b/src/io/cleanSheet.m index 3065abba..6b71cd7a 100755 --- a/src/io/cleanSheet.m +++ b/src/io/cleanSheet.m @@ -1,6 +1,6 @@ % cleanSheet Clean up an Excel sheet. % -% Removes empty rows/columns (and performs some other checks). +% Removes empty rows and columns, and performs further checks. % % Parameters % ---------- @@ -13,16 +13,17 @@ % true if commented lines (non-empty first cell in each row) should be % removed (default true). % removeOnlyCap : logical -% remove columns with captions but no other values (default false). +% true to remove columns with captions but no other values (default +% false). % removeNoCap : logical -% remove columns without captions (default true). +% true to remove columns without captions (default true). % removeEmptyRows : logical -% remove rows with no non-empty cells (default true). +% true to remove rows with no non-empty cells (default true). % % Returns % ------- % raw : cell -% cleaned version. +% the cleaned cell array. % keptRows : double % indices of the kept rows in the original structure. % keptCols : double diff --git a/src/io/exportForGit.m b/src/io/exportForGit.m index 59f289fa..4e183734 100755 --- a/src/io/exportForGit.m +++ b/src/io/exportForGit.m @@ -2,13 +2,13 @@ % exportForGit Export a model for a Git-maintained model repository. % % Generates a directory structure and populates it with model files, ready -% to be committed to a Git(Hub) maintained model repository. Writes the -% model as SBML L3V1 FBCv2 (both XML and YAML), COBRA text, Matlab MAT-file -% and Microsoft Excel formats. +% to be committed to a Git or GitHub repository of a model. Writes the +% model as SBML L3V1 FBCv2 (XML) and YAML, COBRA text, MATLAB MAT-file and +% Microsoft Excel formats. % % The flags mainBranchFlag, subDirs, COBRAtext and neverPrefixIDs accept a -% scalar logical or 0/1, or an empty value for the default. Text and other -% types raise RAVEN:badInput. +% scalar logical, the value 0 or 1, or an empty value for the default. Text +% and other types raise RAVEN:badInput. % % Parameters % ---------- @@ -28,21 +28,20 @@ % should be exported (default all formats as {'mat', 'txt', 'xlsx', % 'xml', 'yml'}). % mainBranchFlag : logical -% if true, function will error if RAVEN (and GECKO for enzyme- -% constrained models) is/are not on the main branch (default false). +% true to raise an error if RAVEN (and GECKO for enzyme-constrained +% models) is not on the main or master branch (default false). % subDirs : logical -% whether model files for each file format should be written in their -% 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 (default true). +% true to write the model files of each file format in their own +% subdirectory, with 'model' as parent directory, following the +% standard-GEM repository format. If false, all files are stored in the +% same folder (default true). % COBRAtext : logical -% whether the txt file should be in COBRA Toolbox format using -% metabolite IDs, instead of metabolite names and compartments -% (default false). +% true to write the txt file in COBRA Toolbox format, which uses +% metabolite IDs. If false, the file uses metabolite names and +% compartments (default false). % neverPrefixIDs : logical % true if prefixes are never added to identifiers, even if they start -% with e.g. digits. This might result in invalid SBML files (default -% false). +% with digits. This can result in invalid SBML files (default false). % % Examples % -------- diff --git a/src/io/exportModel.m b/src/io/exportModel.m index 2bbda7f2..af668d07 100755 --- a/src/io/exportModel.m +++ b/src/io/exportModel.m @@ -9,18 +9,18 @@ function exportModel(model,varargin) % Name-Value Arguments % -------------------- % fileName : char -% filename to export the model to. A dialog window will open if no file -% name is specified. +% file name to export the model to. A dialog window opens if no file name +% is specified. % neverPrefix : logical % true if prefixes are never added to identifiers, even if they start -% with e.g. digits. This might result in invalid SBML files (default -% false). +% with digits. This can result in invalid SBML files (default false). % supressWarnings : logical -% true if warnings should be suppressed. This might result in invalid -% SBML files, as no checks are performed (default false). +% true if warnings should be suppressed. The check of the model +% structure (checkModelStruct) is skipped, which can result in invalid +% SBML files (default false). % sortIds : logical -% whether metabolites, reactions and genes should be sorted -% alphabetically by their identifiers (default false). +% true to sort metabolites, reactions and genes alphabetically by their +% identifiers (default false). % % Examples % -------- diff --git a/src/io/exportToExcelFormat.m b/src/io/exportToExcelFormat.m index 94db137c..fe719d55 100755 --- a/src/io/exportToExcelFormat.m +++ b/src/io/exportToExcelFormat.m @@ -9,11 +9,11 @@ function exportToExcelFormat(model,varargin) % Name-Value Arguments % -------------------- % fileName : char -% file name of the Excel file. Only xlsx format is supported. A dialog -% window will open if fileName is empty. +% file name of the Excel file. Only the xlsx format is supported. A +% dialog window opens if fileName is empty. % sortIds : logical -% whether metabolites, reactions and genes should be sorted -% alphabetically by their identifiers (default false). +% true to sort metabolites, reactions and genes alphabetically by their +% identifiers (default false). % % Examples % -------- diff --git a/src/io/importModel.m b/src/io/importModel.m index 00ec9e95..347e31bb 100755 --- a/src/io/importModel.m +++ b/src/io/importModel.m @@ -4,19 +4,18 @@ % Name-Value Arguments % -------------------- % fileName : char -% a SBML file to import. A dialog window will open if no file name is +% a SBML file to import. A dialog window opens if no file name is % specified. % removeExcMets : logical -% if true, exchange metabolites are removed from the imported model -% (default true). +% true to remove exchange metabolites from the imported model (default +% true). % removePrefix : logical -% 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 (default true). +% true to remove identifier prefixes when loading the model: G_ for +% genes, R_ for reactions, M_ for metabolites, and C_ for compartments. +% The prefix of a type is removed only if all identifiers of that type +% contain it (default true). % supressWarnings : logical -% true if warnings regarding the model structure should be supressed -% (default false). +% true to suppress warnings about the model structure (default false). % % Returns % ------- @@ -50,13 +49,13 @@ % - rxnNotes : reaction notes % - rxnReferences : reaction references % - rxnConfidenceScores : reaction confidence scores -% - rxnDeltaG : reaction Gibbs free energy, from a `deltaG` notes key -% (same convention exportModel writes and raven-toolbox reads/writes; -% omitted entirely if no reaction has one) +% - rxnDeltaG : reaction Gibbs free energy, from the `deltaG` notes +% field (the convention that exportModel writes and raven-toolbox +% reads and writes; omitted if no reaction has one) % - genes : list of all genes % - geneComps : compartments for genes % - geneMiriams : structure with MIRIAM information about the genes -% - geneShortNames : gene alternative names (e.g. ERG10) +% - geneShortNames : gene alternative names (for example ERG10) % - proteins : protein associated to each gene % - metNames : metabolite description % - metComps : compartments for metabolites @@ -64,9 +63,9 @@ % - metFormulas : metabolite chemical formula % - metMiriams : structure with MIRIAM information about the metabolites % - metCharges : metabolite charge -% - metDeltaG : metabolite Gibbs free energy, from a `deltaG` notes key -% (same convention exportModel writes and raven-toolbox reads/writes; -% omitted entirely if no metabolite has one) +% - metDeltaG : metabolite Gibbs free energy, from the `deltaG` notes +% field (the convention that exportModel writes and raven-toolbox +% reads and writes; omitted if no metabolite has one) % - unconstrained : true if the metabolite is an exchange metabolite % % Examples @@ -75,9 +74,9 @@ % % Notes % ----- -% A number of consistency checks are performed to ensure that the model is -% valid. Take these warnings seriously and modify the model structure to -% solve them. +% checkModelStruct checks the consistency of the imported model and raises +% warnings about problems in the model structure. supressWarnings skips this +% check. p=parseRAVENargs(varargin, {'fileName',[]; 'removeExcMets',[]; 'removePrefix',[]; 'supressWarnings',false}); fileName=p.fileName; removeExcMets=p.removeExcMets; removePrefix=p.removePrefix; supressWarnings=p.supressWarnings; diff --git a/src/io/parseYAML.m b/src/io/parseYAML.m index 602f4441..c33b61a7 100644 --- a/src/io/parseYAML.m +++ b/src/io/parseYAML.m @@ -1,21 +1,20 @@ function out = parseYAML(filename) -% parseYAML Read a YAML file into a MATLAB struct/cell tree. +% parseYAML Read a YAML file into a tree of MATLAB structs and cells. % % Supports block-style mappings and sequences (indentation-based), % flow-style mappings and sequences (`{ key: value }`, `[a, b]`), quoted % and unquoted scalars, and comments. Does not support multi-document -% files, anchors/aliases, tags, or block scalars (`|`, `>`). +% files, anchors, aliases, tags, or block scalars (`|`, `>`). % -% Use this for parsing YAML configuration / data files with a nested -% mapping/sequence/scalar shape (e.g. condition files consumed by -% applyCondition). For loading a cobra-format model YAML, use -% readYAMLmodel instead — that function knows the model schema and -% returns a populated RAVEN model struct. +% The function parses YAML configuration and data files with nested +% mappings, sequences and scalars (for example condition files consumed by +% applyCondition). readYAMLmodel loads a cobra-format model YAML: it applies +% the model schema and returns a populated RAVEN model struct. % % Parameters % ---------- % filename : char -% Path to the YAML file. +% path to the YAML file. % % Returns % ------- @@ -26,7 +25,7 @@ % - sequence -> cell column vector % - quoted or unquoted string -> char % - integer or float -> double -% - true/false -> logical +% - true, false -> logical % - null / ~ / empty value -> [] % % Examples diff --git a/src/io/readYAMLmodel.m b/src/io/readYAMLmodel.m index 3db80cd6..29a6ff9b 100755 --- a/src/io/readYAMLmodel.m +++ b/src/io/readYAMLmodel.m @@ -1,16 +1,16 @@ function model=readYAMLmodel(varargin) % readYAMLmodel Read a model structure from a YAML file. % -% Reads a yaml file matching (roughly) the standard cobra-format model -% yaml structure. +% Reads a yaml file in the cobra-format model yaml structure that +% writeYAMLmodel writes. % % Name-Value Arguments % -------------------- % fileName : char -% a model file in yaml file format. A dialog window will open if no -% file name is specified. +% a model file in yaml file format. A dialog window opens if no file +% name is specified. % verbose : logical -% set as true to monitor progress (default false). +% true to print the progress (default false). % % Returns % ------- diff --git a/src/io/writeYAMLmodel.m b/src/io/writeYAMLmodel.m index b9afd250..6dd86094 100755 --- a/src/io/writeYAMLmodel.m +++ b/src/io/writeYAMLmodel.m @@ -1,10 +1,10 @@ function writeYAMLmodel(model,varargin) -% writeYAMLmodel Write a model to a yaml file in the standard cobra-format -% !!omap structure. +% writeYAMLmodel Write a model to a YAML file in the cobra-format !!omap structure. % % The format uses the standard !!omap layout, extended with RAVEN-only % top-level per-entry keys (inchis, deltaG, metFrom, rxnFrom, references, -% confidence_score, protein) and the GECKO ec-rxns / ec-enzymes sections. +% confidence_score, protein, notes) and the GECKO ec-rxns and ec-enzymes +% sections. % Reaction EC numbers are written inside the `annotation` block as % `ec-code`, not as a top-level reaction key. % @@ -16,12 +16,11 @@ function writeYAMLmodel(model,varargin) % Name-Value Arguments % -------------------- % fileName : char -% name that the file will have. A dialog window will open if no file -% name is specified. +% name of the file. A dialog window opens if no file name is specified. % sortIds : logical -% if metabolites, reactions, genes and compartments should be sorted -% alphabetically by their identifier, otherwise they are kept in their -% original order (default false). +% true to sort metabolites, reactions, genes and compartments +% alphabetically by their identifier. If false, they keep their original +% order (default false). % % Examples % -------- diff --git a/src/localization/defaultCompartmentMap.m b/src/localization/defaultCompartmentMap.m index a623e3a0..3bad38cf 100644 --- a/src/localization/defaultCompartmentMap.m +++ b/src/localization/defaultCompartmentMap.m @@ -1,25 +1,25 @@ function map = defaultCompartmentMap() -% defaultCompartmentMap Default predictor/database compartment label -> model compartment id. +% defaultCompartmentMap Default map from compartment labels to model compartment ids. % -% Returns a containers.Map from lower-case predictor / database compartment labels (as used by -% DeepLoc, MULocDeep, COMPARTMENTS and UniProt) to compartment ids, tuned for yeast/fungal -% models (e.g. yeast-GEM codes). Pass it (or your own map) to parseScores / getUniProtScores as +% Returns a containers.Map from lower-case compartment labels of predictors and databases (as +% used by DeepLoc, MULocDeep, COMPARTMENTS and UniProt) to compartment ids, for yeast and fungal +% models (for example yeast-GEM codes). The map is passed to parseScores or getUniProtScores as % 'compartmentMap'. % -% The table below is also the worked example of how such a map is built, so read it as three -% deliberate decisions rather than a lookup list: +% The map holds three decisions: % -% - **Which compartments exist.** A label absent from the map is dropped along with its score -% column, so listing only the ids your model has is how unwanted compartments are excluded. -% 'plastid' is absent because fungi lack one; a plant model would add it. -% - **Which labels are the same thing.** Predictors disagree on wording, so 'cytoplasm' and -% 'cytosol' both map to 'c', and 'mitochondrion' / 'mitochondria' / 'mitochondrial' all map -% to 'm'. Merged columns are combined by maximum, not sum. -% - **Which distinct compartments to collapse.** 'lysosome' maps to 'v' not because it is a -% vacuole but because a yeast model has no lysosome and the vacuole is its functional -% equivalent. Change this if your model separates them. +% - Compartments present. A label absent from the map is dropped along with its score column, so +% the map lists only the compartment ids of the model. 'plastid' is absent because fungi have +% no plastid; a plant model adds it. +% - Labels that name the same compartment. Predictors differ in wording, so 'cytoplasm' and +% 'cytosol' both map to 'c', and 'mitochondrion', 'mitochondria' and 'mitochondrial' all map +% to 'm'. Merged columns are combined by their maximum. +% - Distinct compartments that are collapsed. 'lysosome' maps to 'v' because a yeast model has +% no lysosome and the vacuole is its functional equivalent. A model that separates the two +% needs a different mapping. % -% Extend a copy rather than editing this function, e.g. +% Changes to the mapping go into a copy of the map, which leaves this function unedited, for +% example: % % map = defaultCompartmentMap; % map('cell wall') = 'ce'; diff --git a/src/localization/getUniProtScores.m b/src/localization/getUniProtScores.m index 913e8964..3799b031 100644 --- a/src/localization/getUniProtScores.m +++ b/src/localization/getUniProtScores.m @@ -1,36 +1,36 @@ function GSS = getUniProtScores(organism, varargin) -% getUniProtScores Fetch curated subcellular locations from UniProt -> gene scoring structure. +% getUniProtScores Fetch curated subcellular locations from UniProt as a gene scoring structure. % -% Queries the UniProtKB REST API for an organism's "Subcellular location" annotations and parses -% them into the GSS consumed by predictLocalization (no manual export needed). UniProt's curated -% location is qualitative, so each annotated compartment gets score 1.0 (a multi-located protein -% lands in several). Requires an internet connection. +% Queries the UniProtKB REST API for the "Subcellular location" annotations of an organism and +% parses them into the GSS consumed by predictLocalization. No manual export is needed. UniProt +% locations are qualitative, so each annotated compartment gets score 1.0 and a protein with +% several annotated locations scores 1.0 in each of them. The function requires an internet +% connection. % % Parameters % ---------- % organism : double or char -% a UniProt organism / taxonomy id (e.g. 559292 for S. cerevisiae S288C). +% a UniProt organism (taxonomy) id (for example 559292 for S. cerevisiae S288C). % % Name-Value Arguments % -------------------- % idField : char -% which identifier becomes the gene id: 'gene_oln' (ordered locus / ORF, the default, which -% matches yeast-GEM), 'accession', or 'gene_primary'. +% which identifier becomes the gene id: 'gene_oln' (ordered locus or ORF name, the default, +% which matches yeast-GEM), 'accession', or 'gene_primary'. % reviewed : logical -% restrict to curated Swiss-Prot entries (default true). +% true to restrict the query to curated Swiss-Prot entries (default true). % compartmentMap : containers.Map -% UniProt location term -> your model's compartment id (default -% defaultCompartmentMap). Here the map is not only a renaming: its keys are -% also the vocabulary searched for in UniProt's "Subcellular location [CC]" -% free text, matched whole-word and case insensitively, so they must be -% UniProt's own noun forms ('endoplasmic reticulum', not 'ER') and a term -% that is not a key is never looked for. Several keys may share one -% compartment id, which merges them; since every hit scores 1.0, merging -% here means "annotated to any of these counts as this compartment". One -% key cannot be split across two compartment ids - see parseScores for why, -% and for the recipe to duplicate a column on the returned GSS instead. +% maps UniProt location terms to the compartment ids of the model (default +% defaultCompartmentMap). The keys are also the vocabulary searched for in the +% "Subcellular location [CC]" free text of UniProt, matched as whole words and +% case insensitively. The keys must be the noun forms used by UniProt +% ('endoplasmic reticulum', not 'ER'), and a term that is not a key is not searched. +% Several keys may share one compartment id, which merges them; since every hit +% scores 1.0, a protein annotated to any of the merged terms scores 1.0 in that +% compartment. One key cannot map to two compartment ids; parseScores describes +% how to duplicate a column of the returned GSS instead. % extraQuery : char -% an additional UniProt query clause, ANDed into the query (e.g. 'gene:CIT1'). +% an additional UniProt query clause, combined with the query by AND (for example 'gene:CIT1'). % % Returns % ------- diff --git a/src/localization/parseScores.m b/src/localization/parseScores.m index 15f3c7fa..6306da62 100755 --- a/src/localization/parseScores.m +++ b/src/localization/parseScores.m @@ -1,14 +1,14 @@ function GSS = parseScores(inputFile, varargin) -% parseScores Parse predictor / database output into a gene scoring structure (GSS). +% parseScores Parse predictor or database output into a gene scoring structure (GSS). % -% Reads the output of a subcellular-localization predictor or evidence database and +% Reads the output of a subcellular localisation predictor or evidence database and % builds the gene scoring structure consumed by predictLocalization. Scores are -% normalized so the best score for each gene is 1.0. +% normalised so that the highest score of each gene is 1.0. % % Parameters % ---------- % inputFile : char -% the file with the predictor / database output. +% the file with the predictor or database output. % % Name-Value Arguments % -------------------- @@ -18,15 +18,15 @@ % compartment), 'compartments' (a COMPARTMENTS jensenlab.org channel TSV), or % 'uniprot' (a UniProtKB TSV export with a "Subcellular location [CC]" column). % compartmentMap : containers.Map -% renames the predictor's / database's compartment labels to your model's -% compartment ids. Keys are the labels as the predictor writes them, lower -% case; values are the compartment ids you want in the GSS. See -% Compartment mapping below. Optional for every predictor except 'uniprot', -% where it also supplies the location vocabulary and defaults to -% defaultCompartmentMap. +% maps the compartment labels of the predictor or database to the compartment ids of +% the model. Keys are the labels as the predictor writes them, in lower case; values +% are the compartment ids in the GSS. Optional for every predictor except 'uniprot', +% where the map also supplies the location vocabulary and defaults to +% defaultCompartmentMap. See Compartment mapping below. % idColumn : char or double -% column (name or 1-based index) holding the gene id for 'mulocdeep' / 'uniprot'. -% Default: the first column. For yeast-GEM, use the UniProt ordered-locus column. +% column (name or 1-based index) holding the gene id for 'mulocdeep' and 'uniprot' +% (default: the first column). For yeast-GEM, the UniProt ordered-locus column holds +% the matching ids. % minConfidence : double % for 'compartments', drop annotations with confidence below this (default 0). % @@ -37,34 +37,31 @@ % % - genes : cell, one entry per gene. % - compartments : cell, one entry per compartment column. -% - scores : double, numel(genes)-by-numel(compartments), normalized so -% the best score per gene is 1.0. +% - scores : double, numel(genes)-by-numel(compartments), normalised so +% that the highest score per gene is 1.0. % % Compartment mapping % ------------------- -% Predictors emit their own compartment vocabulary ("Endoplasmic reticulum", -% "Golgi apparatus", ...), which rarely matches a model's compartment ids. -% compartmentMap is a containers.Map that translates them, and it is the only -% place that translation happens - the returned GSS already uses your ids. -% defaultCompartmentMap returns a worked example, tuned for yeast/fungal -% models; use it as-is, or as the template for your own. Three rules: +% Predictors use their own compartment vocabulary ("Endoplasmic reticulum", +% "Golgi apparatus", ...), which need not match the compartment ids of a model. +% compartmentMap is a containers.Map that translates the labels; the translation +% happens only there, so the returned GSS contains the ids of the map values. +% defaultCompartmentMap returns an example map for yeast and fungal models, which can +% be used as it is or as a template. Three rules apply: % -% - **A label not in the map is dropped**, together with its whole score -% column. This is how you exclude compartments your model does not have -% (defaultCompartmentMap has no 'plastid' key, so plastid scores never reach -% a fungal model). Passing no map at all keeps every label untouched. -% - **Several labels may share one compartment id**, which merges their -% columns. The merged score for a gene is the *maximum* over the merged -% labels, not their sum, so a gene predicted 0.7 cytoplasm and 0.4 cytosol -% scores 0.7 for 'c'. Use this for synonyms and for deliberately collapsing -% distinct compartments your model does not separate (defaultCompartmentMap -% sends both 'vacuole' and 'lysosome' to 'v'). Column order follows the first -% appearance of each id. -% - **One label cannot be split across two compartment ids**: a containers.Map -% holds one value per key, and the GSS is what predictLocalization scores -% against, so a split has to be an explicit statement about the returned -% scores rather than a mapping rule. Duplicate the column afterwards, e.g. to -% let a gene predicted "golgi" compete for both 'g' and 'v': +% - A label that is not in the map is dropped, together with its whole score +% column. This excludes compartments that the model does not have +% (defaultCompartmentMap has no 'plastid' key, so plastid scores are dropped for a +% fungal model). Without a map, every label is kept unchanged. +% - Several labels may share one compartment id, which merges their +% columns. The merged score of a gene is the maximum over the merged labels, not +% their sum: a gene predicted 0.7 cytoplasm and 0.4 cytosol scores 0.7 for 'c'. +% Sharing an id merges synonyms and collapses compartments that the model does not +% separate (defaultCompartmentMap sends both 'vacuole' and 'lysosome' to 'v'). +% Column order follows the first appearance of each id. +% - One label cannot map to two compartment ids: a containers.Map holds one +% value per key. A split is made on the returned scores. Duplicating the +% column afterwards lets a gene predicted "golgi" compete for both 'g' and 'v': % % GSS = parseScores(file, 'compartmentMap', map); % g = strcmp(GSS.compartments, 'g'); @@ -72,14 +69,14 @@ % GSS.scores(:,end+1) = GSS.scores(:,g); % % The two columns are then independent: predictLocalization assigns each gene -% to exactly one compartment, so it picks whichever of 'g'/'v' keeps the -% network better connected. Halve the copied column instead of duplicating it -% if the evidence should count for less in the second compartment. +% to one compartment, so it picks whichever of 'g' and 'v' keeps the network +% better connected. Halving the copied column gives the evidence half the +% weight in the second compartment. % -% For 'uniprot' the keys do double duty: they are also the terms searched for -% in the "Subcellular location [CC]" free text, matched whole-word and case -% insensitively, so they must be UniProt's own noun forms. A term that is not a -% key is never looked for. +% For 'uniprot', the keys are also the terms searched for in the +% "Subcellular location [CC]" free text, matched as whole words and case +% insensitively. The keys must be the noun forms used by UniProt. A term that is +% not a key is not searched. % % Examples % -------- diff --git a/src/localization/predictLocalization.m b/src/localization/predictLocalization.m index 9920f27e..05c1ca12 100755 --- a/src/localization/predictLocalization.m +++ b/src/localization/predictLocalization.m @@ -3,71 +3,62 @@ defaultCompartment, varargin) % predictLocalization Assign reactions to compartments using localization predictors. % -% Tries to assign reactions to compartments in a manner that is in -% agreement with localization predictors while at the same time maintaining -% connectivity. +% Assigns reactions to compartments so that the assignment agrees with the localization +% predictors and the network stays connected. % % Parameters % ---------- % model : struct -% a model structure. If the model contains several compartments they -% will be merged. +% a model structure. If the model contains several compartments, they +% are merged. % GSS : struct % a gene scoring structure as from parseScores. % defaultCompartment : char % 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. +% defaultCompartment and the others. The compartment is usually the cytosol. It must +% be one of GSS.compartments. % % Name-Value Arguments % -------------------- % transportCost : double -% the cost for including a transport reaction. If this is 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. Negative costs encourage -% transport of the metabolite (default 0.5). +% the cost for including a transport reaction. A scalar applies the same cost to all +% metabolites; a vector must have the same dimension as model.mets. A negative cost +% favours transport of the metabolite (default 0.5). % maxTime : double -% maximum optimization time in minutes (default 15). +% maximum optimisation time in minutes (default 15). % plotResults : logical -% true if the results should be plotted during the optimization -% (default false). +% true to plot the results during the optimisation (default false). % % Returns % ------- % outModel : struct % the resulting model structure. % geneLocalization : struct -% structure with the genes and their resulting localization. +% structure with the genes and their resulting localisation. % transportStruct : struct -% structure with the transport reactions that had to be inferred and -% between which compartments. +% structure with the inferred transport reactions and the compartments between which +% they transport. % scores : struct -% structure that contains the total score history together with the -% score based on gene localization and the score based on included -% transport reactions. +% structure with the total score history, the score based on gene localisation and +% the score based on the included transport reactions. % removedRxns : cell -% cell array with the reaction ids that had to be removed to have a -% connected input model. +% cell array with the ids of the reactions removed to obtain a connected input model. % % Notes % ----- -% 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. +% The starting network must be connected when it is in one compartment. Unconnected +% reactions are removed and returned in removedRxns. If many reactions are removed, +% fillGaps can produce a more connected input model. The input model must not include +% exchange, demand or sink reactions; otherwise the function provides no 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). +% In the final model, every metabolite is produced in at least one reaction. Internal +% loops can still make the model non-functional. Transport reactions are included only +% 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. +% The score of a model is the sum of the scores of all genes in their assigned +% compartment minus the cost of all included transport reactions. A gene is assigned +% to one compartment, which limits the problem size. The problem is solved by simulated +% annealing. % % Examples % -------- diff --git a/src/manipulation/addExchangeRxns.m b/src/manipulation/addExchangeRxns.m index ddb6af8f..d23bfdfb 100755 --- a/src/manipulation/addExchangeRxns.m +++ b/src/manipulation/addExchangeRxns.m @@ -1,9 +1,11 @@ function [model, addedRxns]=addExchangeRxns(model,reactionType,varargin) % addExchangeRxns Add exchange reactions for some metabolites. % -% 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". +% The function builds the stoichiometric columns directly from the metabolite list, +% without the equation parsing of addRxns, which makes it faster for adding exchange +% reactions. New reactions are +% named "metName exchange (TYPE)" and have the ids "EXC_TYPE_METID", where TYPE is IN, +% OUT or BOTH according to reactionType. % % Parameters % ---------- @@ -14,15 +16,15 @@ % % - 'in' : input reactions % - 'out' : output reactions -% - 'both' : reversible input/output reactions. Positive direction +% - 'both' : reversible input and output reactions. The positive direction % corresponds to output % % Name-Value Arguments % -------------------- % mets : cell or logical or double -% 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 (default model.mets). +% a cell array of metabolite ids, a logical vector with one element per metabolite of +% the model, or a vector of metabolite indexes to add reactions for +% (default model.mets). % % Returns % ------- diff --git a/src/manipulation/addGenesRaven.m b/src/manipulation/addGenesRaven.m index cb00a033..a3e7ef37 100755 --- a/src/manipulation/addGenesRaven.m +++ b/src/manipulation/addGenesRaven.m @@ -1,8 +1,7 @@ function newModel=addGenesRaven(model,genesToAdd) % addGenesRaven Add genes to a model. % -% This function does not make extensive checks about MIRIAM formats, -% forbidden characters or such. +% The function checks neither MIRIAM formats nor forbidden characters in gene ids. % % Parameters % ---------- @@ -11,15 +10,15 @@ % genesToAdd : struct % the genes to add, which can have the following fields: % -% - genes : cell array with unique strings that identifies each gene. -% Only characters 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 +% - genes : cell array with unique strings that identify each gene. +% The characters allowed in SBML ids (mainly a-z, 0-9 and "_") are the +% valid ones, but the function does not check them; they matter only for +% export 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 +% - proteins : cell array of the protein names associated with each gene % (optional, default "") % % Returns diff --git a/src/manipulation/addMets.m b/src/manipulation/addMets.m index c8858de4..d9c01ec9 100755 --- a/src/manipulation/addMets.m +++ b/src/manipulation/addMets.m @@ -1,8 +1,7 @@ function newModel=addMets(model,metsToAdd,varargin) % addMets Add metabolites to a model. % -% This function does not make extensive checks about MIRIAM formats, -% forbidden characters or such. +% The function checks neither MIRIAM formats nor forbidden characters in metabolite ids. % % Parameters % ---------- @@ -11,13 +10,14 @@ % metsToAdd : struct % the metabolite structure, which 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 +% - mets : cell array with unique strings that identify each +% metabolite (optional, default: ids numbered with the prefix defined +% below) +% - metNames : cell array with the names of each metabolite (optional if +% mets is given, default: the ids) % - 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 +% Each entry must match model.comps. A single string, or a cell array +% with one entry, assigns all metabolites to 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 @@ -29,21 +29,19 @@ % default []) % - metCharges : metabolite charge (optional, default NaN) % - metDeltaG : Gibbs free energy of formation at biochemical standard -% condition in kJ/mole (optional, default NaN) +% condition in kJ/mol (optional, default NaN) % - metNotes : cell array with metabolite notes as strings (optional, % default "") % % Name-Value Arguments % -------------------- % copyInfo : logical -% 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 (default true). +% true to copy the available annotation from the metabolite with the same name in +% another compartment of the model (default true). % prefix : char -% 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 (default "m_"). +% prefix of the generated metabolite ids when metsToAdd.mets is not specified. If ids +% with the prefix exist in the model, the numbering starts at the highest +% existing number plus 1 (default "m_"). % % Returns % ------- @@ -56,8 +54,8 @@ % % Notes % ----- -% If multiple metabolites are added at once, the metMiriams cell array -% should be defined as (example with ChEBI and KEGG): +% When multiple metabolites are added at once, metMiriams is a cell array with one MIRIAM +% structure per metabolite (example with ChEBI and KEGG): % % metsToAdd.metMiriams{1} = struct("name",{{"chebi";"kegg.compound"}},... % "value",{{"CHEBI:18072";"C11821"}}); diff --git a/src/manipulation/addRxns.m b/src/manipulation/addRxns.m index 574c6985..91dbe531 100755 --- a/src/manipulation/addRxns.m +++ b/src/manipulation/addRxns.m @@ -1,12 +1,12 @@ function newModel=addRxns(model,rxnsToAdd,varargin) % addRxns Add reactions to a model. % -% This function does not make extensive checks about formatting of -% gene-reaction rules. +% The function checks that grRules has one entry per reaction and that every gene of +% a rule is in model.genes (an error otherwise, unless allowNewGenes is true). +% standardizeGrRules then writes the rules in the standard format. % -% When adding metabolites to a compartment where they previously do not -% exist, the function will copy any available information from the -% metabolite in another compartment. +% New metabolites receive the available annotation of the metabolite with the same name +% in another compartment, when one exists. % % Parameters % ---------- @@ -15,26 +15,26 @@ % rxnsToAdd : struct % the reaction structure, which can have the following fields: % -% - rxns : cell array with unique strings that identifies each reaction +% - rxns : cell array with unique strings that identify 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"} +% involved in each reaction as nested arrays, for example +% {{"met1","met2"},{"met1","met3","met4"}}. For a single added +% reaction, 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] +% corresponding stoichiometries as nested vectors, for example +% {[-1,+2],[-1,-1,+1]}. For a single added reaction, 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) +% model.annotation.defaultLB or -inf for reversible reactions and 0 +% for irreversible reactions when "equations" is used. When "mets" and +% "stoichCoeffs" are used, the default for all reactions is +% model.annotation.defaultLB or -inf) % - ub : vector with the upper bounds (optional, default -% model.annotations.defaultUB or inf) +% model.annotation.defaultUB or inf) % - c : vector with the objective function coefficients (optional, % default 0) % - eccodes : cell array with the EC-numbers for each reaction. Delimit @@ -42,18 +42,17 @@ % - 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 "") +% reaction. "(A and B) or (C)" means that the reaction is +% catalysed by a complex of A and B or by C on its own. All genes must +% be present in model.genes, unless allowNewGenes is true; addGenesRaven +% adds genes (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) +% kJ/mol (optional, default NaN) % - rxnReferences : cell array with reaction references (optional, % default "") % - rxnConfidenceScores : vector with reaction confidence scores @@ -62,36 +61,33 @@ % Name-Value Arguments % -------------------- % eqnType : double or char -% describes how the equation string should be interpreted (default 1). -% Accepts integer values 1/2/3 or the string aliases "id", "name", -% "name[comp]": +% the interpretation of the equation strings (default 1). The values are the +% integers 1, 2 and 3, or the string aliases "id", "name" and "name[comp]": % -% - 1 / "id" : the metabolites are matched to model.mets. New +% - 1 or "id" : the metabolites are matched to model.mets. New % metabolites (if allowed) are added to "compartment" -% - 2 / "name" : 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 / "name[comp]" : 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 +% - 2 or "name" : the metabolites are matched to model.metNames and all +% metabolites are assigned to "compartment". New metabolites get +% ids generated by generateNewIds with the prefix "m_" (or the +% prefix given in allowNewMets), numbered from the highest existing +% number with that prefix plus 1 +% - 3 or "name[comp]" : the metabolites are written as "metNames[comps]". +% Only compartments in model.comps are allowed. New metabolites get +% ids generated in the same way as for eqnType 2 % compartment : char -% the compartment the metabolites should be placed in when using -% eqnType=2. Must match model.comps (optional when eqnType=1 or -% eqnType=3). +% the compartment of the metabolites for eqnType=2 and of new metabolites for +% eqnType=1. Must match model.comps. Not used for eqnType=3. % allowNewMets : logical or char -% 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 -% (default false). +% true to allow the function to add new metabolites. A string also allows it and +% is used as the prefix of the new metabolite ids. The function calls addMets +% with copyInfo true, so a new metabolite takes the charge and deltaG from a +% metabolite with the same name in another compartment, and InChI, SMILES, +% formula and MIRIAM annotation from it when its own are empty. When the +% annotation of new metabolites is to be set explicitly, or when they are to be +% exchange (unconstrained) metabolites, adding them with addMets first gives +% that control (default false). % allowNewGenes : logical -% true if the function is allowed to add new genes (default false). +% true to allow the function to add new genes (default false). % % Returns % ------- diff --git a/src/manipulation/addRxnsGenesMets.m b/src/manipulation/addRxnsGenesMets.m index 5cb31994..79205543 100755 --- a/src/manipulation/addRxnsGenesMets.m +++ b/src/manipulation/addRxnsGenesMets.m @@ -1,24 +1,22 @@ function model=addRxnsGenesMets(model,sourceModel,rxns,varargin) % addRxnsGenesMets Copy reactions from a source model into another model. % -% Copies reactions from a source model to a new model, including (new) -% metabolites and genes. +% Copies reactions from a source model to a draft model, together with their new +% metabolites and genes. Reactions that are already in the draft model are skipped. % -% 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. +% The draft model and the source model must follow the same metabolite and compartment +% naming convention, because metabolites are matched only by metaboliteName[compartment]. +% The function can copy additional reactions from a source model to a draft model that +% getModelFromHomology created from the same models. % % Parameters % ---------- % model : struct -% draft model where reactions should be copied to. +% the draft model that receives the reactions. % sourceModel : struct -% model where reactions and metabolites are sourced from. +% the model that the reactions and metabolites are copied from. % rxns : cell or char -% reaction IDs (from source model). Can also be a string if only one -% reaction is added. +% reaction ids from the source model. A string adds one reaction. % % Name-Value Arguments % -------------------- @@ -28,22 +26,21 @@ % - false : no genes are annotated to the new reactions % - true : grRules are 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 +% - string or cell array : the grRules of the new reactions, as a string or a +% cell array, and new genes are added when required % rxnNote : cell or char -% strings explaining why reactions were copied to the model, to be -% included as newModel.rxnNotes. Can also be a string if the same -% rxnNotes should be added for each new reaction, or only one reaction -% is to be added (default "Added via addRxnsAndMets()"). +% strings that explain why the reactions were copied, stored in rxnNotes of the new +% reactions. A string applies the same note to every new reaction +% (default "Added via addRxnsGenesMets()"). % confidence : double -% integer specifying confidence score for all reactions, following +% integer confidence score for all new reactions, following % doi:10.1038/nprot.2009.203 (default 0): % % - 4 : biochemical data: direct evidence from enzyme assays % - 3 : genetic data: knockout/-in or overexpression analysis -% - 2 : physiological data: indirect evidence, e.g. secretion products +% - 2 : physiological data: indirect evidence, for example secretion products % or defined medium requirement; sequence data: genome annotation -% - 1 : modeling data: required for functional model, hypothetical +% - 1 : modelling data: required for a functional model, hypothetical % reaction % - 0 : no evidence % diff --git a/src/manipulation/addTransport.m b/src/manipulation/addTransport.m index d488ce27..2fbf2538 100755 --- a/src/manipulation/addTransport.m +++ b/src/manipulation/addTransport.m @@ -1,20 +1,22 @@ function [model, addedRxns]=addTransport(model,fromComp,toComps,varargin) % addTransport Add transport reactions between compartments. % -% 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. +% The function builds the stoichiometric columns directly from the metabolite names, +% without the equation parsing of addRxns, which makes it faster for adding transport +% reactions. New reaction names +% have the format "metaboliteName transport, fromCompName-toCompName", where the +% compartment names are the entries of model.compNames. New reaction ids are numbered +% sequentially with the prefix tr_ (tr_0001, tr_0002, ...). % % Parameters % ---------- % model : struct % a model structure. % fromComp : char -% the id of the compartment to transport from (should match -% model.comps). +% the id of the compartment to transport from. Must match one entry of model.comps. % toComps : cell -% compartment names to transport to (should match model.comps). +% the ids of the compartments to transport to. Each must match an entry of +% model.comps. % % Name-Value Arguments % -------------------- @@ -24,11 +26,11 @@ % isRev : logical % true if the transport reactions should be reversible (default true). % onlyToExisting : logical -% 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 (default true). +% true to add transport of a metabolite only if the metabolite exists in the target +% compartment. If false, the missing metabolites are first added with addMets +% (default true). % prefix : char -% prefix to reaction IDs (default "tr_"). +% prefix of the reaction ids (default "tr_"). % % Returns % ------- diff --git a/src/manipulation/changeGrRules.m b/src/manipulation/changeGrRules.m index 09db0fe2..55f792ef 100755 --- a/src/manipulation/changeGrRules.m +++ b/src/manipulation/changeGrRules.m @@ -1,5 +1,7 @@ function model = changeGrRules(model,rxns,grRules,varargin) -% changeGrRules Change multiple grRules at the same time. +% changeGrRules Change the grRules of multiple reactions. +% +% Genes in grRules that are not in the model are added to the model. % % Parameters % ---------- @@ -8,16 +10,15 @@ % rxns : char or cell % reaction IDs. % grRules : char or cell -% additional or replacement gene association. Should be written with -% ' and ' to indicate subunits, ' or ' to indicate isoenzymes, and -% brackets '()' to separate different instances. +% the replacement or additional gene association. ' and ' indicates subunits, ' or ' +% indicates isoenzymes, and brackets '()' separate different instances. A single +% rule applies to all reactions in rxns. % % Name-Value Arguments % -------------------- % replace : logical -% true if old gene association should be replaced with new association. -% False if new gene association should be concatenated to the old -% association (default true). +% true to replace the old gene association with the new association. False to +% combine them as "(old) or (new)" (default true). % % Returns % ------- diff --git a/src/manipulation/changeRxns.m b/src/manipulation/changeRxns.m index feca030e..dc1d4aa5 100755 --- a/src/manipulation/changeRxns.m +++ b/src/manipulation/changeRxns.m @@ -8,9 +8,8 @@ % rxns : cell % cell array with reaction ids. % equations : cell or struct -% cell array with equations. Alternatively, it can be a structure with -% the fields "mets" and "stoichCoeffs", in the same fashion as addRxns. -% E.g.: +% cell array with equations, or a structure with the fields "mets" and +% "stoichCoeffs" as in addRxns, for example: % % - equations.mets = {{"met1","met2"},{"met1","met3"}} % - equations.stoichCoeffs = {[-1,+2],[-1,+1]} @@ -18,30 +17,28 @@ % Name-Value Arguments % -------------------- % eqnType : double -% describes how the equation string should be interpreted (default 1): +% the interpretation of the equation strings (default 1): % % - 1 : the metabolites are matched to model.mets. New metabolites (if % allowed) are added to "compartment". % - 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. +% metabolites are assigned to "compartment". New metabolites get +% ids generated by generateNewIds with the prefix "m_", numbered from the +% highest existing number with that prefix plus 1. +% - 3 : the metabolites are written as "metNames[comps]". Only +% compartments in model.comps are allowed. New metabolites get ids +% generated in the same way as for eqnType 2. % compartment : char -% 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). +% the compartment of the metabolites for eqnType=2 and of new metabolites for +% eqnType=1. Must match model.comps. Not used for eqnType=3. % allowNewMets : logical -% 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 (default false). +% true to allow the function to add new metabolites. The function calls addMets +% with copyInfo true, so a new metabolite takes the charge and deltaG from a +% metabolite with the same name in another compartment, and InChI, SMILES, +% formula and MIRIAM annotation from it when its own are empty. When the +% annotation of new metabolites is to be set explicitly, or when they are to be +% exchange (unconstrained) metabolites, adding them with addMets first gives +% that control (default false). % % Returns % ------- @@ -54,16 +51,13 @@ % % Notes % ----- -% This function should be used with some care, since it does not care about -% bounds on the reactions. Changing an 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. +% The function keeps the bounds of the reactions. Changing an irreversible reaction to a +% reversible one, or the reverse, changes the model.rev field but not model.lb and +% model.ub, so the bounds still define the reversibility of the reaction. setParam +% changes the bounds. % -% When adding metabolites to a compartment where it previously does not -% exist, the function will copy any available information from the metabolite -% in another compartment. +% New metabolites receive the annotation of the metabolite with the same name in +% another compartment, when one exists (see allowNewMets). p=parseRAVENargs(varargin, {'eqnType',1; 'compartment',[]; 'allowNewMets',false}); eqnType=p.eqnType; diff --git a/src/manipulation/closeModel.m b/src/manipulation/closeModel.m index a83ecdff..5def2209 100755 --- a/src/manipulation/closeModel.m +++ b/src/manipulation/closeModel.m @@ -1,7 +1,13 @@ function closedModel=closeModel(model) -% closeModel Add boundary metabolites and their exchange reactions. +% closeModel Add boundary metabolites to exchange reactions. % -% Adds boundary metabolites and their participation in exchange reactions. +% Adds a compartment "b" (boundary) and a boundary metabolite in it for every reaction +% that has metabolites on one side only (exchange, sink and demand reactions). The +% boundary metabolite takes part in the reaction with the coefficient 1 or -1 and is +% marked as unconstrained in model.unconstrained; all other metabolites are marked as +% constrained. A reaction with one metabolite gets the boundary metabolite "_b" with +% the annotation of that metabolite; a reaction with several metabolites gets +% "_b" without annotation. % % Parameters % ---------- diff --git a/src/manipulation/contractModel.m b/src/manipulation/contractModel.m index d99108ed..a0e58b68 100755 --- a/src/manipulation/contractModel.m +++ b/src/manipulation/contractModel.m @@ -1,14 +1,14 @@ function [reducedModel, removedRxns, indexedDuplicateRxns]=contractModel(model,varargin) -% contractModel Contract a model by grouping all identical reactions. +% contractModel Contract a model by merging identical reactions. % -% This is what simplifyModel's deleteDuplicates option runs; it is not a -% separate implementation. 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. +% simplifyModel runs contractModel for its deleteDuplicates option. If the duplicated +% reactions have "_EXP_*" suffixes (where * is a digit), the model has passed through +% expandModel, and the function removes these suffixes. % -% Reactions are merged, so their gene associations are combined rather than -% discarded. Use findDuplicateRxns instead to see which reactions are -% duplicates without changing the model. +% The gene associations and EC numbers of merged reactions are combined. The merged +% reaction keeps the widest bounds and the largest objective coefficient, and a warning +% is given when the duplicates differ in these. findDuplicateRxns lists duplicate +% reactions without changing the model. % % Parameters % ---------- @@ -18,22 +18,22 @@ % Name-Value Arguments % -------------------- % distReverse : logical -% distinguish reactions with same metabolites but different reversibility -% as different reactions (default true). +% true to treat reactions with the same metabolites but different reversibility as +% different reactions (default true). % mets : char or cell -% string or cell array of strings with metabolite identifiers, whose -% involved reactions should be checked for duplication (by default all -% reactions are considered). This option is used by replaceMets. +% metabolite ids as a string or a cell array of strings; only the reactions that +% involve these metabolites are checked for duplication (default: all reactions). +% replaceMets uses this option. % % Returns % ------- % reducedModel : struct % a model structure without duplicate reactions. % removedRxns : cell -% cell array for the removed duplicate reactions. +% cell array with the ids of the removed duplicate reactions. % indexedDuplicateRxns : cell -% indexed cell array for the removed duplicate reactions (multiple values -% separated by semicolon). +% cell array with one entry per reaction of reducedModel, holding the ids of the +% duplicates removed into that reaction (multiple ids separated by semicolon). % % Examples % -------- @@ -41,8 +41,7 @@ % % Notes % ----- -% This code might not work for advanced grRules strings that involve nested -% expressions of "and" and "or". +% The function may not work for grRules strings with nested expressions of "and" and "or". p=parseRAVENargs(varargin, {'distReverse',true; 'mets',[]}); distReverse=p.distReverse; diff --git a/src/manipulation/convertToIrrev.m b/src/manipulation/convertToIrrev.m index faef2815..fe29a9ae 100755 --- a/src/manipulation/convertToIrrev.m +++ b/src/manipulation/convertToIrrev.m @@ -2,8 +2,8 @@ % convertToIrrev Convert a model to irreversible form. % % Reversible reactions are split into one forward and one reverse -% reaction. The reverse reactions are saved as 'rxnID_REV'. A warning is -% shown if some reaction identifiers already end with '_REV'. +% reaction. The reverse reactions are named 'rxnID_REV'. A warning is +% shown if some reaction ids already end with '_REV'. % % Parameters % ---------- @@ -13,7 +13,7 @@ % Name-Value Arguments % -------------------- % rxns : cell -% cell array with the reactions to split, if reversible (default +% cell array with the ids of the reactions to split, if reversible (default % model.rxns). % % Returns diff --git a/src/manipulation/copyToComps.m b/src/manipulation/copyToComps.m index 72a423f2..fdc81131 100755 --- a/src/manipulation/copyToComps.m +++ b/src/manipulation/copyToComps.m @@ -6,26 +6,22 @@ % model : struct % a model structure. % toComps : cell -% cell array of compartment ids. If there is no match to model.comps -% then it is added as a new compartment (see compNames and -% compOutside). +% cell array of compartment ids. An id that is not in model.comps is added as a +% new compartment (see compNames and compOutside). % % Name-Value Arguments % -------------------- % rxns : cell or logical or double -% 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 copy (default model.rxns). +% a cell array of reaction ids, a logical vector with one element per reaction of +% the model, or a vector of reaction indexes to copy (default model.rxns). % deleteOriginal : logical -% true if the original reactions should be removed, making it move the -% reactions instead (default false). +% true to remove the original reactions, which moves the reactions (default false). % compNames : cell -% cell array of compartment names. Used if new compartments should be -% added (default toComps). +% cell array of compartment names. Used when new compartments are added +% (default toComps). % compOutside : cell -% cell array of the id (as in comps) for the compartment surrounding -% each of the compartments. Used if new compartments should be added -% (default all {''}). +% cell array with the id (as in comps) of the compartment that surrounds each new +% compartment. Used when new compartments are added (default all {''}). % % Returns % ------- @@ -38,7 +34,7 @@ % % Notes % ----- -% New reactions and metabolites will be named as "id_toComps(i)". +% New reactions and metabolites have the ids "id_toComps(i)". p=parseRAVENargs(varargin, {'rxns',[]; 'deleteOriginal',false; 'compNames',[]; 'compOutside',[]}); rxns=p.rxns; diff --git a/src/manipulation/expandModel.m b/src/manipulation/expandModel.m index f3fb2498..441b273f 100755 --- a/src/manipulation/expandModel.m +++ b/src/manipulation/expandModel.m @@ -1,8 +1,8 @@ function [newModel, rxnToCheck]=expandModel(model) % expandModel Expand reactions that use several gene associations. % -% Each reaction that uses several gene associations is split into several -% reactions, each under the control of only one gene. +% Each reaction with several gene associations (isozymes) is split into one reaction per +% association. % % Parameters % ---------- @@ -12,12 +12,12 @@ % Returns % ------- % newModel : struct -% model structure with separate reactions for iso-enzymes, where the -% reaction ids are renamed as id_EXP_1, id_EXP_2, etc. +% model structure with separate reactions for isozymes. The ids of split reactions +% are id_EXP_1, id_EXP_2 and so on, numbered per isozyme. % rxnToCheck : cell -% cell array with original reaction identifiers for those whose grRule -% was not in disjunctive normal form, and so had to be expanded by -% distributivity, plus any whose grRule could not be parsed. +% cell array with the original ids of the reactions whose grRule is not in +% disjunctive normal form and was expanded by distributivity, and of the reactions +% whose grRule cannot be parsed and is left unchanged. % % Examples % -------- @@ -26,11 +26,11 @@ % Notes % ----- % The isozymes are the AND-clauses of the grRule in disjunctive normal form, -% so nested expressions are expanded correctly: "g1 and (g2 or g3)" yields -% "g1 and g2" and "g1 and g3". Reactions listed in rxnToCheck are expanded -% correctly too; they are reported only because a rule needing -% distributivity is often a sign that the GPR was not what its author -% intended. Use standardizeGrRules/findPotentialErrors to inspect them. +% so nested expressions are expanded: "g1 and (g2 or g3)" yields "g1 and g2" and +% "g1 and g3". Reactions listed in rxnToCheck because of distributivity are expanded in +% the same way; they are listed because a rule that needs distributivity can indicate +% that the GPR differs from what its author intended. standardizeGrRules and +% findPotentialErrors inspect them. %Work out the isozymes of every reaction up front. The number of copies is %the number of DNF clauses, which is not the number of ' or ' substrings: diff --git a/src/manipulation/findDuplicateRxns.m b/src/manipulation/findDuplicateRxns.m index be0a18ac..d0a3c928 100644 --- a/src/manipulation/findDuplicateRxns.m +++ b/src/manipulation/findDuplicateRxns.m @@ -1,21 +1,19 @@ function pairs = findDuplicateRxns(model, varargin) % findDuplicateRxns Find reactions that share identical stoichiometry. % -% The upstream version of yeast-GEM's findDuplicatedRxns. -% -% Only stoichiometry is compared — bounds, GPRs, and annotations are -% ignored. The default treats A→B and B→A as duplicates (typical curation -% use case: "find reactions that could be merged"). +% Only the stoichiometry is compared; bounds, GPRs and annotations are ignored. With +% the default ignoreDirection, A→B and B→A are duplicates. The pairs identify +% reactions that could be merged (contractModel merges duplicate reactions). % % Parameters % ---------- % model : struct -% RAVEN model struct. +% a model structure. % % Name-Value Arguments % -------------------- % ignoreDirection : logical -% treat A→B and B→A as duplicates (default true). +% true to treat A→B and B→A as duplicates (default true). % % Returns % ------- diff --git a/src/manipulation/findPotentialErrors.m b/src/manipulation/findPotentialErrors.m index 48960d9a..b4d8780e 100644 --- a/src/manipulation/findPotentialErrors.m +++ b/src/manipulation/findPotentialErrors.m @@ -1,11 +1,10 @@ function issues=findPotentialErrors(model) % findPotentialErrors Identify reactions with non-DNF GPR rules. % -% Detects grRules that are not in disjunctive normal form (DNF) — -% i.e. rules where an OR operator is nested inside an AND context. -% Standard RAVEN format requires DNF: groups of genes that must all be -% present together (enzyme complexes) are written as conjunctions, and -% the reaction is catalysed by at least one complex (disjunction of +% Detects grRules that are not in disjunctive normal form (DNF), that is, rules in +% which an OR operator is nested inside an AND context. The RAVEN format requires DNF: +% groups of genes that must all be present together (enzyme complexes) are written as +% conjunctions, and the reaction is catalysed by at least one complex (a disjunction of % conjunctions). % % Parameters @@ -16,23 +15,22 @@ % Returns % ------- % issues : struct -% struct array — one element per problematic reaction — with fields: +% struct array with one element per problematic reaction and the fields: % -% - index : double — 1-based index into model.rxns. -% - rxn : char — reaction ID. -% - grRule : char — the problematic grRule string. -% - reason : char — short explanation. +% - index : double, 1-based index into model.rxns. +% - rxn : char, reaction id. +% - grRule : char, the problematic grRule string. +% - reason : char, short explanation. % % Notes % ----- -% Detection walks the parse tree from parseGrRule rather than searching the -% raw string, so gene IDs that contain substrings such as "and" or "or" do -% not cause false positives or negatives. +% Detection walks the parse tree from parseGrRule, so gene ids that contain substrings +% such as "and" or "or" are not misread as operators. % % A rule is non-DNF when an AND operator has an OR anywhere beneath it. -% Bracketing alone never makes a rule non-DNF: "((G1 and G2) or G3)" and -% "(G1 or G2) or (G3 and G4)" are both fine. -% Use standardizeGrRules to attempt automatic repair. +% Bracketing alone does not make a rule non-DNF: "((G1 and G2) or G3)" and +% "(G1 or G2) or (G3 and G4)" are both in DNF. standardizeGrRules attempts an +% automatic repair. % % Rules that cannot be parsed at all are reported as issues too, with the % parser's message as the reason. diff --git a/src/manipulation/generateNewIds.m b/src/manipulation/generateNewIds.m index e6227fc0..ca6e157a 100755 --- a/src/manipulation/generateNewIds.m +++ b/src/manipulation/generateNewIds.m @@ -1,8 +1,8 @@ function newIds=generateNewIds(model,type,prefix,varargin) % generateNewIds Generate a list of new metabolite or reaction ids. % -% The ids are sequentially numbered with a defined prefix. The model is -% queried for the highest existing number of that type of id. Suffixes are +% The ids are numbered sequentially with a defined prefix. The highest existing number +% among the ids of that type with the prefix is read from the model. Suffixes are % read with str2double. A suffix counts as a number when the result is a % finite integer value below 2^52; text, Inf, NaN, fractions (r_2.5) and % numbers of 2^52 or more (r_1e300, r_1e400) do not count. @@ -14,17 +14,16 @@ % type : char % type of id, 'rxns' or 'mets'. % prefix : char -% prefix to be used in all ids, e.g. 's_' or 'r_'. +% prefix to be used in all ids, for example 's_' or 'r_'. % % Name-Value Arguments % -------------------- % quantity : double -% number of new ids that should be generated (default 1). +% number of new ids to generate (default 1). % numLength : double -% length of the numerical part of the 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 -% (default 4). +% length of the numerical part of the id; 4 gives ids like r_0001 and 6 gives ids like +% r_000001. If the prefix is used in the model, the length of the existing ids +% applies instead (default 4). % % Returns % ------- diff --git a/src/manipulation/mergeCompartments.m b/src/manipulation/mergeCompartments.m index ce4e80e9..42de7294 100755 --- a/src/manipulation/mergeCompartments.m +++ b/src/manipulation/mergeCompartments.m @@ -9,28 +9,29 @@ % Name-Value Arguments % -------------------- % keepUnconstrained : logical -% keep metabolites that are unconstrained in a "unconstrained" -% compartment. If these are merged the exchange reactions will most often -% be deleted (default false). +% true to keep the unconstrained metabolites in a separate compartment "b" +% (name "Unconstrained"). If they are merged, an exchange reaction between an +% unconstrained metabolite and a metabolite of the same name has no net +% stoichiometry after merging and is deleted (default false). % deleteRxnsWithOneMet : logical -% 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 (default -% false). +% true to delete reactions that have one metabolite after merging and had more +% before. Such reactions arise from reactions such as A[c] + B[c] => A[m]. Some +% models balance hydrogen around each membrane with reactions like this +% (default false). % distReverse : logical -% distinguish reactions with same metabolites but different reversibility -% as different reactions (default true). +% true to treat reactions with the same metabolites but different reversibility as +% different reactions (default true). % % Returns % ------- % model : struct -% a model with all reactions located to one compartment. +% a model with all reactions in one compartment. % deletedRxns : cell -% reactions that were deleted because of only having one metabolite -% after merging. +% the ids of the reactions deleted because they have one metabolite after merging. % duplicateRxns : cell -% identical reactions that occurred in different compartments and were -% deleted because they turned to be duplicated after merging. +% one entry per reaction of the returned model: '' when no duplicate was merged +% into it, otherwise the ids of the identical reactions from different +% compartments that were removed into it, joined by ";". % % Examples % -------- @@ -38,17 +39,16 @@ % % Notes % ----- -% 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. +% Merges all compartments into one compartment "s" (name "System"). The merged model +% can be used to test whether the network can synthesise all metabolites. % % Metabolites with the same name are merged into one. The merged metabolite % keeps the id and the other fields of one of the copies: the copy that is % already in compartment "s" if there is one, otherwise the copy whose id % comes first in character code order (for example ACCOA_c before ACCOA_m). % With keepUnconstrained only the copies that are not unconstrained are -% candidates. If the metabolite IDs reflect the compartment that they are in -% the IDs may no longer be representative. +% candidates. If the metabolite ids contain the compartment, the ids of merged +% metabolites can name a compartment that no longer exists. p=parseRAVENargs(varargin, {'keepUnconstrained',false; 'deleteRxnsWithOneMet',false; 'distReverse',true}); keepUnconstrained=p.keepUnconstrained; diff --git a/src/manipulation/mergeModels.m b/src/manipulation/mergeModels.m index 5ece7c76..411a161f 100755 --- a/src/manipulation/mergeModels.m +++ b/src/manipulation/mergeModels.m @@ -1,10 +1,11 @@ function model=mergeModels(models,varargin) % mergeModels Merge models into one model structure. % -% 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. +% Merges models into one model structure. Reactions are added without a check for +% duplicate reactions, so duplicates can appear. A reaction id that already exists in +% the merged model is renamed by appending "_" and the id of its source model. +% Metabolites are matched by name and compartment (metaboliteName[comp]) and genes by +% name. % % Parameters % ---------- @@ -14,23 +15,22 @@ % Name-Value Arguments % -------------------- % metParam : char -% string, metabolite name ("metNames") or ID ("mets") are used for -% matching (default "metNames"). +% the metabolite field used for matching: "metNames" (name and compartment) or +% "mets" (id) (default "metNames"). % supressWarnings : logical -% whether warnings should be supressed (default false). +% true to suppress warnings (default false). % copyToComps : logical -% internal flag used by copyToComps.m when it calls mergeModels to -% duplicate a model into a new compartment; leave at default when -% calling mergeModels directly (default false). +% internal flag set by copyToComps when it calls mergeModels to duplicate a model into +% a new compartment. Left at the default when calling mergeModels directly +% (default false). % % Returns % ------- % model : struct -% 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. +% the merged model structure. In addition to the usual fields, it has the fields +% rxnFrom, metFrom and geneFrom, which hold the id of the model that each reaction, +% metabolite and gene was taken from. If a model already has these fields, its +% entries are not modified. % % Examples % -------- diff --git a/src/manipulation/removeBadRxns.m b/src/manipulation/removeBadRxns.m index 17a891a8..382ebf70 100755 --- a/src/manipulation/removeBadRxns.m +++ b/src/manipulation/removeBadRxns.m @@ -1,87 +1,77 @@ function [newModel, removedRxns]=removeBadRxns(model,varargin) -% removeBadRxns Remove reactions that enable production/consumption from nothing. +% removeBadRxns Remove reactions that enable production or consumption from nothing. % -% Iteratively removes reactions which enable production/consumption of some -% metabolite without any uptake/excretion. +% Iteratively removes reactions that enable production or consumption of a metabolite +% without any uptake or excretion. % % Parameters % ---------- % model : struct -% a model structure. For the intended function, the model should not -% allow for any uptake/excretion. The easiest way to achieve this is to -% import the model using importModel("filename", false). +% a model structure. The model must not allow any uptake or excretion; the function +% warns about open exchange reactions when the model has no unconstrained field. +% importModel("filename", false) imports a model without uptake and excretion. % % Name-Value Arguments % -------------------- % rxnRules : double % which reactions may be removed (default 1): % -% - 1 : only remove reactions which are unbalanced -% - 2 : also remove reactions which could not be checked for mass -% balancing -% - 3 : all reactions can be removed +% - 1 : remove only unbalanced reactions +% - 2 : also remove reactions that could not be checked for mass +% balance +% - 3 : any reaction can be removed % ignoreMets : cell or logical or double -% 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 -% for metabolites to exclude from this analysis (default []). +% a cell array of metabolite ids, a logical vector with one element per metabolite +% of the model, or a vector of metabolite indexes to exclude from the analysis +% (default []). % isNames : logical -% 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 +% true if ignoreMets holds metabolite names (false: ids), which excludes the +% metabolites of that name in all compartments. Applies only if ignoreMets is a % cell array (default false). % balanceElements : cell -% a cell array with the elements for which to balance the reactions. May -% contain any combination of the elements defined in parseFormulas -% (default {"C";"P";"S";"N";"O"}). +% a cell array with the elements for which to balance the reactions, chosen from +% the elements defined in parseFormulas (default {"C";"P";"S";"N";"O"}). % refModel : struct -% 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" does not render the problem unfeasible. +% a reference model, intended as a copy of model with uptake and excretion allowed +% and some objectives (such as production of biomass) constrained to a non-zero +% flux. A supplied reference model triggers a warning that the feature is not +% supported, followed by an error. % ignoreIntBounds : logical -% 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 (default false). +% true to ignore internal bounds (including reversibility). Exchange reactions are +% not affected. Ignoring the bounds finds unbalanced solutions that the default +% constraints do not allow (default false). % printReport : logical -% true if a report should be printed (default false). +% true to print a report (default false). % seed : double -% seed for the random number generator, so that which reaction is -% removed among several equally-valid candidates is reproducible -% across runs (default: current rng state is left untouched). +% seed for the random number generator. A seed makes the choice among several +% candidate reactions reproducible (default: the current rng state is not +% changed). % % Returns % ------- % newModel : struct -% a model structure after the problematic reactions have been deleted. +% the model structure without the problematic reactions. % removedRxns : cell -% a cell array with the reactions that were removed. +% a cell array with the ids of the removed reactions. % % Notes % ----- -% The purpose of this function is to remove reactions which enable -% production/consumption of metabolites even when exchange reactions are not -% 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 or -% excretion. A common reason for this is when general compounds have -% different meaning in different reactions (as DNA has in these two -% reactions): +% The function removes reactions that enable production or consumption of metabolites +% when no exchange reaction is used. Models inferred automatically from databases can +% contain unbalanced reactions that allow net production or consumption of metabolites +% without any consumption or excretion. One cause is a general compound that has a +% 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 the case 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 -% findLeakMetabolite, checking if any of the involved reactions are -% elementally unbalanced, removing one of them, and then iterating until no -% metabolites can be produced/consumed. The 'produce' direction is run -% before the 'consume' one. +% Such reactions are elementally unbalanced, but the model can contain further +% unbalanced reactions that are not problematic. The function removes as few reactions +% as possible so that the model cannot produce or consume anything from nothing. It +% calls findLeakMetabolite repeatedly, selects at random one of the elementally +% unbalanced reactions that carry flux in the solution, removes it, and iterates until +% no metabolite can be produced or consumed. The 'produce' direction runs before the +% 'consume' direction. % % Examples % -------- diff --git a/src/manipulation/removeGenes.m b/src/manipulation/removeGenes.m index 00f3e30f..5c215b9b 100755 --- a/src/manipulation/removeGenes.m +++ b/src/manipulation/removeGenes.m @@ -12,13 +12,12 @@ % Name-Value Arguments % -------------------- % removeUnusedMets : logical -% remove metabolites that are no longer in use (default false). +% remove metabolites that no remaining reaction uses (default false). % removeBlockedRxns : logical -% remove reactions that get blocked after deleting the genes (default -% false). +% remove reactions that cannot carry flux after the genes are deleted. +% When false, the bounds of these reactions are set to 0 (default false). % standardizeRules : logical -% format gene rules to be compliant with the standard format (default -% true). +% write the gene rules in the standard format (default true). % % Returns % ------- @@ -29,9 +28,12 @@ % written in the standard format). Otherwise, besides genesToRemove, every % gene that no remaining reaction used before the removal is deleted as % well, also when it was not requested (for example a gene that no -% reaction uses). A gene whose only reaction is kept but blocked +% reaction uses). A gene that only occurs in a rule part removed with +% another gene stays, because the reaction used it before the removal +% (for example G3 in (G1 and G3) or G2 after removing G1). A gene also +% stays when its reaction remains, even if that reaction is blocked % (removeBlockedRxns false), such as the other subunit of a complex that -% lost one, stays. +% lost one. % % Examples % -------- diff --git a/src/manipulation/removeLowScoreGenes.m b/src/manipulation/removeLowScoreGenes.m index fb9b8c3d..160b81ef 100644 --- a/src/manipulation/removeLowScoreGenes.m +++ b/src/manipulation/removeLowScoreGenes.m @@ -1,10 +1,10 @@ function [newModel,remGenes] = removeLowScoreGenes(model,geneScores,varargin) -% removeLowScoreGenes Remove low-scoring genes from model. +% removeLowScoreGenes Remove low-score genes from a 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: +% Removes genes from a model based on their scores, a step used by the tINIT +% package. The function distinguishes isozymes from 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. @@ -14,17 +14,18 @@ % model : struct % model structure from which genes are to be removed. % geneScores : double -% 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. +% a vector of scores associated with the model genes, with the same +% dimensions as model.genes. Genes with a score of zero or above and genes +% without a score (NaN) remain in the rules; a gene that no rule uses +% afterwards is removed from model.genes. Genes with a negative score +% are removed from the rules when the conditions above allow it. % -% If all genes associated with a reaction have a negative score, then the -% least-negative gene will remain; if there is a tie, the gene listed first -% in the rule will be kept. +% If all genes associated with a reaction have a negative score, the +% least-negative gene remains; in a tie, the gene listed first in the rule +% is kept. % -% 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: +% A negative-scoring gene that is a subunit in a complex is not removed, +% but the entire complex may be removed. Example cases: % % - Original: G1 or (G2 and G3 and G4); Negative: G1, G2; New: G2 and G3 % and G4. @@ -36,21 +37,23 @@ % Name-Value Arguments % -------------------- % isozymeScoring : char -% method used to combine the scores of multiple isozymes; "min", "max", -% "median", or "average" (default "max"). +% method used to combine the scores of multiple isozymes: "min", "max", +% "median" or "average" (default "max"). % complexScoring : char % method used to combine the scores of enzyme complex subunits: "min", -% "max", "median", or "average" (default "min"). +% "max", "median" or "average" (default "min"). % % Returns % ------- % newModel : struct -% model with updated gene, grRules, and rxnGeneMat fields after attempting -% to remove negative-score genes. +% model with updated genes, grRules and rxnGeneMat fields, and with the +% gene-associated fields (geneShortNames, proteins, geneMiriams, geneFrom, +% geneComps) trimmed to the remaining genes. % remGenes : cell -% 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. +% the genes removed from model.genes: negative-score genes removed from every +% grRule and genes that no rule uses, whatever their score. Negative-score +% genes that are removed from some grRules but not all are not included in +% this list. p=parseRAVENargs(varargin, {'isozymeScoring',[]; 'complexScoring','min'}); diff --git a/src/manipulation/removeMets.m b/src/manipulation/removeMets.m index e494d3ac..e9fb6c3c 100755 --- a/src/manipulation/removeMets.m +++ b/src/manipulation/removeMets.m @@ -13,16 +13,17 @@ % Name-Value Arguments % -------------------- % isNames : logical -% 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 (default false). +% true if the supplied mets are metabolite names, false if they are IDs. +% All metabolites with a listed name are deleted, which removes +% metabolites in several compartments at once. Requires metsToRemove to +% be a cell array (default false). % removeUnusedRxns : logical -% remove reactions that are no longer in use (default false). +% remove reactions that involve no metabolite (default false). % removeUnusedGenes : logical -% remove genes that are no longer in use (default false). +% remove genes that no remaining reaction uses. Takes effect only when +% removeUnusedRxns is true (default false). % removeUnusedComps : logical -% remove compartments that are no longer in use (default false). +% remove compartments that contain no metabolite (default false). % % Returns % ------- diff --git a/src/manipulation/removeReactions.m b/src/manipulation/removeReactions.m index a19fbf9f..ae124b72 100755 --- a/src/manipulation/removeReactions.m +++ b/src/manipulation/removeReactions.m @@ -13,11 +13,12 @@ % Name-Value Arguments % -------------------- % removeUnusedMets : logical -% remove metabolites that are no longer in use (default false). +% remove metabolites that no remaining reaction uses (default false). % removeUnusedGenes : logical -% remove genes that are no longer in use (default false). +% remove genes that no remaining reaction uses (default false). % removeUnusedComps : logical -% remove compartments that are no longer in use (default false). +% remove compartments that contain no metabolite. Takes effect only when +% removeUnusedMets is true (default false). % % Returns % ------- diff --git a/src/manipulation/replaceMets.m b/src/manipulation/replaceMets.m index bcba7d0f..bb1198d2 100755 --- a/src/manipulation/replaceMets.m +++ b/src/manipulation/replaceMets.m @@ -1,20 +1,24 @@ function [model, removedRxns, idxDuplRxns]=replaceMets(model,metabolite,replacement,varargin) % replaceMets Replace a metabolite with another already in the model. % -% Replaces metabolite names and annotation with a 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 occurred. +% Replaces the name and annotation (formula, miriams, charge, deltaG, InChI +% and SMILES) of a metabolite with those of a replacement metabolite that is +% already in the model. If this results in duplicate metabolites, the S matrix +% is updated to use one of them. With identifiers true the replacement +% metabolite is kept; by name, the metabolite with the lowest index among those +% of the same name and compartment is kept. At the end, contractModel is run to remove +% duplicate reactions that this creates. % % Parameters % ---------- % model : struct % a model structure. % metabolite : char -% string with name of metabolite to be replaced. +% name of the metabolite to be replaced (its identifier if identifiers is +% true). % replacement : char -% string with name of replacement metabolite. +% name of the replacement metabolite (its identifier if identifiers is +% true). % % Name-Value Arguments % -------------------- @@ -22,17 +26,17 @@ % whether to print the ids of reactions that involve the replaced % metabolite (default false). % identifiers : logical -% true if 'metabolite' and 'replacement' refer to metabolite -% identifiers instead of metabolite names (default false). +% true if 'metabolite' and 'replacement' are metabolite identifiers, +% false if they are metabolite names (default false). % % Returns % ------- % model : struct -% model structure with selected metabolites replaced. +% model structure with the selected metabolites replaced. % removedRxns : cell -% identifiers of duplicate reactions that were removed. +% not assigned by the function; requesting this output raises an error. % idxDuplRxns : double -% index of removedRxns in original model. +% not assigned by the function; requesting this output raises an error. % % Examples % -------- @@ -41,9 +45,9 @@ % % Notes % ----- -% 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. +% The function applies to a model that contains both 'oxygen' and 'o2' as +% metabolite names. If 'oxygen' and 'o2' are identifiers, 'identifiers' is +% set to true. metabolite=char(metabolite); replacement=char(replacement); diff --git a/src/manipulation/reverseRxns.m b/src/manipulation/reverseRxns.m index efb5f6fc..8ab24ff3 100644 --- a/src/manipulation/reverseRxns.m +++ b/src/manipulation/reverseRxns.m @@ -1,10 +1,27 @@ function model=reverseRxns(model, rxns) -% reverseRxns -% Reverses the given reactions in place: negates their stoichiometry and -% objective coefficient, and swaps/negates their lower and upper bounds, -% so flux in the new positive direction is what was previously negative flux. -% model the model to change (input/output) -% rxns the rxns to reverse +% reverseRxns Reverse the direction of reactions in a model. +% +% Negates the stoichiometric coefficients and the objective coefficient of +% the reactions, and sets the lower bound to the negated upper bound and the +% upper bound to the negated lower bound. A flux in the new positive +% direction equals a flux in the original negative direction. Reaction IDs +% in rxns that are not in the model are ignored. +% +% Parameters +% ---------- +% model : struct +% a model structure. +% rxns : cell +% IDs of the reactions to reverse. +% +% Returns +% ------- +% model : struct +% an updated model structure. +% +% Examples +% -------- +% model = reverseRxns(model, rxns); rxnInd = find(ismember(model.rxns,rxns)); diff --git a/src/manipulation/setExchangeBounds.m b/src/manipulation/setExchangeBounds.m index a3a32b5a..dddc6d5c 100755 --- a/src/manipulation/setExchangeBounds.m +++ b/src/manipulation/setExchangeBounds.m @@ -10,31 +10,34 @@ % -------------------- % mets : cell or double % a cell array of metabolite names (case insensitive) or metabolite -% IDs, or a vector of metabolite indices (default all exchanged +% IDs, or a vector of indices in model.mets (default all exchanged % metabolites). % lb : double -% 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 (default model.annotation.defaultLB if it -% exists, otherwise -1000). +% lower bound of exchange flux. Either a vector of bounds corresponding +% to each of the provided metabolites, or a single value that is applied +% to all (default model.annotation.defaultLB if it exists, otherwise +% -1000). Without mets, only a single value is accepted. % ub : double -% 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 (default model.annotation.defaultUB if it -% exists, otherwise 1000). +% upper bound of exchange flux. Either a vector of bounds corresponding +% to each of the provided metabolites, or a single value that is applied +% to all (default model.annotation.defaultUB if it exists, otherwise +% 1000). Without mets, only a single value is accepted. % closeOthers : logical -% 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 (default true). +% close the exchange reactions of all exchanged metabolites that are not +% in the provided list. This prevents import of these metabolites and +% leaves their export unchanged. Set to false, with a warning, when the +% exchange reactions are not all written in the same direction +% (default true). % mediaOnly : logical % 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 reactions as exchange reactions. 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 (default false). +% are therefore ignored, although "getExchangeRxns" identifies such +% reactions as exchange reactions. The extracellular compartment is the +% one named "extracellular" in the "compNames" field (case insensitive). +% The "compNames" and "metComps" fields are required; an error is thrown +% if either is missing or if no compartment has this name +% (default false). % % Returns % ------- @@ -42,8 +45,8 @@ % a model structure with updated exchange flux bounds for the provided % set of metabolites. % unusedMets : cell -% metabolites provided by the user that were not used because they are -% not involved in any exchange reactions in the model. +% metabolites in mets that were not used because they are not involved +% in any of the considered exchange reactions in the model. % % Examples % -------- @@ -52,7 +55,7 @@ % % Notes % ----- -% Exchange reactions involving more than one metabolite will be ignored. +% Exchange reactions involving more than one metabolite are ignored. % handle input arguments diff --git a/src/manipulation/setParam.m b/src/manipulation/setParam.m index 07304c7e..df82afb4 100755 --- a/src/manipulation/setParam.m +++ b/src/manipulation/setParam.m @@ -6,23 +6,31 @@ % model : struct % a model structure. % paramType : char -% the type of parameter to set: +% the type of parameter to set. The value is matched case-insensitively, +% except for the reset of the other objective coefficients under "obj" +% (below): % % - "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). +% - "obj" : objective coefficient. The objective coefficients of all +% other reactions are set to 0 only when every element of paramType +% contains "obj" in lower case; with another capitalisation, or when +% paramType also holds other types, the other coefficients keep their +% values. +% - "rev" : reversibility (only changes the model.rev field, does not +% affect model.lb and model.ub). A non-zero value sets the reaction +% reversible. % - "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). +% - "unc" : unconstrained, sets the lower and upper bound to +% model.annotation.defaultLB and model.annotation.defaultUB if these +% are defined, otherwise to -1000 and 1000. % rxnList : cell or double % a cell array of reaction IDs or a vector with their corresponding -% indexes. +% indexes. IDs that are not in the model are ignored with a warning. % params : double -% a vector of the corresponding values. +% a vector of the corresponding values, or a single value that is +% applied to all reactions in rxnList. % var : double, optional % 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 diff --git a/src/manipulation/simplifyModel.m b/src/manipulation/simplifyModel.m index d579230d..464f4011 100755 --- a/src/manipulation/simplifyModel.m +++ b/src/manipulation/simplifyModel.m @@ -1,9 +1,8 @@ function [reducedModel, deletedReactions, deletedMetabolites]=simplifyModel(model,varargin) % simplifyModel Simplify a model by deleting reactions and 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. +% Deletes reactions and metabolites that cannot carry flux. The deleted +% reactions and metabolites identify different types of gaps. % % Parameters % ---------- @@ -13,27 +12,37 @@ % Name-Value Arguments % -------------------- % deleteUnconstrained : logical -% delete metabolites marked as unconstrained (default true). +% delete metabolites marked as unconstrained in model.unconstrained, and +% the compartments that are then left without metabolites (default true). % deleteDuplicates : logical -% delete all but one of duplicate reactions (default false). +% delete all but the first occurrence of duplicate reactions, as found by +% contractModel. Duplicate reactions have the same stoichiometry and +% reversibility. The kept reaction takes the minimum lower bound, the +% maximum upper bound and the maximum objective coefficient of the +% duplicates, with a warning when these differ (default false). % deleteZeroInterval : logical % delete reactions that are constrained to zero flux (default false). % deleteInaccessible : logical % delete dead end reactions (default false). % deleteMinMax : logical -% delete reactions that cannot carry a flux by trying to -% minimize/maximize the flux through that reaction. May be time -% consuming (default false). +% delete reactions that cannot carry a flux, as determined by haveFlux +% under the bounds of the model. The run time grows with the number of +% reactions, since haveFlux solves linear programs (default false). % groupLinear : logical -% group linearly dependent pathways (default false). +% group linearly dependent pathways. The grouped model is irreversible, +% and all gene information (genes, rxnGeneMat, grRules and the +% gene-associated fields) is deleted (default false). % constrainReversible : logical % 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 -% (default false). +% one direction, and if so constrain them to be irreversible. A reversible +% reaction that is constrained to one direction is not split into two +% reactions when groupLinear converts the model to irreversible, so the +% metabolites that it connects can meet the condition for grouping (one +% producing and one consuming reaction) (default false). % reservedRxns : cell -% cell array with reaction IDs that are not allowed to be removed -% (default none). +% cell array with reaction IDs that are not deleted by +% deleteZeroInterval, deleteInaccessible and deleteMinMax and not merged +% by groupLinear (default none). % suppressWarnings : logical % true if warnings should be suppressed (default false). % diff --git a/src/manipulation/sortIdentifiers.m b/src/manipulation/sortIdentifiers.m index 5a062a1e..acc0e833 100755 --- a/src/manipulation/sortIdentifiers.m +++ b/src/manipulation/sortIdentifiers.m @@ -1,8 +1,8 @@ function newModel = sortIdentifiers(model) % sortIdentifiers Sort model identifiers alphabetically. % -% Sort reactions, metabolites, genes and compartments alphabetically by -% their identifier. +% Sorts reactions, metabolites, genes (if the genes field exists) and +% compartments alphabetically by their identifier. % % Parameters % ---------- diff --git a/src/manipulation/sortModel.m b/src/manipulation/sortModel.m index 481924b5..010d669c 100755 --- a/src/manipulation/sortModel.m +++ b/src/manipulation/sortModel.m @@ -1,8 +1,9 @@ function model=sortModel(model,varargin) -% sortModel Standardize a model's internal ordering: can orient -% reversible reactions consistently; can also reorder metabolites within -% reaction equations and/or reactions within each subsystem, depending on -% which options are enabled. +% sortModel Sort the metabolites and reactions of a model. +% +% Depending on the options, the function sorts the metabolites by name and +% compartment, orients reversible reactions consistently, and reorders the +% reactions within each subsystem. % % Parameters % ---------- @@ -12,21 +13,25 @@ % Name-Value Arguments % -------------------- % sortReversible : logical -% sorts the reversible reactions so that the metabolite that is first -% in lexicographical order is a reactant (default false). +% orient each reversible reaction by changing the sign of its +% stoichiometric coefficients. The metabolite that is first in +% lexicographical order (metabolite name followed by compartment ID) +% becomes a reactant. Not applied when sortReactionOrder is true +% (default false). % sortMetName : logical -% sort the metabolite names in the equation, also uses compartment -% abbreviation (default false). +% sort the metabolites of the model by metabolite name followed by +% compartment ID (default false). % sortReactionOrder : logical -% sorts the reaction order within each subsystem so that reactions -% consuming some metabolite come after reactions producing it. This -% overrides the sortReversible option and reactions are sorted so that -% the production direction matches the consumption direction (default -% false). +% reorder the reactions within each subsystem, such that reactions +% consuming a metabolite come after reactions producing it. The order is +% found by a random local search that also changes the direction of +% reversible reactions to match production and consumption direction. +% Requires the subSystems field. Subsystems with fewer than 2 or more +% than 250 reactions are not reordered (default false). % seed : double % seed for the random number generator used by the sortReactionOrder -% local search, so its result is reproducible across runs (default: -% current rng state is left untouched). +% local search, which makes its result reproducible across runs +% (default: the current rng state is not changed). % % Returns % ------- diff --git a/src/manipulation/standardizeGrRules.m b/src/manipulation/standardizeGrRules.m index b95babdb..e59ddff4 100755 --- a/src/manipulation/standardizeGrRules.m +++ b/src/manipulation/standardizeGrRules.m @@ -1,13 +1,17 @@ function [grRules,rxnGeneMat,indexes2check] = standardizeGrRules(model,varargin) -% standardizeGrRules Standardize gene-reaction rules in a model. +% standardizeGrRules Standardise gene-reaction rules in a model. % -% The grRules are standardized according to the following: +% The grRules are standardised according to the following: % % - No overall containing brackets -% - Just enzyme complexes are enclosed into brackets -% - " and " and " or " strings are strictly set to lowercase +% - Only enzyme complexes are enclosed in brackets +% - " and " and " or " strings are set to lowercase % -% A rxnGeneMat matrix consistent with the standardized grRules is created. +% A rxnGeneMat matrix consistent with the standardised grRules is created. +% grRules that are not in disjunctive normal form (an "or" nested inside an +% "and") or that cannot be parsed are not standardised, apart from the +% removal of double spaces, spaces inside brackets and uppercase operators. +% The function throws an error if the model has no grRules field. % % Parameters % ---------- @@ -17,21 +21,21 @@ % Name-Value Arguments % -------------------- % embedded : logical -% if true, suppresses the console warning about potentially -% problematic grRules relationships, for use when this function is -% called inside of another RAVEN function that handles reporting -% itself (default false). +% if true, suppresses the console warning about grRules that are not in +% disjunctive normal form or cannot be parsed, for use when this +% function is called inside another RAVEN function that handles +% reporting itself (default false). % % Returns % ------- % grRules : cell -% [nRxns x 1] cell array with the standardized grRules. +% [nRxns x 1] cell array with the standardised grRules. % rxnGeneMat : double -% [nRxns x nGenes] sparse matrix consistent with the standardized +% [nRxns x nGenes] sparse matrix consistent with the standardised % grRules. % indexes2check : double -% indices of the grRules with potentially problematic relationships -% that should be checked manually. +% indices of the grRules that are not in disjunctive normal form or +% cannot be parsed. These grRules need a manual check. % % Examples % -------- diff --git a/src/queries/buildEquation.m b/src/queries/buildEquation.m index 6c93679e..9bb5951c 100755 --- a/src/queries/buildEquation.m +++ b/src/queries/buildEquation.m @@ -6,14 +6,17 @@ % mets : cell % metabolites involved in the reaction. % stoichCoeffs : double -% vector with corresponding stoichiometric coeffs. +% vector with the corresponding stoichiometric coefficients, of the same +% length as mets. Negative coefficients are reactants and positive +% coefficients are products. % isrev : logical -% indicates if the reaction is reversible or not. +% true if the reaction is reversible (written with "<=>"), false if it +% is irreversible (written with "=>"). % % Returns % ------- % equationString : char -% equation as a string. +% the equation as a string. % % Examples % -------- diff --git a/src/queries/checkModelStruct.m b/src/queries/checkModelStruct.m index 59b11149..38e2f4b1 100755 --- a/src/queries/checkModelStruct.m +++ b/src/queries/checkModelStruct.m @@ -1,5 +1,5 @@ function issues=checkModelStruct(model,varargin) -% checkModelStruct Perform a number of checks to ensure a model structure is ok. +% checkModelStruct Check a model structure for errors and inconsistencies. % % Parameters % ---------- @@ -10,32 +10,33 @@ % -------------------- % throwErrors : logical % true if structural problems (wrong types, missing required fields, -% duplicate IDs, etc.) should throw an error. Advisory notices such as +% duplicate IDs and other problems of structure) should throw an error. Advisory notices such as % unused elements and bound inconsistencies are always reported as % warnings regardless of this flag (default true). % trimWarnings : logical -% true if only a maximum of 10 items should be displayed in a given -% warning or error (default true). +% true if a given warning or error lists at most 10 items, the last of +% which reports the number of remaining items (default true). % % Returns % ------- % issues : struct -% When called with an output argument, returns a struct array with one -% element per finding (does not throw or print) instead of the default -% print/throw behaviour. Fields: +% When called with an output argument, the function returns a struct +% array with one element per finding and neither throws nor prints. The +% default behaviour without an output argument is to print warnings and +% throw errors. Fields: % -% - category : char — type of issue: "missing_field", "wrong_type", -% "empty_id", "duplicate", "invalid_id", "invalid_bounds", -% "unused", "objective", "gpr", "invalid_formula", -% "cross_reference", or "other". -% - target : char — the specific item involved (field name, reaction -% ID, metabolite ID, etc.), or "" when not applicable. -% - message : char — the full diagnostic text. +% - category (char): type of issue, one of "missing_field", +% "wrong_type", "empty_id", "duplicate", "invalid_id", +% "invalid_bounds", "unused", "objective", "gpr", "invalid_formula", +% "cross_reference" or "other". +% - target (char): the item involved (field name, reaction ID, +% metabolite ID or another item), or "" when not applicable. +% - message (char): the full diagnostic text. % % Notes % ----- -% This is typically performed after importing or constructing a model, or -% before attempting to export a model to SBML format. +% The check is intended for use after importing or constructing a model and +% before exporting a model to SBML format. % % Examples % -------- diff --git a/src/queries/constructEquations.m b/src/queries/constructEquations.m index de3368a5..23f5d3ee 100755 --- a/src/queries/constructEquations.m +++ b/src/queries/constructEquations.m @@ -18,21 +18,23 @@ % sort reversible reactions so that the metabolite that is first in the % lexicographic order is a reactant (default false). % sortMetNames : logical -% sort the metabolite names in the equation. Uses compartment even if -% useComps is false (default false). +% sort the metabolite names in the equation. The compartment is included +% in the sorting even if useComps is false (default false). % useMetID : logical -% use metabolite ID in generated equations (default false). +% use metabolite ID in generated equations. Cannot be true together with +% useFormula (default false). % useFormula : logical -% use metabolite formula in generated equations (default false). +% use metabolite formula in generated equations. Cannot be true together +% with useMetID (default false). % useRevField : logical -% use the model.rev field to indicate reaction reversibility, -% alternatively this is determined from the model.ub and model.lb fields +% use the model.rev field to indicate reaction reversibility. When +% false, a reaction is reversible if model.lb < 0 and model.ub > 0 % (default true). % % Returns % ------- % equationStrings : cell -% a cell array with equations. +% a cell array with the equation of each reaction. % % Examples % -------- @@ -41,9 +43,9 @@ % % Notes % ----- -% 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. +% If useRevField is false, the reactions have to be written in their forward +% direction (for example ub = 1000 and lb = -1000 or 0) for the reversibility +% to be determined correctly. p=parseRAVENargs(varargin, {'rxns',[]; 'useComps',true; 'sortRevRxns',false; 'sortMetNames',false; 'useMetID',false; 'useFormula',false; 'useRevField',true}); rxns=p.rxns; diff --git a/src/queries/constructS.m b/src/queries/constructS.m index 03b03162..f837a4ed 100755 --- a/src/queries/constructS.m +++ b/src/queries/constructS.m @@ -4,32 +4,34 @@ % Parameters % ---------- % equations : cell -% cell array of equations on the form "A + 2 B <=> 3 C", where <=> +% cell array of equations in the form "A + 2 B <=> 3 C", where <=> % indicates reversible and => irreversible reactions. % % Name-Value Arguments % -------------------- % mets : cell % cell array of metabolites. All metabolites in the equations must be -% present in the list (default generated from the equations). +% present in the list, otherwise an error is thrown (default generated +% from the equations). % rxns : cell -% cell array of reaction ids. This is only used for printing reaction ids -% instead of equations in warnings/errors (default []). +% cell array of reaction ids. Used to print reaction ids in error +% messages in place of equations (default []). % % Returns % ------- % S : double % the resulting stoichiometric matrix. % mets : cell -% cell array with metabolites that corresponds to the order in the S +% cell array with the metabolites in the order of the rows of the S % matrix. % badRxns : logical -% 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. +% logical vector with true for the reactions in which one or more +% metabolites occur more than once, for example as both substrate and +% product. An example is the phosphotransferase reaction +% ATP + ADP <=> ADP + ATP, which gives an empty column in the +% stoichiometric matrix. % reversible : logical -% boolean vector with true if the equation is reversible. +% logical vector with true if the equation is reversible. % % Examples % -------- diff --git a/src/queries/getAllRxnsFromGenes.m b/src/queries/getAllRxnsFromGenes.m index a1710c92..046e7b31 100755 --- a/src/queries/getAllRxnsFromGenes.m +++ b/src/queries/getAllRxnsFromGenes.m @@ -2,7 +2,8 @@ % getAllRxnsFromGenes Find all reactions annotated by the genes of a set. % % Given a list of reactions, this function finds the associated genes in -% the model and returns all reactions that are annotated by these genes. +% the model and returns all reactions that are annotated by these genes, +% including the given reactions. % % Parameters % ---------- @@ -15,9 +16,9 @@ % Returns % ------- % allRxns : cell or logical or double -% 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. +% the reactions in the same format as rxns: a cell array of IDs (unique +% and sorted), a logical vector with the same number of elements as +% reactions in the model, or a vector of indexes (unique and sorted). % % Examples % -------- diff --git a/src/queries/getElementalBalance.m b/src/queries/getElementalBalance.m index f015984c..d13d0593 100755 --- a/src/queries/getElementalBalance.m +++ b/src/queries/getElementalBalance.m @@ -1,7 +1,10 @@ function balanceStructure=getElementalBalance(model,varargin) % getElementalBalance Check whether the reactions of a model are balanced. % -% Checks a model to see if the reactions are elementally balanced. +% Checks whether the reactions are elementally balanced, using the +% metFormulas field or, when that is absent, the inchis field. An error is +% thrown if the model has neither field. The charge balance is reported +% separately. % % Parameters % ---------- @@ -13,13 +16,13 @@ % rxns : cell or logical or double % 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. Only these reactions will be checked (default model.rxns). +% indexes. Only these reactions are checked (default model.rxns). % printUnbalanced : logical -% print warnings about the reactions that were unbalanced +% print warnings about the reactions that are unbalanced % (default false). % printUnparsable : logical -% print warnings about the reactions that cannot be parsed -% (default false). +% print warnings about the reactions that cannot be balanced because of +% missing information or parsing errors (default false). % % Returns % ------- @@ -28,12 +31,13 @@ % % - balanceStatus : 1 if the reaction is balanced, 0 if it is % unbalanced, -1 if it could not be balanced due to missing -% information, -2 if it could not be balanced due to an error. -% Elemental only; charge is reported separately below +% information (including a reaction without metabolites), -2 if it +% could not be balanced because a formula could not be parsed. +% Elemental only; charge is reported in chargeStatus % - chargeStatus : 1 if the reaction is charge balanced, 0 if it is -% not, -1 if any participating metabolite has no charge (or the -% model has no metCharges field), in which case the charge balance -% is unknown rather than zero +% not, -1 if any participating metabolite has no charge, the reaction +% has no metabolites, or the model has no metCharges field; the +% charge balance is then unknown % - chargeResidual : the sum of charges over the reaction, NaN where % chargeStatus is -1 % - elements : struct with fields abbrevs (cell array with diff --git a/src/queries/getExchangeRxns.m b/src/queries/getExchangeRxns.m index aa86b753..b6c35575 100755 --- a/src/queries/getExchangeRxns.m +++ b/src/queries/getExchangeRxns.m @@ -2,7 +2,9 @@ % getExchangeRxns Retrieve the exchange reactions from a model. % % Exchange reactions are identified by having either no substrates or no -% products. +% products. In a model with metabolites marked in the unconstrained field, +% the exchange reactions are the reactions that involve such a metabolite +% (as substrate for 'in', as product for 'out'). % % Parameters % ---------- @@ -39,8 +41,9 @@ % exchangeRxnsIndexes : double % vector with the indexes of the exchange reactions. % exchangedMets : double -% vector with the metabolite index for each exchange reaction (one -% metabolite per exchange reaction). Only computed when requested. +% vector with the index of the first metabolite with a non-zero +% coefficient in each exchange reaction (0 if there is none). Only +% computed when requested. % % Notes % ----- diff --git a/src/queries/getGenesFromGrRules.m b/src/queries/getGenesFromGrRules.m index 5b561ec5..945addb0 100755 --- a/src/queries/getGenesFromGrRules.m +++ b/src/queries/getGenesFromGrRules.m @@ -5,25 +5,25 @@ % ---------- % grRules : cell % a cell array of model grRules, from which a list of genes is 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. +% extracted. Boolean operators can be text ("and", "or") or symbolic +% ("&", "|"), with a space between operators and gene names or IDs. % % Name-Value Arguments % -------------------- % originalGenes : cell % the original gene list from the model. If supplied, the genes parsed -% from grRules must match it exactly (as a set), an error is thrown -% otherwise, and the returned genes list follows originalGenes' order. +% from grRules must match it as a set, otherwise an error is thrown, and +% the returned genes list follows the order of originalGenes. % % Returns % ------- % genes : cell -% a unique list of all gene IDs that appear in grRules. +% a unique, sorted list of all gene IDs that appear in grRules (in the +% order of originalGenes when supplied). % rxnGeneMat : double -% (optional) a binary matrix indicating which genes participate in each -% reaction, where rows correspond to reactions (entries in grRules) and -% columns correspond to genes. +% (optional) a sparse binary matrix indicating which genes participate in +% each reaction, where rows correspond to reactions (entries in grRules) +% and columns correspond to genes. Only computed when requested. % % Examples % -------- diff --git a/src/queries/getIndexes.m b/src/queries/getIndexes.m index 1c64efa5..61840547 100755 --- a/src/queries/getIndexes.m +++ b/src/queries/getIndexes.m @@ -7,15 +7,19 @@ % a model structure. % objects : cell or logical or double % 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. +% elements as objects of the given type in the model, or a vector of +% indexes. An error is raised if an ID is not found in the model, except +% for type 'metnames', where a name that is not found gives an empty +% index vector. % type : char -% 'rxns', 'mets', or 'genes' depending on what to retrieve. 'metnames' -% queries metabolite names, while 'metcomps' allows providing specific +% 'rxns', 'mets' or 'genes', depending on what to retrieve. 'metnames' +% queries metabolite names and returns, for each name, the indexes of all +% metabolites with that name. 'metcomps' queries specific % metabolites and their compartments in the format metaboliteName[comp]. % An error is raised if such a name matches no metabolite, or more than % one. -% If a model.ec structure exists (GECKO 3), then also 'ecenzymes', -% 'ecrxns' and 'ecgenes' are allowed. +% If a model.ec structure exists (GECKO 3), 'ecenzymes', 'ecrxns' and +% 'ecgenes' are also allowed. % % Name-Value Arguments % -------------------- @@ -26,8 +30,8 @@ % Returns % ------- % indexes : logical or double -% can be a logical array or a double array depending on the value of -% returnLogical. +% a logical array if returnLogical is true, otherwise a double array. For +% 'metnames' with several names, a cell array of double vectors. % % Notes % ----- diff --git a/src/queries/getRxnsInComp.m b/src/queries/getRxnsInComp.m index ce980a90..a4ac4f63 100755 --- a/src/queries/getRxnsInComp.m +++ b/src/queries/getRxnsInComp.m @@ -6,20 +6,21 @@ % model : struct % a model structure. % comp : char -% string with the compartment id. +% the compartment id (case insensitive). An error is thrown if the id +% does not match exactly one compartment. % % Name-Value Arguments % -------------------- % includePartial : logical -% true if reactions with metabolites in several compartments (normally -% transport reactions) should be included (default false). +% true if reactions with metabolites in several compartments (for +% example transport reactions) are included (default false). % % Returns % ------- % I : double -% boolean vector of the reactions. +% indexes of the reactions in the compartment. % rxnNames : cell -% the names of the reactions. +% the names of these reactions. % % Examples % -------- diff --git a/src/queries/getTransportRxns.m b/src/queries/getTransportRxns.m index a1d989f7..e7678af0 100755 --- a/src/queries/getTransportRxns.m +++ b/src/queries/getTransportRxns.m @@ -19,7 +19,8 @@ % Notes % ----- % Transport reactions are defined as reactions involving (at least) one -% metabolite name in more than one compartment. +% metabolite name in more than one compartment. Exchange reactions, as +% identified by getExchangeRxns, are not transport reactions. transportRxns=false(numel(model.rxns),1); diff --git a/src/queries/modelSummary.m b/src/queries/modelSummary.m index a8fa03c9..0a26f6ed 100644 --- a/src/queries/modelSummary.m +++ b/src/queries/modelSummary.m @@ -1,9 +1,9 @@ function modelSummary(model, varargin) -% modelSummary Print a concise overview of a RAVEN model and its flux state. +% modelSummary Print an overview of a RAVEN model and its flux state. % -% Prints model dimensions, the objective function, and — when a flux vector -% is supplied — the objective value plus all net exchange fluxes partitioned -% into uptake and secretion. +% Prints the model dimensions and the objective function. When a flux vector +% is supplied, it also prints the objective value and the net exchange +% fluxes, partitioned into uptake and secretion. % % Parameters % ---------- @@ -13,12 +13,14 @@ function modelSummary(model, varargin) % Name-Value Arguments % -------------------- % fluxes : double -% flux vector (length = numel(model.rxns)). When provided, shows the -% objective value and the exchange-flux summary (default []). +% flux vector with numel(model.rxns) elements. When provided, the +% objective value and the exchange-flux summary are printed +% (default []). % cutoff : double % minimum absolute net exchange flux to include (default 1e-8). % nMax : double -% maximum exchange reactions displayed per direction (default 20). +% maximum number of exchange reactions displayed per direction, in +% descending order of absolute flux (default 20). % % Examples % -------- @@ -28,12 +30,12 @@ function modelSummary(model, varargin) % % See also % -------- -% printModelStats : the structural view instead. It breaks the counts down per -% compartment, adds unique EC codes, biochemically unique reactions and -% unique metabolite names, and optionally reports dead ends and elemental -% imbalances. It knows nothing about fluxes or the objective. -% printFluxes : the exchange fluxes on their own, with more control over -% formatting and filtering than the summary here offers. +% printModelStats : model statistics. It breaks the counts down per +% compartment, adds the number of unique EC codes, biochemically unique +% reactions and unique metabolite names, and optionally reports dead ends +% and elemental imbalances. It prints no fluxes or objective. +% printFluxes : prints the fluxes of reactions with options for filtering +% and for the format of the output. p = parseRAVENargs(varargin, {'fluxes',[]; 'cutoff',1e-8; 'nMax',20}); fluxes = p.fluxes; diff --git a/src/queries/parseFormulas.m b/src/queries/parseFormulas.m index c827e387..d394496a 100755 --- a/src/queries/parseFormulas.m +++ b/src/queries/parseFormulas.m @@ -9,15 +9,16 @@ % Name-Value Arguments % -------------------- % noPolymers : logical -% 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" (default false). +% treat polymers as a single unit: everything between (...)n is counted +% with n equal to one. Only one set of parentheses is allowed. If this is +% false, polymers get exitFlag -1, "Could not parse formula" +% (default false). % isInchi : logical % true if the formulas are in the InChI format (default false). % ignoreRX : logical -% ignore R-groups and bound protein. This can be useful since they are -% often used only as intermediates (default false). +% set the atomic weight of R-groups and bound protein to 0, which allows +% MW to be calculated for formulas that contain them. The atoms are still +% counted in useMat (default false). % % Returns % ------- @@ -26,6 +27,8 @@ % % - abbrevs : cell array with abbreviations for all used elements % - names : cell array with the names for all used elements +% +% Elements that occur in none of the formulas are not included. % useMat : double % MxN matrix with the number of atoms for each formula (M) and each % element (N). @@ -36,10 +39,11 @@ % - 0 : no formula found % - -1 : could not parse formula % MW : double -% predicted molecular weight (g/mol). This is only returned for -% formulas which can be successfully parsed, and its calculation -% doesn't affect the exitFlag variable. NaN is returned if the weight -% couldn't be calculated. +% predicted molecular weight (g/mol). This is only calculated when +% requested, and only for formulas which can be successfully parsed; +% its calculation does not affect the exitFlag variable. NaN is returned +% if the weight cannot be calculated, for example for formulas that +% contain R-groups or bound protein while ignoreRX is false. % % Examples % -------- diff --git a/src/queries/parseRxnEqu.m b/src/queries/parseRxnEqu.m index a1ecb934..219ce0ff 100755 --- a/src/queries/parseRxnEqu.m +++ b/src/queries/parseRxnEqu.m @@ -9,7 +9,7 @@ % Returns % ------- % metabolites : cell -% a cell array with the involved metabolites. +% a unique, sorted cell array with the involved metabolites. % % Examples % -------- @@ -17,12 +17,13 @@ % % Notes % ----- -% The equations should be written like: +% The equations are written like: % -% 1 A + 3 B (=> or <=>) 5C + 2 D +% 1 A + 3 B (=> or <=>) 5 C + 2 D % -% If the equation is expressed as for example '... + (n-1) starch' then -% '(n-1) starch' will be interpreted as one metabolite. +% with a space around each arrow and plus sign and between a coefficient and +% its metabolite name. If the equation is expressed as for example +% '... + (n-1) starch', '(n-1) starch' is interpreted as one metabolite. if ~iscell(equations) equations={equations}; diff --git a/src/queries/printFluxes.m b/src/queries/printFluxes.m index c592d499..fde3fb9a 100755 --- a/src/queries/printFluxes.m +++ b/src/queries/printFluxes.m @@ -6,7 +6,8 @@ function printFluxes(model, fluxes, varargin) % model : struct % a model structure. % fluxes : double -% a vector with fluxes. +% a vector with fluxes, or a matrix with one row per reaction and one +% column per flux distribution. % % Name-Value Arguments % -------------------- @@ -22,8 +23,8 @@ function printFluxes(model, fluxes, varargin) % a string that specifies the output of each reaction (default % "%rxnID\t(%rxnName):\t%flux\n"). % metaboliteList : cell -% cell array of metabolite names. Only reactions involving any of these -% metabolites will be printed. +% cell array of metabolite names (case insensitive). Only reactions +% involving any of these metabolites are printed. % % Notes % ----- @@ -36,12 +37,12 @@ function printFluxes(model, fluxes, varargin) % - %obj : objective coefficient % - %eqn : equation % - %flux : flux -% - %element : equation using the metabolite formulas rather than metabolite +% - %element : equation using the metabolite formulas in place of 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 +% - %lumped : equation where the elemental compositions of the left-hand and +% right-hand sides are lumped % % Examples % -------- diff --git a/src/queries/printModelStats.m b/src/queries/printModelStats.m index c0c8f4ed..595edf9c 100755 --- a/src/queries/printModelStats.m +++ b/src/queries/printModelStats.m @@ -1,5 +1,10 @@ function printModelStats(model, varargin) -% printModelStats Print some statistics about a model to the screen. +% printModelStats Print statistics about a model to the screen. +% +% Prints the numbers of genes, reactions and metabolites in total and per +% compartment, the number of unique EC codes (if the eccodes field exists), +% the number of biochemically unique reactions and the number of unique +% metabolite names. % % Parameters % ---------- @@ -9,11 +14,12 @@ function printModelStats(model, varargin) % Name-Value Arguments % -------------------- % printModelIssues : logical -% true if information about unconnected reactions/metabolites and -% elemental balancing should be printed (default false). +% true if information about unused metabolites, empty reactions, +% dead-end reactions and metabolites, and elemental balancing is printed +% (default false). % printDetails : logical -% true if detailed information should be printed about model issues. -% Only used if printModelIssues is true (default true). +% true if the individual metabolites and reactions of each issue are +% listed. Used only if printModelIssues is true (default true). % % Examples % -------- @@ -21,9 +27,9 @@ function printModelStats(model, varargin) % % See also % -------- -% modelSummary : the shorter view, without the per-compartment breakdown, but -% adding the objective function and - given a flux vector - the objective -% value and the net uptake and secretion. +% modelSummary : prints the model dimensions without the per-compartment +% breakdown, the objective function and, given a flux vector, the +% objective value and the net uptake and secretion. p=parseRAVENargs(varargin, {'printModelIssues',false; 'printDetails',true}); printModelIssues=p.printModelIssues; diff --git a/src/reconstruction/guessComposition.m b/src/reconstruction/guessComposition.m index a2ccb2c6..2eeaf741 100755 --- a/src/reconstruction/guessComposition.m +++ b/src/reconstruction/guessComposition.m @@ -1,8 +1,8 @@ function [model, guessedFor, couldNotGuess]=guessComposition(model, varargin) % guessComposition Guess the composition of metabolites without one. % -% Attempts to guess the composition of metabolites without information about -% elemental composition. +% Derives the elemental composition of metabolites without a formula from the +% reactions they participate in, and writes it to the metFormulas field. % % Parameters % ---------- @@ -12,17 +12,18 @@ % Name-Value Arguments % -------------------- % printResults : logical -% true if the output should be printed (default true). +% true if the predicted compositions are printed (default true). % % Returns % ------- % model : struct -% a model structure with information about elemental composition added. -% guessedFor : double -% indexes for the metabolites for which a composition could be guessed. -% couldNotGuess : double -% indexes for the metabolites for which no composition could be -% assigned. +% a model structure with the predicted formulas added to metFormulas, for +% all metabolites that share the metabolite name. +% guessedFor : cell +% metabolite names for which a composition could be guessed. +% couldNotGuess : cell +% metabolite names, among those without a formula in the input model, +% for which no composition could be assigned. % % Examples % -------- @@ -33,12 +34,13 @@ % A metabolite's composition can only be resolved from a reaction in which % every other participating metabolite already has a known composition; % the function repeats this until no further metabolites can be resolved. -% It requires that the existing compositions and reactions are correct, -% and throws an error if a metabolite would need inconsistent -% compositions in different reactions -- so it can also be used to check -% a model for such errors. Note that successful completion does not -% guarantee correctness if the pre-existing compositions were themselves -% wrong. +% It requires that the existing compositions and reactions are correct. If a +% metabolite would need different compositions in different reactions, or a +% reaction gives both positive and negative atom counts, the function issues +% a warning and assigns no composition to that metabolite, so the warnings +% can also be used to check a model for such inconsistencies. Completion +% without warnings does not show that the pre-existing compositions are +% correct. p=parseRAVENargs(varargin, {'printResults',true}); printResults=p.printResults; diff --git a/src/reconstruction/homology/getBlast.m b/src/reconstruction/homology/getBlast.m index 4701b5fd..f87daa2d 100755 --- a/src/reconstruction/homology/getBlast.m +++ b/src/reconstruction/homology/getBlast.m @@ -19,25 +19,28 @@ % Name-Value Arguments % -------------------- % developMode : logical -% true if blastReport should be generated that is used in the unit -% testing function for BLAST+ (default false). +% true if blastReport is filled, as used in the unit test for BLAST+ +% (default false). % hideVerbose : logical % true if no status messages should be printed (default false). % % Returns % ------- % blastStructure : struct -% structure containing the bidirectional homology measurements that -% can be used by getModelFromHomology. +% structure array with one element per search direction and template +% organism (2 times the number of modelIDs), containing the bidirectional +% homology measurements (fromId, toId, fromGenes, toGenes, evalue, +% identity, aligLen, bitscore and ppos) for use by getModelFromHomology. % blastReport : struct % structure containing MD5 hashes for FASTA database files and -% non-parsed BLAST output data. Will be blank if developMode is false. +% unparsed BLAST output data. The fields are empty if developMode is +% false. % % Notes % ----- % 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 +% standard settings. The only filtering this function applies is the removal % of hits with an E-value higher than 10e-5. % % Examples diff --git a/src/reconstruction/homology/getDiamond.m b/src/reconstruction/homology/getDiamond.m index 7dedb5bd..09fca52b 100755 --- a/src/reconstruction/homology/getDiamond.m +++ b/src/reconstruction/homology/getDiamond.m @@ -19,28 +19,30 @@ % Name-Value Arguments % -------------------- % developMode : logical -% true if blastReport should be generated that is used in the unit -% testing function for DIAMOND (default false). +% true if diamondReport is filled, as used in the unit test for DIAMOND +% (default false). % hideVerbose : logical % true if no status messages should be printed (default false). % % Returns % ------- % blastStructure : struct -% structure containing the bidirectional homology measurements which -% are used by getModelFromHomology. +% structure array with one element per search direction and template +% organism (2 times the number of modelIDs), containing the bidirectional +% homology measurements (fromId, toId, fromGenes, toGenes, evalue, +% identity, aligLen, bitscore and ppos) for use by getModelFromHomology. % diamondReport : struct % structure containing MD5 hashes for FASTA database files and -% non-parsed BLAST output data. Will be blank if developMode is false. +% unparsed DIAMOND output data. The fields are empty if developMode is +% false. % % Notes % ----- % 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(). +% "--more-sensitive" setting from DIAMOND. getBlast() gives the most +% sensitive results; getDiamond() is >15x faster. The blastStructure is in +% the same format as that obtained from getBlast(). % % Examples % -------- diff --git a/src/reconstruction/homology/getModelFromHomology.m b/src/reconstruction/homology/getModelFromHomology.m index 13dfb33d..41101910 100755 --- a/src/reconstruction/homology/getModelFromHomology.m +++ b/src/reconstruction/homology/getModelFromHomology.m @@ -21,28 +21,30 @@ % Name-Value Arguments % -------------------- % preferredOrder : cell -% 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 (default {}). +% the order in which reactions are added from the models, as a cell array +% of model IDs. If not supplied, reactions are included from all models, +% otherwise one gene results in reactions from one model only +% (default {}). % strictness : double -% integer that specifies which reactions should be included (default 1): +% integer that specifies which reactions are included (default 1): % -% - 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 the correspondent direction (mapping can be done in the -% opposite direction, see mapNewGenesToOld below). -% - 3 : check all BLASTP results and retain only the best hit (by -% bitscore) for each gene pair in each direction separately, then map -% new genes to old for all pairs which have acceptable BLASTP results -% in both directions. +% - 1 : map new genes to old for all pairs which have BLASTP results +% that pass the filters (maxE, minLen, minIde) in both directions. +% - 2 : map new genes to old for all pairs which have BLASTP results +% that pass the filters in one direction, selected by mapNewGenesToOld. +% - 3 : apply the filters (maxE, minLen, minIde), retain only the best hit +% (highest bitscore, ties included) among the hits that passed them for +% each query gene in each direction separately, then map new genes to +% old for all pairs which have BLASTP results in both directions. % onlyGenesInModels : logical % 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 +% give less reliable results. Changes the result only if strictness=3 % (default false). % maxE : double -% only look at genes with E-values <= this value (default 10^-30). +% only look at genes with E-values < this value (default 10^-30). In a +% benchmark against KEGG and OMA orthology, with the minIde filter in +% place, values between 10^-4 and 10^-50 gave the same result. % minLen : double % only look at genes with alignment length >= this value (default 100). % Measured against KEGG and OMA orthology across four organisms: any @@ -50,37 +52,37 @@ % real orthologs without reducing the number of wrong ones. % minIde : double % only look at genes with identity >= this value (default 40 (%)). -% The filter that decides the outcome, and 40 is the measured optimum -% once a wrongly transferred reaction is treated as worse than a missing -% one. maxE, by contrast, changes nothing between 10^-4 and 10^-50. +% This filter determines the result. In the calibration, with a wrongly +% transferred reaction counted as worse than a missing one, 40 lies in the +% 35 to 45 range that the KEGG and OMA references favour. % mapNewGenesToOld : logical -% 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 (default true). +% determines how to match genes when strictness is 2: true maps the new +% genes to the old, false maps the old genes to the new (default true). % complexPolicy : char -% what happens to an "and"-linked subunit without an ortholog: -% "flag" keeps the reaction with the subunit renamed -% OLD_MODELID_geneName, for a curator to review; "keep" drops just that -% subunit; "drop" drops the whole reaction (default "flag"). +% what happens to an "and"-linked subunit without an ortholog (case +% insensitive): "flag" keeps the reaction with the subunit renamed +% OLD_MODELID_geneName, for review; "keep" drops that subunit; +% "drop" drops the whole reaction (default "flag"). % keepGeneFree : logical % also transfer the template reactions that have no grRule (spontaneous, % transport, exchange, artificial). By default they are dropped, because -% nothing supports them in the new organism. Set it when the template is -% a curated reference whose gene-free reactions belong in every derived -% model. With several templates, a gene-free reaction comes in once per -% template (default false). +% no gene supports them in the new organism. When the template is a +% curated reference whose gene-free reactions belong in every derived +% model, true transfers them. With several templates, a gene-free +% reaction comes in once per template (default false). % preserveNotes : logical -% keep each transferred reaction's rxnNotes, rxnReferences and -% rxnConfidenceScores from the template. By default the notes say the -% reaction was included by getModelFromHomology and the confidence score -% is 2 (default false). +% keep rxnNotes and rxnConfidenceScores of each transferred reaction from +% the template. By default the notes say the reaction was included by +% getModelFromHomology and the confidence score is 2. The rxnReferences of +% the template reactions are always kept (default false). % % Returns % ------- % draftModel : struct % a model structure for the new organism. % hitGenes : struct -% collect the old and new genes. +% structure with the fields oldGenes (the template genes that were +% mapped) and newGenes (the corresponding genes of the new organism). % % Examples % -------- @@ -88,10 +90,10 @@ % % Notes % ----- -% 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 +% The models in the "models" structure should name 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 +% unnecessary old genes, the models should not have "or"-relations in their % grRules (use expandModel). % % The gene ids of the new organism in blastStructure become its gene ids in @@ -102,12 +104,14 @@ % The resulting draft model contains only reactions associated with % orthologous genes, plus the gene-free ones with keepGeneFree. With % complexPolicy "flag", the old (original) genes involved in "and" relations -% in grRules without any orthologs are still included in the draft model as +% in grRules without any orthologs are included in the draft model as % OLD_MODELID_geneName. A gene that several template genes map to appears % once in a grRule. The draft does not keep the version, date or % descriptive annotation of the templates. % -% "to" and "from" means relative to the new organism. +% "to" and "from" are relative to the new organism: "to" is a BLAST search from +% a template organism to the new organism, "from" is a search from the new +% organism to a template organism. % % The hits can also come from SuppOrth consensus orthologs (hitsFromSuppOrth, % runSuppOrth). Their e-value, identity and alignment length are diff --git a/src/reconstruction/homology/hitsFromSuppOrth.m b/src/reconstruction/homology/hitsFromSuppOrth.m index bc414d49..37fb1e2f 100644 --- a/src/reconstruction/homology/hitsFromSuppOrth.m +++ b/src/reconstruction/homology/hitsFromSuppOrth.m @@ -16,7 +16,7 @@ % organismID : char % SuppOrth species label of the organism to build a model for: the % FASTA file name without extension, or the --labels value. It becomes -% fromId/toId unless speciesToModel maps it to another id. +% fromId and toId unless speciesToModel maps it to another id. % % Name-Value Arguments % -------------------- diff --git a/src/reconstruction/homology/makeFakeBlastStructure.m b/src/reconstruction/homology/makeFakeBlastStructure.m index 734c70c5..78bdd77b 100755 --- a/src/reconstruction/homology/makeFakeBlastStructure.m +++ b/src/reconstruction/homology/makeFakeBlastStructure.m @@ -1,12 +1,11 @@ function blastStructure=makeFakeBlastStructure(orthologList,sourceModelID,getModelFor) % makeFakeBlastStructure Make a fake blastStructure from an ortholog list. % -% This is a structure that would normally be generated by getBlast. It -% 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. +% The structure has the format that getBlast generates. It feeds a +% predefined list of orthologs to getModelFromHomology. The orthologList +% is a cell array with at least 10 rows and two columns: the first column +% contains the genes from the source organism and the second column the +% genes from the target organism. % % Parameters % ---------- @@ -24,9 +23,10 @@ % Returns % ------- % blastStructure : struct -% 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. +% a fake blastStructure with one element per direction. For every pair, +% evalue is 0, identity is 100, aligLen is 1000, bitscore is 100 and +% ppos is 100. All orthologous pairs pass the filters of +% getModelFromHomology. % % Examples % -------- diff --git a/src/reconstruction/kegg/buildGlobalGPR.m b/src/reconstruction/kegg/buildGlobalGPR.m index 9c88b6c6..d27a128b 100644 --- a/src/reconstruction/kegg/buildGlobalGPR.m +++ b/src/reconstruction/kegg/buildGlobalGPR.m @@ -1,11 +1,11 @@ function [genes,rxnGeneMat]=buildGlobalGPR(rxns,koReaction,organismGeneKO) -% buildGlobalGPR Join every KEGG organism's genes onto the reference -% reactions through their shared KO (KEGG Orthology) ids. +% buildGlobalGPR Join the genes of all KEGG organisms to reference reactions by KO id. % -% Builds two sparse gene-KO / KO-reaction incidence matrices sharing one -% KO axis, and multiplies them, rather than expanding the join row by -% row --- organismGeneKO can carry millions of rows (every gene of every -% KEGG organism), so a per-row loop is not viable. +% Joins every KEGG organism's genes onto the reference reactions through their +% shared KO (KEGG Orthology) ids. The function builds two sparse incidence +% matrices (gene to KO and KO to reaction) that share one KO axis, and +% multiplies them. The join is not expanded row by row, because organismGeneKO +% can contain millions of rows (every gene of every KEGG organism). % % Parameters % ---------- @@ -22,7 +22,7 @@ % genes : cell array % sorted unique 'organism:gene' identifiers. % rxnGeneMat : sparse double -% numel(rxns) x numel(genes); rxnGeneMat(i,j)=1 when gene j shares at +% numel(rxns) by numel(genes); rxnGeneMat(i,j)=1 when gene j shares at % least one KO with reaction i. %Map each ko_reaction row onto the reference model's own reaction order; diff --git a/src/reconstruction/kegg/buildGlobalKEGGModel.m b/src/reconstruction/kegg/buildGlobalKEGGModel.m index f31b248a..b5417ec0 100644 --- a/src/reconstruction/kegg/buildGlobalKEGGModel.m +++ b/src/reconstruction/kegg/buildGlobalKEGGModel.m @@ -2,10 +2,10 @@ % buildGlobalKEGGModel Download and assemble the global KEGG model. % % Fetches the toolbox-assets _core.tar.gz bundle (the -% gene-free reference model plus the ko_reaction / organism_gene_ko / -% rxn_flags relational tables), then joins every organism's -% genes onto the reference reactions through their shared KO ids. The -% KEGG version is read from keggDataVersion, not hardcoded here. +% gene-free reference model plus the ko_reaction, organism_gene_ko and +% rxn_flags relational tables), then joins every organism's genes onto +% the reference reactions through their shared KO ids. The KEGG version +% is read from keggDataVersion. % % Parameters % ---------- @@ -15,9 +15,9 @@ % Returns % ------- % model : struct -% the full global KEGG model (all reactions/metabolites, genes and -% rxnGeneMat spanning every KEGG organism). Callers narrow this down -% to one organism (see getKEGGModelForOrganism). +% the full global KEGG model (all reactions and metabolites, genes and +% rxnGeneMat spanning every KEGG organism). getKEGGModelForOrganism +% narrows it to one organism. % KOModel : struct % a minimal model struct whose rxns are the KO ids linked to at % least one reaction (getKEGGModelForOrganism's HMM-search path uses diff --git a/src/reconstruction/kegg/getKEGGModelForOrganism.m b/src/reconstruction/kegg/getKEGGModelForOrganism.m index 18330504..319e7a72 100755 --- a/src/reconstruction/kegg/getKEGGModelForOrganism.m +++ b/src/reconstruction/kegg/getKEGGModelForOrganism.m @@ -3,84 +3,83 @@ % % 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). +% the function stops with an error; give a closely related species as +% organismID. Without a fastaFile, the +% protein homology search is skipped (see the fastaFile parameter). % % Parameters % ---------- % organismID : char % 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. +% If the organism is not available, a closely related species can be +% given. The abbreviation determines the genes that are kept when +% fastaFile is empty. "eukaryotes" or "prokaryotes" gives a model for +% the whole domain. Only applicable if fastaFile is empty, that is when +% no homology search is performed. % % Name-Value Arguments % -------------------- % fastaFile : char % a FASTA file that contains the protein sequences of the organism for % which to reconstruct a model. 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. +% model is reconstructed based only on the organism abbreviation. In this +% case, cutOff, minScoreRatioKO, minScoreRatioG and dataDir are not +% used (default []). % dataDir : char -% directory for which to retrieve the input data, styled as -% kegg118_prokaryotes or kegg118_eukaryotes, indicating the KEGG version -% and whether the HMMs were trained on pro- or eukaryotic sequences. The -% directory name matches the published HMM library it is paired with. The -% prebuilt concatenated KO HMM library (dataDir.hmm) is downloaded here -% from the corresponding toolbox-assets release if not already present. This -% parameter should ALWAYS be provided. +% directory of the HMM library, named kegg118_prokaryotes or +% kegg118_eukaryotes. The name gives the KEGG version and whether the +% HMMs were trained on pro- or eukaryotic sequences, and matches the +% published HMM library it is paired with. The prebuilt concatenated KO +% HMM library (dataDir.hmm) is downloaded from the corresponding +% toolbox-assets release if it is not already present. Required when +% fastaFile is supplied (default []). % outDir : char -% 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 -% (default is a temporary dir where all *.out files are deleted before -% and after doing the reconstruction). +% directory that is created if it does not exist when fastaFile is +% supplied. The function writes no result files to it (default is the +% temporary directory, where all *.out files are deleted before the +% reconstruction). % keepSpontaneous : logical -% include reactions labeled as "spontaneous" (default true). +% include reactions labelled as "spontaneous" (default true). % keepUndefinedStoich : logical -% include reactions in the form n A <=> n+1 A. These will be dealt with -% as two separate metabolites (default true). +% include reactions in the form n A <=> n+1 A. These are treated as +% two separate metabolites (default true). % keepIncomplete : logical % include reactions which have been labelled as "incomplete", % "erroneous" or "unclear" (default true). % keepGeneral : logical % 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 (default false). +% These are reactions of the form "an aldehyde <=> an alcohol". Not all +% such reactions have this label, so the function cannot remove all of +% them (default false). % cutOff : double -% significance score from HMMer needed to assign genes to a KO (default -% 10^-30). +% maximum full-sequence E-value from HMMER for assigning a gene to a KO +% (default 10^-30). % minScoreRatioKO : double -% ignore genes in a KO if their 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 (default 0.9, lower is less strict). +% a gene is only assigned to KOs for which log(score)/log(best score) +% is at least this value, where best score is the lowest E-value of +% that gene over its KOs after the minScoreRatioKO step. This removes the +% assignment of a gene to KOs with a much higher E-value than its best KO +% (default 0.9, lower is less strict). % maxPhylDist : double -% -1 to only use sequences from the same domain (Prokaryota, Eukaryota); -% any other (positive) value to only use sequences for organisms where -% the phylogenetic distance is at the most this large (as calculated in -% getPhylDist). Only used when reconstructing from KEGG annotations (no -% fastaFile) (default Inf, which means that all sequences will be used). +% only used when fastaFile is empty and organismID is "eukaryotes" or +% "prokaryotes". -1 keeps genes from organisms in the same domain +% (Prokaryota, Eukaryota) as H. sapiens ("hsa") or E. coli ("eco"), +% respectively. Any other value, including Inf, does not restrict the +% domain, and the value is not compared with the distances calculated +% in getPhylDist (default Inf). % globalModel : struct % 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 +% by getModelFromKEGG. When empty, the global model is loaded with +% getModelFromKEGG. Providing globalModel avoids reloading it when +% getKEGGModelForOrganism is run several times, for example for % different strains. Example: % [globalModel.model,globalModel.KOModel] = getModelFromKEGG (default -% empty, global model is loaded by getModelFromKEGG). +% []). % % Returns % ------- @@ -93,19 +92,18 @@ % % 1. From KEGG annotations (no fastaFile supplied). The reactions % associated with organismID in the local KEGG database are kept; -% maxPhylDist controls which organism annotations are considered. +% maxPhylDist applies to organismID "eukaryotes" and "prokaryotes". % 2. From protein homology (fastaFile supplied). The query proteome is % searched, in a single hmmsearch, against a prebuilt KEGG-version- and -% domain-specific concatenated KO HMM library (e.g. kegg118_eukaryotes), -% downloaded from the corresponding RAVEN release if not already present -% in dataDir. Hits are filtered by cutOff and the minScoreRatioKO / -% minScoreRatioG ratios into a KO-gene matrix, from which the model is -% built (spontaneous reactions without genes are kept if keepSpontaneous -% is true). +% domain-specific concatenated KO HMM library (for example +% kegg118_eukaryotes), downloaded from the corresponding toolbox-assets +% release if not already present in dataDir. Hits are filtered by cutOff, +% minScoreRatioKO and minScoreRatioG into a KO-gene matrix, from which the +% model is built (spontaneous reactions without genes are kept if +% keepSpontaneous is true). % % The global KEGG model (reaction-KO relationships) is either supplied via -% globalModel, built from a local KEGG FTP dump in dataDir\keggdb (which -% requires a KEGG FTP license), or loaded from the internal RAVEN version. +% globalModel or loaded with getModelFromKEGG. % % Examples % -------- diff --git a/src/reconstruction/kegg/getModelFromKEGG.m b/src/reconstruction/kegg/getModelFromKEGG.m index f619df61..1b853173 100755 --- a/src/reconstruction/kegg/getModelFromKEGG.m +++ b/src/reconstruction/kegg/getModelFromKEGG.m @@ -1,19 +1,18 @@ function [model,KOModel]=getModelFromKEGG(varargin) % getModelFromKEGG Load the global KEGG model. % -% Loads the global KEGG reaction/gene model from keggModel.mat. On first -% use --- when no keggModel.mat is present yet --- the underlying -% artefacts (the gene-free reference model plus the KO/reaction/organism- -% gene relational tables, published as a toolbox-assets release) are -% downloaded and assembled instead, and the result is cached to -% keggModel.mat so later calls load instantly. The first build can take -% a while (the organism-gene table covers every KEGG organism) and needs -% a few hundred MB of disk. +% Loads the global KEGG reaction and gene model from keggModel.mat. When +% keggModel.mat is not present, the underlying artefacts (the gene-free +% reference model plus the KO, reaction and organism-gene relational +% tables, published as a toolbox-assets release) are downloaded and +% assembled, and the result is saved to keggModel.mat for later calls. The +% first build takes longer because the organism-gene table covers every +% KEGG organism, and needs a few hundred MB of disk. % % Name-Value Arguments % -------------------- % keepSpontaneous : logical -% include reactions labeled as "spontaneous" (default true). +% include reactions labelled as "spontaneous" (default true). % keepUndefinedStoich : logical % include reactions in the form n A <=> n+1 A (default true). % keepIncomplete : logical @@ -32,9 +31,9 @@ % % Notes % ----- -% The model output can be used as a template for fillGaps. In that case, -% remove the genes and rxnGeneMat fields before parsing: -% model = rmfield(model, 'genes'), etc. +% The model output can be used as a template for fillGaps after the genes +% and rxnGeneMat fields are removed: +% model = rmfield(model, 'genes') and model = rmfield(model, 'rxnGeneMat'). % % See also % -------- diff --git a/src/reconstruction/kegg/getPhylDist.m b/src/reconstruction/kegg/getPhylDist.m index 57922753..f9dc8125 100755 --- a/src/reconstruction/kegg/getPhylDist.m +++ b/src/reconstruction/kegg/getPhylDist.m @@ -2,7 +2,7 @@ % getPhylDist Load the pre-built KEGG phylogenetic distance matrix. % % Loads the pre-built phylogenetic distance matrix from keggPhylDist.mat. -% The matrix ships with RAVEN; it is derived from the KEGG taxonomy, which +% The matrix ships with RAVEN and is derived from the KEGG taxonomy, which % is a toolbox-assets release asset. % % Name-Value Arguments diff --git a/src/reconstruction/kegg/keggDataVersion.m b/src/reconstruction/kegg/keggDataVersion.m index 36477332..c8ee5493 100644 --- a/src/reconstruction/kegg/keggDataVersion.m +++ b/src/reconstruction/kegg/keggDataVersion.m @@ -1,16 +1,15 @@ function version=keggDataVersion() % keggDataVersion The toolbox-assets release tag for KEGG artefacts. % -% Reads reconstruction/kegg/KEGG_VERSION.md --- the single place this -% version is recorded --- so every function that downloads a KEGG -% artefact (getModelFromKEGG, getKEGGModelForOrganism) stays in sync -% when toolbox-assets publishes a new KEGG release. The version is the -% file's first line. +% Reads the first line of src/reconstruction/kegg/KEGG_VERSION.md. The file is +% the single place where the version is recorded, so that every function that +% downloads a KEGG artefact (getModelFromKEGG, getKEGGModelForOrganism) uses +% the same release. % % Returns % ------- % version : char -% the toolbox-assets release tag, e.g. 'kegg118'. +% the toolbox-assets release tag, for example 'kegg118'. ravenPath=findRAVENroot(); versionFile=fullfile(ravenPath,'src','reconstruction','kegg','KEGG_VERSION.md'); diff --git a/src/reconstruction/kegg/readKEGGTable.m b/src/reconstruction/kegg/readKEGGTable.m index 7fce0690..76ebe6e7 100644 --- a/src/reconstruction/kegg/readKEGGTable.m +++ b/src/reconstruction/kegg/readKEGGTable.m @@ -1,13 +1,13 @@ function tbl=readKEGGTable(gzFile) -% readKEGGTable Read a gzipped KEGG relational table into a table with -% every column forced to char cellstr (matching RAVEN's own -% cell-array-of-char convention, regardless of the caller's default -% text-import type). +% readKEGGTable Read a gzipped KEGG relational table into a table of cellstr columns. +% +% Every column is a cellstr (RAVEN's cell-array-of-char convention), whatever the +% default text-import type of the caller. % % Parameters % ---------- % gzFile : char -% path to the gzipped TSV file, e.g. '.../kegg118_ko_reaction.tsv.gz'. +% path to the gzipped TSV file, for example '.../kegg118_ko_reaction.tsv.gz'. % % Returns % ------- diff --git a/src/solver/getMinNrFluxes.m b/src/solver/getMinNrFluxes.m index 655e7287..3c7a6213 100755 --- a/src/solver/getMinNrFluxes.m +++ b/src/solver/getMinNrFluxes.m @@ -12,16 +12,19 @@ % Name-Value Arguments % -------------------- % toMinimize : cell or logical or double -% 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 -% for the reactions that should be minimized (default model.rxns). +% 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 for the +% reactions that should be minimised (default model.rxns). % params : struct -% *obsolete option*. +% solver parameters passed to optimizeProb. With formulation +% 'reversible', intTol (10^-9), TimeLimit (300) and Seed (26) are set +% when absent (default empty struct). % scores : double -% 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)), or to 0 if scores has no -% negative entry at all. Must have the same dimension as toMinimize +% vector of weights for the reactions. A reaction with a negative +% score adds the negated score to the minimised objective when it +% carries flux. Scores of 0 or above are not supported and are +% changed to max(scores(scores<0)), or to 0 if scores has no negative +% entry at all. Must have the same dimension as toMinimize % (find(toMinimize) if it is a logical vector) (default -1 for all % reactions). % formulation : char @@ -29,24 +32,26 @@ % % - 'irrev' : convert the model to irreversible format and use one % binary per irreversible reaction, so a reversible reaction that is -% minimized costs two binaries. The magnitude of the fluxes is +% minimised needs two binaries. The magnitude of the fluxes is % estimated with an LP first, which also provides a start solution. % - 'reversible' : keep the model reversible and use one binary per -% reaction, at the cost of a larger constraint matrix. Fewer binaries -% makes this the faster formulation on large problems, but it needs a -% solver that handles MILPs well and no LP estimate of the flux -% magnitudes is made, so an arbitrary large flux is assumed. +% reaction, with a larger constraint matrix. The formulation has +% fewer binaries but needs a solver that handles MILPs well. No LP +% estimate of the flux magnitudes is made, and a fixed flux of 1000 is +% assumed. % verbose : logical % if true, the MILP progression will be shown (default false). % resolveTies : logical -% if true, pin the MILP's degenerate optimum to a canonical answer instead of -% relying on Seed alone: hold the primary (scores) objective at its optimum, -% then minimize the count of "on" reactions, then, among the sparsest, minimize -% their summed reaction-id rank (lowest ids preferred). Two extra MILP solves; -% best-effort, so a phase that does not converge within TimeLimit is dropped -% with a warning rather than changing the result. Only implemented for -% formulation='reversible' -- errors if combined with 'irrev'. Matches -% raven-toolbox's resolve_ties (raven-gecko-parity#104) (default false). +% if true, select one optimum among the degenerate optima of the MILP +% instead of relying on Seed: the primary (scores) objective is held +% at its optimum, the count of "on" reactions is minimised, and among +% the sparsest solutions the summed reaction-id rank is minimised +% (lowest ids preferred). This takes two extra MILP solves. A phase +% that is not proven optimal within TimeLimit gives a warning, and the +% solution of the last phase is used when it is feasible. Only +% implemented for formulation='reversible'; combined with 'irrev' it +% gives an error. Matches resolve_ties in raven-toolbox +% (raven-gecko-parity#104) (default false). % % Returns % ------- @@ -62,8 +67,8 @@ % - -1 : no solution found, either because the problem is infeasible or % because the solver reached its time limit before finding one % - -2 : a solution was found but is not proven optimal, because the -% solver stopped before reaching optimality. It is returned, but it -% may use more fluxes than the minimum +% solver stopped before reaching optimality. It is returned and may +% use more fluxes than the minimum % % Examples % -------- @@ -71,8 +76,11 @@ % % Notes % ----- -% Uses 1000 mmol/gDW/h as an arbitary large flux. Could possibly cause -% problems if the fluxes in the model are larger than that. +% The binary of a reaction is linked to its flux through a large flux +% value. With formulation 'irrev' the value is the larger of 1000 and 5 +% times the largest flux of an LP solution; with 'reversible' it is 1000 +% (mmol/gDW/h). A flux above this value is cut off by the binary constraint +% of the reaction, so the MILP can become infeasible. p=parseRAVENargs(varargin, {'toMinimize',[]; 'params',[]; 'scores',[]; ... 'formulation','irrev'; 'verbose',false; 'resolveTies',false}); diff --git a/src/solver/optimizeProb.m b/src/solver/optimizeProb.m index 6fc3585e..f765886d 100755 --- a/src/solver/optimizeProb.m +++ b/src/solver/optimizeProb.m @@ -1,22 +1,23 @@ function res = optimizeProb(prob,varargin) -% optimizeProb Optimize an LP or MILP formulated in COBRA terms. +% optimizeProb Optimise an LP or MILP formulated in COBRA terms. % % Parameters % ---------- % prob : struct -% COBRA-style LP/MILP problem struct to be optimised. +% COBRA-style problem struct of an LP or MILP to be optimised. % % Name-Value Arguments % -------------------- % params : struct % solver-specific parameters. In addition to solver parameters, the -% field "maxRatio" can be set to a number > 1 to improve numerical -% conditioning: before solving (LP only) any column whose coefficients -% span more than maxRatio is split via auxiliary metabolites/variables, -% preserving the feasible region. See splitProbForConditioning. The -% field is consumed here and not forwarded to the solver. +% field "maxRatio" can be set to a finite number > 1 for numerical +% conditioning: before solving an LP, any column whose coefficients +% span more than maxRatio is split with auxiliary metabolites and +% variables, which preserves the feasible region. See +% splitProbForConditioning. The field is removed before the parameters +% are passed to the solver, and is ignored for MILPs. % verbose : logical -% if true MILP progress is shown (default true). +% if true, MILP progress is shown (default true). % % Returns % ------- @@ -24,16 +25,16 @@ % the output structure from the selected solver RAVENSOLVER (COBRA % style). In addition to the fields set by the solver, the logical field % "hitTimeLimit" is true if the solver stopped because it reached its -% time limit. Whatever solution is in res is then either absent or not -% proven optimal. +% time limit. The solution in res is then either absent or not proven +% optimal. % % Notes % ----- % MILPs can be solved with GLPK, either RAVEN's bundled GLPK ('glpk') or % the COBRA Toolbox's GLPK interface ('cobra' with GLPK as its MILP solver). -% A RAVEN:glpkMILP warning then recommends Gurobi, which is much faster and -% more reliable on larger MILPs (such as ftINIT or getMinNrFluxes on -% genome-scale models). +% The RAVEN:glpkMILP warning then states that GLPK works for small problems +% and that Gurobi is much faster and more reliable for larger ones (such as +% ftINIT or getMinNrFluxes on genome-scale models). % % See also % -------- diff --git a/src/solver/setRavenSolver.m b/src/solver/setRavenSolver.m index dc534e91..c8ce7f2a 100755 --- a/src/solver/setRavenSolver.m +++ b/src/solver/setRavenSolver.m @@ -10,15 +10,15 @@ function setRavenSolver(solver) % string with solver name. The following options are available: % % - glpk : uses RAVEN-provided binaries. Solves LPs and MILPs; for -% MILPs a RAVEN:glpkMILP warning recommends Gurobi, which is much -% faster and more reliable on larger problems. +% MILPs the RAVEN:glpkMILP warning states that Gurobi is much faster +% and more reliable for larger problems. % - gurobi : requires a working Gurobi installation. % - scip : requires a SCIP MEX interface. RAVEN provides a % precompiled binary for Windows only. % - cobra : requires a working COBRA Toolbox installation. RAVEN % parses the problem to COBRA and uses the solver that is set by -% changeCobraSolver. MILPs are refused when COBRA's MILP solver is -% GLPK. +% changeCobraSolver. For MILPs, the RAVEN:glpkMILP warning is issued +% when COBRA's MILP solver is GLPK. % % Examples % -------- diff --git a/src/solver/solveLP.m b/src/solver/solveLP.m index a5e96d78..ed0c4fb6 100755 --- a/src/solver/solveLP.m +++ b/src/solver/solveLP.m @@ -9,28 +9,28 @@ % Name-Value Arguments % -------------------- % minFlux : double -% determines if a second optimization should be performed in order to -% get rid of loops in the flux distribution (default 0): +% determines if a second optimisation is performed to remove loops +% from the flux distribution (default 0): % -% - 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 +% - 0 : no second optimisation is performed +% - 1 : the sum of abs(fluxes) is minimised with an LP, which does not +% need the MILP that the minimisation of the number of fluxes requires +% - 2 : deprecated; gives an error +% - 3 : the number of fluxes is minimised with getMinNrFluxes, which +% solves a MILP and can take long. The result has the fewest active +% reactions, which can make the flux distribution easier to interpret % params : struct -% solver parameters, forwarded to optimizeProb. Mostly obsolete, but the -% field "maxRatio" (a number > 1) can be set to improve numerical -% conditioning of ill-scaled models: any reaction whose stoichiometric -% coefficients span more than maxRatio is transiently split via -% auxiliary metabolites before solving, which preserves the feasible -% region (and thus the flux distribution of the original reactions). A -% common value is 1e6 (no splitting by default). +% solver parameters, forwarded to optimizeProb. The field "maxRatio" +% (a number > 1) can be set for numerical conditioning of ill-scaled +% models: any reaction whose stoichiometric coefficients span more +% than maxRatio is split with auxiliary metabolites before solving, +% which preserves the feasible region (and thus the flux distribution +% of the original reactions). A common value is 1e6. No splitting is done +% when maxRatio is absent (default struct with relGap=0.4). % hsSol : struct -% 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. +% hot-start solution for the LP solver, as hsSolOut from a previous +% call. It speeds up the solution when many similar optimisation +% problems are solved iteratively. A hsSol with stat<1 is ignored. % % Returns % ------- @@ -39,15 +39,16 @@ % % - f : objective value % - x : primal (flux distribution) -% - stat : exit flag (1 = optimization terminated successfully, 0 = +% - stat : exit flag (1 = optimisation terminated successfully, 0 = % 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 +% solution found, -2 = solution found but flux minimisation failed) +% - msg : string describing the status of the optimisation % - sPrice : shadow price (only reported if minFlux was 0) % - rCost : reduced cost (only reported if minFlux was 0) % hsSolOut : struct % solution to be used as hot-start solution (see the input parameters). -% Only used if minFlux is 0 or 1. +% Set only if minFlux is 0 or 1, and only when the solver returns a +% basis. % % Examples % -------- diff --git a/src/solver/splitProbForConditioning.m b/src/solver/splitProbForConditioning.m index c9fb6b38..98157373 100644 --- a/src/solver/splitProbForConditioning.m +++ b/src/solver/splitProbForConditioning.m @@ -4,18 +4,20 @@ % Reformulates an LP problem to improve its numerical conditioning by % splitting columns whose coefficients span more than a given ratio. In a % metabolic model a column corresponds to a reaction, and a wide spread of -% stoichiometric coefficients within one reaction (e.g. a biomass reaction -% with both major substrates and trace cofactors) cannot be removed by the -% diagonal row/column scaling that LP solvers apply, and may lead to +% stoichiometric coefficients within one reaction (for example a biomass reaction +% with both large and small coefficients) cannot be removed by the +% diagonal row and column scaling that LP solvers apply, and may lead to % unreliable solutions or spurious infeasibility. % -% Splitting is done via auxiliary metabolites and variables that preserve +% Splitting is done with auxiliary metabolites and variables that preserve % the feasible region of the original problem exactly, so the values of all -% original variables are unchanged. +% original variables are unchanged. A column is split when its ratio +% exceeds maxRatio by more than 1 %. Columns with a single nonzero +% coefficient are never split. % -% The function is meant to be called inside optimizeProb, on the COBRA-style -% problem struct, immediately before the problem is passed to the solver. -% Auxiliary rows/columns are appended after the original ones, so the +% optimizeProb calls this function on the COBRA-style problem struct of an +% LP, immediately before the problem is passed to the solver. Auxiliary +% rows and columns are appended after the original ones, so the % augmentation can be stripped from the solver output afterwards (see % condInfo). % @@ -31,13 +33,14 @@ % Returns % ------- % prob : struct -% the (possibly) augmented problem struct. Identical to the input if no -% column needed splitting. +% the augmented problem struct. Identical to the input if no column +% needed splitting. % condInfo : struct % struct describing the augmentation, with fields: % % - applied : true if any column was split -% - nSplits : number of auxiliary metabolite/conversion pairs added +% - nSplits : number of pairs of an auxiliary metabolite and a conversion +% variable added % - nOrigRows : number of constraint rows before augmentation % - nOrigCols : number of variables (columns) before augmentation % diff --git a/src/tasks/checkTasks.m b/src/tasks/checkTasks.m index 778f4eff..69a5c1fa 100755 --- a/src/tasks/checkTasks.m +++ b/src/tasks/checkTasks.m @@ -1,12 +1,11 @@ function [taskReport, essentialRxns, taskStructure, essentialFluxes]=checkTasks(model,inputFile,varargin) % checkTasks Perform a set of simulations as defined in a task file. % -% 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. +% The function runs a set of tasks for a model. Each task is defined by +% constraints on the model, and the task is successful if the problem is +% feasible. 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. % % The task inputs and outputs are applied to the boundary metabolites of % the model. The model's own exchange reactions are not closed: they keep @@ -30,17 +29,18 @@ % true if only tasks that failed should be displayed (default false). % getEssential : logical % true if the essential reactions should be calculated for all the -% tasks. This option is used with runINIT (default false). +% tasks. This option is used by prepINITModel (ftINIT) and getINITModel +% (tINIT) (default false). % taskStructure : struct % structure with the tasks, as from parseTaskList. If this is supplied % then inputFile is ignored. % runParallel : logical -% true to evaluate tasks in parallel workers, since each task is -% independent of the others (see parallelWorkersRAVEN). Gurobi is -% automatically pinned to one thread per worker by optimizeProb, so -% this does not oversubscribe cores. Default false, matching the -% previous (serial) behaviour, since checkTasks is often called on -% small task lists where starting a pool would only add overhead. +% true to evaluate tasks in parallel workers, as each task is +% independent of the others (see parallelWorkersRAVEN). In a worker, +% optimizeProb sets Gurobi to one thread, so the workers do not use +% more cores than assigned. With false the tasks are evaluated in +% series, which avoids the overhead of starting a pool for small task +% lists (default false). % % Returns % ------- @@ -59,7 +59,9 @@ % taskStructure : struct % structure with the tasks, as from parseTaskList. % essentialFluxes : double -% the fluxes of the essential rxns - same structure as essentialRxns. +% the fluxes of the model reactions in the solution of each task (NaN +% for a task without a solution), with the same dimensions as +% essentialRxns. % % Examples % -------- diff --git a/src/tasks/parseTaskList.m b/src/tasks/parseTaskList.m index dde8b8f5..4589d6c3 100755 --- a/src/tasks/parseTaskList.m +++ b/src/tasks/parseTaskList.m @@ -5,36 +5,33 @@ % ---------- % inputFile : char % a task list in either Excel (*.xlsx, with a sheet named TASKS with -% all relevant content) or tab-delimited (*.txt) format. The old binary +% all relevant content) or tab-delimited (*.txt) format. The binary % *.xls format is not supported. 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; the -% header row itself must therefore start with an empty cell): +% column headers. Rows that start with a non-empty cell are comments +% and are removed. The first row that starts with an empty cell is the +% header row, so the header row and the task rows must start with an +% empty cell: % % - ID : the only required header (string or numeric). Ids may repeat, % for example as category codes. A task starts at a row with a % non-empty id and can span multiple rows; only the first row of a task % should have an id % - DESCRIPTION : description of the task -% - IN : allowed input(s) for the task. Metabolite names should be on +% - IN : allowed input(s) for the task. Metabolite names are written in % 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) +% (optional, default 0) % - 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) +% (optional, default 1000) % - 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) +% row (optional, default 0) % - 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 +% row (optional, default 1000) +% - EQU : equation to add. The equation is written in the form +% "0.4 A + 2 B <=> (or =>) C" and the metabolites in the % form "model.metName[model.comps]" (optional) % - EQU LB : lower bound for the equation (optional, default -1000 for % reversible and 0 for irreversible) @@ -47,13 +44,15 @@ % of the reaction is left as it is % - CHANGED UB : upper bound for the reaction. If empty, the upper bound % of the reaction is left as it is -% - SHOULD FAIL : true if the correct behavior of the model is to not +% - SHOULD FAIL : true if the correct behaviour of the model is to not % have a feasible solution given the constraints. Any non-empty value % except 0, false and no (any case) counts as true (optional, default % false) -% - PRINT FLUX : true if the function should print the corresponding -% flux distribution for a task. Can be useful for testing. Read in -% the same way as SHOULD FAIL (optional, default false) +% - PRINT FLUX : true if checkTasks should print the corresponding +% flux distribution for a task. Read in the same way as SHOULD FAIL +% (optional, default false) +% - COMMENTS : comments on the task, stored in the field comments +% (optional) % % Headers are matched ignoring case and surrounding whitespace. In the % ";"-delimited cells, items are trimmed and empty items are dropped. @@ -90,23 +89,20 @@ % % Notes % ----- -% 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. +% The task list defines a set of tasks for a model to perform. A task is +% defined by constraints on the model, and the task is successful if the +% problem is feasible. 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. % % 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 is the synthesis of some metabolite that is limiting or -% whether it is 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. +% inputs or outputs in the same manner as normal metabolites. They allow, +% for example, excretion of all metabolites, to check whether the +% synthesis of some metabolite or the degradation of some byproduct is +% limiting. Only the upper bounds are used for these general metabolites, +% so uptake or excretion can be allowed but not required. A lower bound +% would overwrite the constraints of the individual metabolites. % % See also % -------- diff --git a/src/utils/convertCharArray.m b/src/utils/convertCharArray.m index ec25bcfd..e140abf0 100755 --- a/src/utils/convertCharArray.m +++ b/src/utils/convertCharArray.m @@ -1,9 +1,9 @@ function inputConverted = convertCharArray(funcInput) % convertCharArray Ensure input is a cell array of character vectors. % -% Converts input to make sure it is a cell array of character vectors. -% String arrays are transformed into character vectors. Output is always a -% cell array, also if only one character vector is given as input. +% Converts the input to a cell array of character vectors. String arrays +% are transformed into character vectors. A single character vector gives +% a cell array with one element. An empty input gives []. % % Parameters % ---------- @@ -13,7 +13,7 @@ % Returns % ------- % inputConverted : cell -% cell array of character vectors. +% cell array of character vectors, or [] if funcInput is empty. % % Examples % -------- diff --git a/src/utils/deprecationWarning.m b/src/utils/deprecationWarning.m index aa0a6f5c..8cf4b91e 100644 --- a/src/utils/deprecationWarning.m +++ b/src/utils/deprecationWarning.m @@ -2,16 +2,16 @@ function deprecationWarning(oldFunction, replacement) % deprecationWarning Warn once per session that a function is deprecated. % % Used by the wrappers in the deprecated/ folder. Each function warns the -% first time it is called in a MATLAB session and stays quiet afterwards, -% so a loop over thousands of reactions does not bury the console. Call -% "clear functions" to reset. +% first time it is called in a MATLAB session and does not warn again, also +% when it is called repeatedly in a loop. "clear functions" resets the +% record of functions that have warned. % % Parameters % ---------- % oldFunction : char % name of the deprecated function. % replacement : char -% what to call instead, written as it would be typed, e.g. +% what to call instead, written as it would be typed, for example % 'findLeakMetabolite(model,''produce'',...)'. % % Examples diff --git a/src/utils/grRuleToDNF.m b/src/utils/grRuleToDNF.m index f2ea4465..d8dca909 100644 --- a/src/utils/grRuleToDNF.m +++ b/src/utils/grRuleToDNF.m @@ -9,7 +9,7 @@ % ---------- % rule : char or string or struct % a grRule, or a tree from parseGrRule. A grRule is read by parseGrRule: -% genes joined by "and"/"or" in any case or by "&", "&&", "|", "||", +% genes joined by "and" or "or" in any case or by "&", "&&", "|", "||", % each operator separated from the gene ids by whitespace or a bracket, % with AND binding tighter than OR. % @@ -27,11 +27,11 @@ % % Gene order within a clause follows the order the genes appear in the rule. % Duplicates are not removed: "G1 and G1" stays a two-element clause, since -% collapsing it would silently rewrite the user's rule. +% collapsing it would change the rule. % % The number of clauses is the product of the OR-arities across a complex, -% so a pathological rule can expand combinatorially. Callers that build one -% object per clause should check numel(clauses) first. +% so the number of clauses can grow combinatorially with the rule. A caller +% that builds one object per clause can check numel(clauses) first. % % Examples % -------- diff --git a/src/utils/grRuleToString.m b/src/utils/grRuleToString.m index 19706872..8f9e6f57 100644 --- a/src/utils/grRuleToString.m +++ b/src/utils/grRuleToString.m @@ -1,9 +1,10 @@ function rule=grRuleToString(tree) % grRuleToString Render a grRule syntax tree back to a string. % -% Writes the standard RAVEN format: " and " / " or " as operators, with -% parentheses added only where precedence requires them, so that -% parseGrRule(grRuleToString(tree)) round-trips to the same structure. +% Writes the standard RAVEN format, with " and " and " or " as operators. An +% AND node inside an OR node and an OR node inside an AND node are placed in +% parentheses. The result parses with parseGrRule to a rule with the same +% logic. % % Parameters % ---------- diff --git a/src/utils/isDnfGrRule.m b/src/utils/isDnfGrRule.m index 343709e0..1b73bf9c 100644 --- a/src/utils/isDnfGrRule.m +++ b/src/utils/isDnfGrRule.m @@ -1,11 +1,11 @@ function tf=isDnfGrRule(rule) % isDnfGrRule Test whether a grRule is in disjunctive normal form. % -% DNF ("OR of AND-complexes") means no AND operator has an OR anywhere -% beneath it, i.e. the rule is a single gene, a pure AND-complex, or an OR -% of those. Standard RAVEN format requires DNF: subunits that must all be -% present are ANDed into a complex, and the reaction is catalysed by at -% least one such complex. +% A rule in disjunctive normal form (DNF, an OR of AND-complexes) has no OR +% operator beneath an AND operator. It is a single gene, an AND-complex, or an +% OR of genes and AND-complexes. The standard RAVEN format requires DNF: the +% subunits that must all be present are joined by AND into a complex, and the +% reaction is catalysed by at least one such complex. % % Parameters % ---------- diff --git a/src/utils/legacyMethodNotice.m b/src/utils/legacyMethodNotice.m index cfe1cdff..17734a69 100644 --- a/src/utils/legacyMethodNotice.m +++ b/src/utils/legacyMethodNotice.m @@ -1,29 +1,28 @@ function legacyMethodNotice(oldFunction, preferred) -% legacyMethodNotice Point a caller at the recommended method, once. +% legacyMethodNotice Warn once that a function has a recommended replacement. % -% For functions that remain supported but are no longer the recommended way -% to do the job. Unlike deprecationWarning, this promises no removal: the -% function keeps working and keeps being maintained. It is a signpost, not a -% countdown. +% For functions that remain supported and maintained but have a recommended +% replacement for new work. Unlike deprecationWarning, the notice announces no +% removal. % -% The notice is issued the first time the function is called in a MATLAB -% session and stays quiet afterwards, so a script that calls it in a loop -% does not bury the console. Call "clear functions" to reset. A caller that -% wants the legacy method deliberately can silence it with -% warning('off','RAVEN:legacyMethod'). +% The warning RAVEN:legacyMethod is issued at the first call of each +% oldFunction in a MATLAB session; later calls with the same oldFunction issue +% nothing. "clear functions" resets this. warning('off','RAVEN:legacyMethod') +% silences the notice. % % Parameters % ---------- % oldFunction : char -% name of the function being called. +% name of the function being called. The notice is issued once per name. % preferred : char -% what to use instead for new work, written as it would be typed. +% name of the recommended replacement for new work, written as in the +% warning text. % % Examples % -------- % legacyMethodNotice('getINITModel','ftINIT'); % -% See Also +% See also % -------- % deprecationWarning diff --git a/src/utils/parallelWorkersRAVEN.m b/src/utils/parallelWorkersRAVEN.m index dc142c8f..bd9ce7c9 100644 --- a/src/utils/parallelWorkersRAVEN.m +++ b/src/utils/parallelWorkersRAVEN.m @@ -1,29 +1,31 @@ function nW = parallelWorkersRAVEN(runParallel) % parallelWorkersRAVEN Return the parfor worker count for a given setting. % -% Returns a value for use with the parfor worker-count syntax: +% Returns the value for the maximum-workers argument of parfor: % % nW = parallelWorkersRAVEN(runParallel); % parfor (i = 1:N, nW) % ... % end % -% This avoids mutating global parallel-pool state: nW == 0 forces parfor -% to run as a plain for loop; nW == Inf lets the Parallel Computing Toolbox -% manage the pool size and auto-creation. +% The function leaves the global parallel pool unchanged. With nW == 0, parfor +% runs as a plain for loop. With nW == Inf, the Parallel Computing Toolbox +% manages the pool size and creates a pool when none exists. When +% runParallel is true but the Parallel Computing Toolbox is not installed, the +% function prints a message and returns 0. % % Parameters % ---------- % runParallel : logical -% whether the caller should use parallel workers. +% true to use parallel workers, false for sequential execution. % % Returns % ------- % nW : double -% 0 to force sequential execution (parfor behaves as a for loop, -% no pool required or created). -% Inf to use available pool workers (PCT manages pool size and -% auto-creation). +% 0 sequential execution (parfor behaves as a for loop, no pool is +% required or created). +% Inf available pool workers (the Parallel Computing Toolbox manages +% the pool size and creates a pool when none exists). if ~runParallel nW = 0; diff --git a/src/utils/parseGrRule.m b/src/utils/parseGrRule.m index 596a5694..7ece12f9 100644 --- a/src/utils/parseGrRule.m +++ b/src/utils/parseGrRule.m @@ -1,16 +1,15 @@ function tree=parseGrRule(rule) % parseGrRule Parse a grRule into a syntax tree. % -% Parses a gene-protein-reaction rule into a tree of AND/OR/gene nodes, so -% that callers can reason about its structure instead of searching the raw -% string. Gene IDs are matched as whole tokens, so IDs that contain "and" or -% "or" as a substring (RAND1), or that are prefixes of one another (10 and -% 100), are never confused with operators or with each other. +% Parses a gene-protein-reaction rule into a tree of AND, OR and gene nodes. +% Gene IDs are matched as whole tokens, so IDs that contain "and" or "or" as a +% substring (RAND1), or that are prefixes of one another (10 and 100), are +% distinct from operators and from each other. % % Parameters % ---------- % rule : char or string -% a grRule, e.g. "(G1 and G2) or G3". Both the word forms ("and", "or", +% a grRule, for example "(G1 and G2) or G3". Both the word forms ("and", "or", % any case) and the symbol forms ("&", "&&", "|", "||") are accepted. % An empty rule yields an empty tree. % @@ -19,23 +18,22 @@ % tree : struct % a scalar struct with fields: % -% - type : char — 'gene', 'and' or 'or'. -% - id : char — the gene ID; '' for 'and'/'or' nodes. -% - children : cell — child nodes; {} for 'gene' nodes. +% - type : char, 'gene', 'and' or 'or'. +% - id : char, the gene ID; '' for 'and' and 'or' nodes. +% - children : cell, the child nodes; {} for 'gene' nodes. % % An empty rule returns a 0x0 struct array, for which isempty is true. % % Notes % ----- -% The grammar is the usual precedence, with AND binding tighter than OR: +% AND binds tighter than OR. The grammar is: % % expr := term ( OR term )* % term := factor ( AND factor )* % factor := gene | '(' expr ')' % -% Malformed rules raise RAVEN:badGrRule rather than being silently -% misparsed. Callers that lint user input (findPotentialErrors) catch this -% and report it instead of failing. +% Malformed rules raise the error RAVEN:badGrRule. findPotentialErrors catches +% this error and reports the rule. % % Examples % -------- diff --git a/src/utils/parseRAVENargs.m b/src/utils/parseRAVENargs.m index 1910be9d..0a5e557e 100644 --- a/src/utils/parseRAVENargs.m +++ b/src/utils/parseRAVENargs.m @@ -1,18 +1,17 @@ function args = parseRAVENargs(rawArgs, spec) % parseRAVENargs Resolve optional arguments passed positionally or by name. % -% Helper that lets a RAVEN function accept its optional arguments either in -% the traditional positional order, as name-value pairs, or as a mix of -% leading positional values followed by name-value pairs. The required -% leading arguments stay explicit in the function signature; the optional -% tail is collected into varargin and passed here together with a -% specification of the optional parameters. +% Helper for RAVEN functions that accept optional arguments in positional +% order, as name-value pairs, or as leading positional values followed by +% name-value pairs. The required leading arguments are explicit in the function +% signature. The optional arguments are collected in varargin and passed to +% this function together with a specification of the optional parameters. % % Parameters % ---------- % rawArgs : cell -% the varargin of the function, i.e. whatever was supplied after the required -% positional arguments. +% the varargin of the function, holding the arguments supplied after the +% required positional arguments. % spec : cell % an N-by-2 or N-by-3 cell array describing the optional parameters, one % per row: @@ -20,9 +19,9 @@ % - column 1 : parameter name (char). % - column 2 : default value, used when the parameter is not supplied. % - column 3 : optional validator, a function handle that is called with -% the resolved value (including the default, when the parameter was not -% supplied) and should error on an invalid value, e.g. @mustBeNumeric. -% Use [] for no validation. +% the resolved value (the default when the parameter was not supplied) +% and should error on an invalid value, for example @mustBeNumeric. [] means no +% validation. % % Returns % ------- @@ -31,27 +30,27 @@ % % Notes % ----- -% Calling convention is resolved as follows: +% The calling convention is resolved in these steps: % % 1. If rawArgs is empty, all parameters take their defaults. -% 2. The first element in rawArgs that is a string matching a known -% parameter name marks position k. Everything before k is treated -% as positional (assigned left-to-right by the order in spec). -% Everything from k onward must form valid name-value pairs: an even -% count where every name-position element is a known parameter name. -% 3. If no such position exists (no element is a matching string), or the -% trailing section from k does not form valid name-value pairs, the -% entire rawArgs is treated as positional. +% 2. The first element in rawArgs that is a string matching a parameter +% name (case-insensitive) marks position k. The elements before k are +% positional and are assigned in the order of spec. The elements from k +% onward must form valid name-value pairs: an even count in which every +% name-position element is a parameter name. +% 3. If no element is a matching string, or the elements from k do not form +% valid name-value pairs, all of rawArgs is positional. % -% This means three styles are accepted interchangeably: +% Three styles are accepted: % % f(model, v1, v2) % purely positional % f(model, "p1", v1, "p2", v2) % purely named % f(model, v1, "p2", v2, "p3", v3) % hybrid: v1 positional, rest named % -% When a positional value could itself be a string that equals a parameter -% name, use the explicit name-value form for that argument to avoid -% ambiguity. +% A positional value that is a string equal to a parameter name is read as a +% parameter name only when the arguments from there on form valid name-value +% pairs; otherwise all arguments are positional. The name-value form passes +% such a value unambiguously. % % Examples % -------- @@ -62,7 +61,7 @@ % fileName = p.fileName; % sortIds = p.sortIds; % -% % the caller may use any of these: +% % the caller can use any of these: % exportToExcelFormat(model, "model.xlsx", true) % positional % exportToExcelFormat(model, "sortIds", true) % named % exportToExcelFormat(model, "model.xlsx", "sortIds", true) % hybrid diff --git a/src/utils/printOrange.m b/src/utils/printOrange.m index 7611e23b..a72fd7bb 100755 --- a/src/utils/printOrange.m +++ b/src/utils/printOrange.m @@ -1,14 +1,16 @@ function orangeString = printOrange(stringToPrint) % printOrange Print an orange-coloured string to the MATLAB Command Window. % -% Prints stringToPrint in orange colour to the MATLAB Command Window. Only -% works if MATLAB is open with a GUI; it does not work with command-line -% MATLAB. +% Prints stringToPrint in orange colour to the MATLAB Command Window. The +% colour requires the MATLAB desktop; in command-line MATLAB the text is +% printed without colour. When called without an output argument, the text is +% wrapped to the width of the Command Window and printed. With an output +% argument, nothing is printed. % % Parameters % ---------- % stringToPrint : char -% string that should be printed in orange colour. "\n" marks a line +% string to print in orange colour. "\n" marks a line % break, as in fprintf; no other escape sequence or format directive % is interpreted, so text containing "%" prints as-is. % diff --git a/src/utils/progressReport.m b/src/utils/progressReport.m index f02d13c0..b4d191e1 100644 --- a/src/utils/progressReport.m +++ b/src/utils/progressReport.m @@ -1,35 +1,36 @@ classdef progressReport < handle % progressReport Universal progress reporting for RAVEN functions. % -% A single progress-reporting API used across RAVEN. The rendering backend -% is selected automatically so that the same call works on an interactive -% desktop, a plain command-line session and a headless server, and is -% silenced during unit tests: +% Progress-reporting class used by RAVEN functions. The rendering backend is +% selected automatically. The same calls work on an interactive desktop, in a +% command-line session and on a headless server. During unit tests no output +% is produced. The backends are: % % - 'gui' : MATLAB waitbar (interactive desktop). % - 'cli' : animated command-line bar (interactive terminal). -% - 'log' : plain milestone lines, e.g. "Running BLAST: 30%". Contains no -% control characters, so it stays readable in redirected logs -% and on headless / -batch servers. +% - 'log' : plain milestone lines, for example "Running BLAST: 30%", printed +% every 10%. The lines contain no control characters, so they +% are readable in redirected logs and on headless and -batch +% servers. % - 'none' : no output (during tests, or when disabled). % -% The backend can be forced with setRavenProgress, e.g. setRavenProgress('log') -% on a compute cluster, or setRavenProgress('off') to silence all progress -% reporting. +% setRavenProgress sets the backend: setRavenProgress('log') selects plain +% lines, for example on a compute cluster, and setRavenProgress('off') +% disables all progress reporting. % % Usage % ----- -% For loops with one cheap-to-expensive iteration each, count one per pass: +% To register each iteration, call count once per pass: % % PB = progressReport(N, 'Task name'); % before the loop % for i = 1:N % ... % loop body % PB.count; % or count(PB), also in parfor % end -% PB.done; % optional; cleans up on early exit +% PB.done; % optional; finalises the bar on early exit % -% For very long loops over cheap iterations, set the absolute position at -% intervals to avoid per-iteration overhead: +% To avoid the per-iteration overhead in long loops of short iterations, set +% the absolute position at intervals: % % PB = progressReport(N, 'Task name'); % for i = 1:N @@ -43,7 +44,8 @@ % Parameters % ---------- % N : double -% number of iterations the loop will perform (a positive integer). +% number of iterations the loop performs (a positive integer). For any other +% value, no progress is shown. % taskName : char, optional % label shown alongside the progress (default ''). % diff --git a/src/utils/ravenList.m b/src/utils/ravenList.m index 0d5d2af3..60936b5b 100644 --- a/src/utils/ravenList.m +++ b/src/utils/ravenList.m @@ -1,20 +1,23 @@ function msg = ravenList(header, items, trim) -% ravenList Format a header and item list for warning() or error(). +% ravenList Format a header and a list of items for warning() or error(). % % Parameters % ---------- % header : char % message header string. % items : cell -% cell array of items to list below the header. +% cell array of items, listed one per line after the header. % trim : logical -% cap the list at 10 items (default true). +% true to limit the list to 10 lines (default true). When the list has more +% than 10 items, the tenth line reads '...and N more' and replaces items +% 10 to the end, with N the number of replaced items. % % Returns % ------- % msg : char -% header + newline + tab-indented items, ready to pass to warning() or -% error() as the format string. +% header, a newline, and the items separated by newlines with a tab before +% each item. If items is empty, msg is header. Passed to warning() or +% error() as an argument after the format '%s'. % % Examples % -------- diff --git a/src/utils/ravenModelFields.m b/src/utils/ravenModelFields.m index 32654108..95654c63 100644 --- a/src/utils/ravenModelFields.m +++ b/src/utils/ravenModelFields.m @@ -1,20 +1,21 @@ function reg = ravenModelFields() % ravenModelFields Declarative registry of all RAVEN model struct fields. % -% Returns a struct array. Each element describes one field: +% Returns a struct array with one element per field. The elements have the +% fields: % .name - field name (char) -% .type - entity type: 'rxn', 'met', 'gene', or 'comp' (char) +% .type - entity type: 'rxn', 'met', 'gene' or 'comp' (char) % .default - default value when padding new entries % -% Only 1-D (vector-per-entity) fields are listed here. Fields that require -% custom 2-D indexing or value-remapping are excluded and must be handled -% explicitly by callers: +% Only 1-D (vector-per-entity) fields are listed. Fields that need 2-D +% indexing or value remapping are excluded, and callers handle them +% explicitly: % % S - sparse (mets x rxns); use S(:,perm) for rxns, S(perm,:) for mets % rxnGeneMat - sparse (rxns x genes); use rxnGeneMat(perm,:) or rxnGeneMat(:,perm) % b - double (mets x N), may be 2-D; use b(perm,:) -% metComps, rxnComps, geneComps - when permuting comps, their VALUES must -% be remapped (not the arrays themselves permuted) +% metComps, rxnComps, geneComps - when the compartments are permuted, the +% values of these arrays are remapped; the arrays are not permuted rows = { % name type default diff --git a/src/utils/runRAVENtests.m b/src/utils/runRAVENtests.m index 6801e027..a93f6958 100644 --- a/src/utils/runRAVENtests.m +++ b/src/utils/runRAVENtests.m @@ -1,8 +1,9 @@ function testResults = runRAVENtests % runRAVENtests Run all RAVEN function tests. % -% Runs all unit tests found at RAVEN/test/function_tests, and prints output in -% the command window. +% Runs all unit tests found in the folder tests/function_tests of the RAVEN +% root folder, except the abstract base class RavenTestCase, and prints the +% output in the command window. % % Returns % ------- diff --git a/src/utils/setRavenProgress.m b/src/utils/setRavenProgress.m index 58b423c5..29f72174 100644 --- a/src/utils/setRavenProgress.m +++ b/src/utils/setRavenProgress.m @@ -2,25 +2,26 @@ function setRavenProgress(mode) % setRavenProgress Set the RAVEN progress-reporting backend. % % Sets the preference that progressReport uses to decide how progress is -% shown. The setting is persistent across MATLAB sessions. +% shown. The setting is stored as the RAVEN preference progressBar and +% persists across MATLAB sessions. % % Parameters % ---------- % mode : char % one of: % -% - 'auto' : choose automatically (default). GUI on an interactive -% desktop, an animated bar in an interactive terminal, plain log lines -% on a headless / -batch server, and no output during unit tests. +% - 'auto' : choose automatically (default): 'gui' on the MATLAB desktop, +% 'cli' in a terminal, 'log' on a -batch or deployed session, and no +% output during unit tests. % - 'gui' : always use a MATLAB waitbar. % - 'cli' : always use the animated command-line bar. -% - 'log' : always print plain milestone lines (safe in redirected -% logs and on headless servers). -% - 'none' / 'off' : never show progress. +% - 'log' : always print plain milestone lines, which are readable in +% redirected logs and on headless servers. +% - 'none' or 'off' : never show progress. % % Examples % -------- -% setRavenProgress('log'); % e.g. on a compute cluster +% setRavenProgress('log'); % for example on a compute cluster % setRavenProgress('off'); % silence all progress reporting % setRavenProgress('auto'); % restore the default behaviour %