Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@
* `getModelFromHomology` with `preferredOrder` treats a gene of a later model that maps to a new gene an earlier model already maps as a subunit without an ortholog, and `complexPolicy` decides what happens to it (was: the gene and every part of the rule that needs it were removed). For the rule `(a and b) or x` with `a` taken by an earlier model, `flag` gives `(OLD_MODELID_a and nb) or nx`, `keep` gives `nb or nx` and `drop` gives `nx`. A reaction that has genes, none of which keeps a mapping, is not included.
* `getModelFromHomology` with `complexPolicy` `drop` removes each complex that has a subunit without an ortholog, and removes the reaction only when no complex remains (was: the reaction was removed as soon as one subunit had no ortholog). For the rule `(A and B) or (C and D)` without an ortholog of `B`, the draft has the orthologs of `C` and `D`.

### Experiments

* New: the `experiments/` folder scores a model against measured growth rates and exchange fluxes. `loadFluxData` reads one flux file, with a `weight` column for the weight of each condition, and `loadExperimentData` reads `fluxData.tsv`, `maxGrowth.tsv` and `zeroFlux.tsv` from a folder. `simulateConditions` fixes the uptake of each condition and solves the model; the anaerobic switch, the change of the protein content and the solver call are given as function handles. `computeCarbonWeights` gives the carbon weight of each reaction, `datasetRmse` and `experimentDistance` combine the carbon-weighted errors of the flux and maximum growth conditions into one value, and `applyFluxDataConstraints` bounds the exchange fluxes of a model to one condition.

### Fixes

* `getModelFromHomology` reads the rule as a tree, in which `and` binds tighter than `or`, when it removes the placeholder genes of isozymes without an ortholog (was: it removed a placeholder that stood beside an `or` token, also when the placeholder belongs to a complex). A placeholder in an `or` group is removed when the group has a member that is not a placeholder, in nested groups as well. For the rule `(A or B and C) and D` without an ortholog of `B`, where `nA`, `nC` and `nD` are the orthologs of `A`, `C` and `D`, the draft rule is `(nA or (OLD_T_B and nC)) and nD` under `flag`, `(nA or nC) and nD` under `keep` and `nA and nD` under `drop`; it was `nA and nC and nD` under all three. The result differs from before only for rules with unbracketed `and` and `or` or with nested `or` groups.
Expand Down
164 changes: 164 additions & 0 deletions src/experiments/applyFluxDataConstraints.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
function model = applyFluxDataConstraints(model, fluxData, bioRxnId, varargin)
% applyFluxDataConstraints Constrain the exchange fluxes of a model to one condition.
%
% Sets the bounds of the biomass reaction to the measured growth rate and the
% bounds of each exchange reaction of fluxData to its measured flux in the
% chosen condition. An exchange without a measurement (NaN) is left as it
% is. A flux of -1000 or 1000 means unconstrained, whatever the setting of
% looseStrictFlux: -1000 gives the bounds -1000 and 0 (free uptake), and 1000
% gives 0 and 1000 (free excretion).
%
% Parameters
% ----------
% model : struct
% model with the exchange reactions of fluxData. Not changed; the
% constrained model is returned.
% fluxData : struct
% flux data, as returned by loadFluxData.
% bioRxnId : char
% id of the biomass reaction.
%
% Name-Value Arguments
% --------------------
% condition : double or char
% index of the condition in fluxData.conds (counted from 1), or its name
% (default 1).
% maxMinGrowth : char
% 'max' sets the upper bound of the biomass reaction to the measured
% growth rate and the lower bound to 0; 'min' sets the lower bound to the
% growth rate and the upper bound to 1000, which suits the minimisation
% of a resource such as the protein pool (default 'max').
% looseStrictFlux : char or double
% how tightly the exchange fluxes are constrained (default 'loose'):
%
% - 'loose' : one bound is 0 and the other the measured flux, which
% allows zero flux.
% - 0-100 : the bounds are set around the measured flux with this
% percentage in total, so 10 gives 0.95 and 1.05 times the flux. This
% forces a flux through the reaction.
% cSource : char
% id of the preferred carbon source uptake reaction. Its bounds are set
% to 0 and 0 before the flux data is applied, so that the data alone
% determines the carbon source. [] or '' blocks no reaction, and a
% reaction that is not in the model is ignored (default []).
%
% Returns
% -------
% model : struct
% model with the constrained fluxes.
%
% Notes
% -----
% The function raises applyFluxDataConstraints:invalidMaxMinGrowth,
% applyFluxDataConstraints:invalidLooseStrictFlux,
% applyFluxDataConstraints:unknownCondition (a name that is not in
% fluxData.conds), applyFluxDataConstraints:conditionOutOfRange and
% applyFluxDataConstraints:missingReaction (an exchange reaction of fluxData
% that is not in the model, or the biomass reaction).
%
% Examples
% --------
% model = applyFluxDataConstraints(model, fluxData, 'growth');
% model = applyFluxDataConstraints(model, fluxData, 'growth', ...
% 'condition', 'glucose', 'looseStrictFlux', 10, 'cSource', 'EX_glc');
%
% See also
% --------
% loadFluxData, simulateConditions

p = parseRAVENargs(varargin, { ...
'condition', 1; ...
'maxMinGrowth', 'max'; ...
'looseStrictFlux', 'loose'; ...
'cSource', []});
condition = p.condition;
maxMinGrowth = p.maxMinGrowth;
looseStrictFlux = p.looseStrictFlux;
cSource = p.cSource;

if ~(ischar(maxMinGrowth) && any(strcmp(maxMinGrowth, {'max','min'})))
error('applyFluxDataConstraints:invalidMaxMinGrowth', ...
'maxMinGrowth must be ''max'' or ''min''.');
end
isLoose = ischar(looseStrictFlux) && strcmp(looseStrictFlux, 'loose');
if ~(isLoose || (isnumeric(looseStrictFlux) && isscalar(looseStrictFlux) ...
&& looseStrictFlux >= 0 && looseStrictFlux <= 100))
error('applyFluxDataConstraints:invalidLooseStrictFlux', ...
'looseStrictFlux must be ''loose'' or a number in [0, 100].');
end

if ischar(condition) || isstring(condition)
condIdx = find(strcmp(fluxData.conds, char(condition)), 1);
if isempty(condIdx)
error('applyFluxDataConstraints:unknownCondition', ...
'Condition %s is not in fluxData.conds.', char(condition));
end
else
if ~(isscalar(condition) && condition >= 1 && condition <= numel(fluxData.conds) ...
&& condition == round(condition))
error('applyFluxDataConstraints:conditionOutOfRange', ...
'Condition index %g is out of range (fluxData has %d condition(s)).', ...
condition, numel(fluxData.conds));
end
condIdx = condition;
end

[found, exchIdx] = ismember(fluxData.exchRxnIDs, model.rxns);
if ~all(found)
missing = fluxData.exchRxnIDs(~found);
error('applyFluxDataConstraints:missingReaction', ...
'%d exchange reaction(s) of fluxData are not in the model (examples: %s).', ...
numel(missing), strjoin(missing(1:min(5, end)), ', '));
end
bioIdx = find(strcmp(model.rxns, bioRxnId));
if isempty(bioIdx)
error('applyFluxDataConstraints:missingReaction', ...
'The biomass reaction %s is not in the model.', bioRxnId);
end

if ~isempty(cSource)
cIdx = find(strcmp(model.rxns, cSource));
model.lb(cIdx) = 0;
model.ub(cIdx) = 0;
end

growth = fluxData.grRate(condIdx);
if strcmp(maxMinGrowth, 'max')
model.lb(bioIdx) = 0;
model.ub(bioIdx) = growth;
else
model.lb(bioIdx) = growth;
model.ub(bioIdx) = 1000;
end

fluxes = fluxData.exchFluxes(condIdx, :);
for k = 1:numel(fluxes)
flux = fluxes(k);
if isnan(flux)
continue
end
idx = exchIdx(k);
if abs(flux) == 1000
if flux == -1000
model.lb(idx) = -1000;
model.ub(idx) = 0;
else
model.lb(idx) = 0;
model.ub(idx) = 1000;
end
elseif isLoose
if flux < 0
model.lb(idx) = flux;
model.ub(idx) = 0;
else
model.lb(idx) = 0;
model.ub(idx) = flux;
end
else
lo = flux * (1 - looseStrictFlux / 200);
hi = flux * (1 + looseStrictFlux / 200);
model.lb(idx) = min(lo, hi);
model.ub(idx) = max(lo, hi);
end
end
end
103 changes: 103 additions & 0 deletions src/experiments/computeCarbonWeights.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
function carbonWeights = computeCarbonWeights(model, rxnIds, bioRxnId)
% computeCarbonWeights Carbon weight of each reaction for the distance to measurements.
%
% The distance between simulated and measured fluxes compares fluxes of
% different metabolites, so each exchange flux is multiplied by the number of
% carbon atoms of the metabolite it exchanges, which gives Cmmol/gDCWh. The
% growth rate is put on the same scale with the assumed carbon content of
% biomass, 41 Cmmol/gDCW.
%
% Parameters
% ----------
% model : struct
% model that provides the metabolite formulas (metFormulas).
% rxnIds : cell
% reaction ids to compute weights for, typically the exchange reactions
% of the datasets, the zero-flux reactions and the biomass reaction.
% bioRxnId : char
% id of the biomass reaction.
%
% Returns
% -------
% carbonWeights : containers.Map
% weight per reaction id. The biomass reaction gets 41. Every other
% reaction gets the number of carbon atoms in the formula of its single
% exchanged metabolite. A reaction with more than one metabolite, a
% metabolite without a formula and a metabolite with 0 carbon atoms (O2,
% water) get the weight 1, so their flux mismatches still count in the
% distance.
%
% Notes
% -----
% A model without formulas gives every exchange the weight 1 and a warning
% (computeCarbonWeights:noFormulas). A reaction that is not in the model
% raises computeCarbonWeights:missingReaction.
%
% Examples
% --------
% carbonWeights = computeCarbonWeights(model, {'EX_glc','EX_etoh','growth'}, 'growth');
% carbonWeights('EX_glc')
%
% See also
% --------
% datasetRmse, experimentDistance

rxnIds = cellstr(rxnIds);
biomassCarbon = 41; % Cmmol/gDCW, assumed carbon content of biomass

if ~isfield(model, 'metFormulas') || all(cellfun(@isempty, model.metFormulas))
warning('computeCarbonWeights:noFormulas', ...
'The model has no metabolite formulas; every exchange reaction gets the weight 1.');
formulas = repmat({''}, numel(model.mets), 1);
else
formulas = model.metFormulas;
end

[found, rxnIdx] = ismember(rxnIds, model.rxns);
if ~all(found)
error('computeCarbonWeights:missingReaction', ...
'The reactions %s are not in the model.', strjoin(rxnIds(~found), ', '));
end

carbonWeights = containers.Map('KeyType', 'char', 'ValueType', 'double');
for i = 1:numel(rxnIds)
if strcmp(rxnIds{i}, bioRxnId)
carbonWeights(rxnIds{i}) = biomassCarbon;
continue
end
mets = find(model.S(:, rxnIdx(i)));
value = 1;
if numel(mets) == 1
carbon = carbonAtoms(formulas{mets});
if ~isnan(carbon) && carbon ~= 0
value = carbon;
end
end
carbonWeights(rxnIds{i}) = value;
end
end

function carbon = carbonAtoms(formula)
% Number of carbon atoms in a formula, NaN when the formula has no carbon or
% cannot be read as a plain list of elements and counts.
carbon = NaN;
if isempty(formula)
return
end
tokens = regexp(formula, '([A-Z][a-z]?)(\d*\.?\d*)', 'tokens');
if isempty(tokens) || ~strcmp(strjoin(cellfun(@(t) [t{1} t{2}], tokens, 'UniformOutput', false), ''), formula)
return
end
for i = 1:numel(tokens)
if strcmp(tokens{i}{1}, 'C')
count = str2double(tokens{i}{2});
if isnan(count)
count = 1;
end
if isnan(carbon)
carbon = 0;
end
carbon = carbon + count;
end
end
end
112 changes: 112 additions & 0 deletions src/experiments/datasetRmse.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
function [rmse, rmseList] = datasetRmse(fluxData, sims, constrain, carbonWeights, bioRxnId, varargin)
% datasetRmse Carbon-weighted distance between a simulated and a measured dataset.
%
% For each condition the root mean square error is computed over the
% carbon-weighted growth rate, and if constrain is true also over the
% carbon-weighted measured exchange fluxes and the zero-flux reactions. A
% zero-flux reaction that is simulated at exactly 0 is left out so that
% correct predictions do not dilute the error. An infeasible condition gets
% a fixed penalty. The distance of the dataset is the mean of the errors of
% its conditions, each multiplied by the weight of the condition if the data
% has one.
%
% Parameters
% ----------
% fluxData : struct
% dataset that was simulated, as returned by loadFluxData.
% sims : struct
% simulation result of the dataset, from simulateConditions.
% constrain : logical
% must be the value that was given to simulateConditions: true includes
% the exchange flux terms (flux data), false scores the growth alone
% (maximum growth data).
% carbonWeights : containers.Map
% weights from computeCarbonWeights. A reaction that is not in the map
% gets the weight 1.
% bioRxnId : char
% id of the biomass reaction. It is not read at the moment; the growth
% rate of the simulation is taken from sims.
%
% Name-Value Arguments
% --------------------
% penalty : double
% error of an infeasible condition (default 99). It must dominate the
% errors of feasible conditions.
%
% Returns
% -------
% rmse : double
% weighted mean of the errors of the conditions.
% rmseList : double
% error of each condition, with the penalty but before weighting.
%
% Notes
% -----
% A sims with another number of elements than fluxData has conditions raises
% datasetRmse:wrongSimCount.
%
% Examples
% --------
% [rmse, rmseList] = datasetRmse(fluxData, sims, true, carbonWeights, 'growth');
%
% See also
% --------
% computeCarbonWeights, simulateConditions, experimentDistance

p = parseRAVENargs(varargin, {'penalty', 99});
penalty = p.penalty;
biomassCarbon = 41; % Cmmol/gDCW, assumed carbon content of biomass

n = numel(fluxData.conds);
if numel(sims) ~= n
error('datasetRmse:wrongSimCount', ...
'sims has %d elements; expected %d to match fluxData.conds.', numel(sims), n);
end

rmseList = zeros(n, 1);
for i = 1:n
sim = sims(i);
if ~sim.feasible
rmseList(i) = penalty;
continue
end
bioMeas = fluxData.grRate(i) * biomassCarbon;
bioSim = sim.growth * biomassCarbon;
if ~constrain
rmseList(i) = abs(bioMeas - bioSim);
continue
end

measured = bioMeas;
simulated = bioSim;
for k = 1:numel(sim.exchRxnIDs)
w = weightOf(carbonWeights, sim.exchRxnIDs{k});
col = find(strcmp(fluxData.exchRxnIDs, sim.exchRxnIDs{k}), 1);
measured(end+1) = w * fluxData.exchFluxes(i, col); %#ok<AGROW>
simulated(end+1) = w * sim.exchFluxes(k); %#ok<AGROW>
end
for k = 1:numel(sim.blockRxnIDs)
weightedSim = weightOf(carbonWeights, sim.blockRxnIDs{k}) * sim.blockFluxes(k);
if weightedSim == 0
continue
end
measured(end+1) = 0; %#ok<AGROW>
simulated(end+1) = weightedSim; %#ok<AGROW>
end
rmseList(i) = sqrt(mean((measured - simulated).^2));
end

weighted = rmseList;
if isfield(fluxData, 'weight') && ~isempty(fluxData.weight)
weighted = rmseList .* fluxData.weight(:);
end
rmse = mean(weighted);
end

function w = weightOf(carbonWeights, rxnId)
if isKey(carbonWeights, rxnId)
w = carbonWeights(rxnId);
else
w = 1;
end
end
Loading
Loading