diff --git a/src/gather_kcats/kcatEvidence.m b/src/gather_kcats/kcatEvidence.m new file mode 100644 index 00000000..991ededa --- /dev/null +++ b/src/gather_kcats/kcatEvidence.m @@ -0,0 +1,294 @@ +function [evidence, summary, rows] = kcatEvidence(model, varargin) +% kcatEvidence Show the kcats that every source gives for selected reactions. +% +% For each selected model.ec reaction, reads the kcat of every source file +% in data/kcats (see loadKcatSource) and puts it next to the kcat that the +% model has now and, for a tuned kcat, the kcat before tuning. The +% reactions are selected with rxns, enzymes and tunedKcats; a reaction that +% any of them selects is included. Without a selection, all model.ec +% reactions are included; a selection that is given and empty (for example +% no relaxed enzymes) selects none. +% +% The EC-tree estimate can be computed for the selected reactions (compute). +% The source files are only read, never changed. A row of a source file +% without a valid kcat (missing, 0 or not a number) is left out by +% loadKcatSource, which reports it; the source then has no value for the +% reaction. +% +% Name-Value Arguments +% -------------------- +% rxns : cell, char, double or logical +% reactions to include: names of model.ec.rxns or conventional reaction +% names (see getEcRxnKeys; a reverse direction is named with _REV), or +% indices or a logical vector over model.ec.rxns. +% enzymes : cell +% UniProt accessions; every reaction catalysed by one of them is +% included. flexEnz.uniprotIDs, the result of flexibilizeEnzConcs or +% relaxEnzConcs, gives the enzymes whose measured concentration was +% relaxed. +% tunedKcats : struct +% the tuned kcats returned by sensitivityTuning; the model is the one +% it returned. +% sources : cell +% names of the source files, without .tsv (default: all files in +% data/kcats, including the okp___query.tsv files that +% kcatsForReactions wrote; {} for none). +% compute : cell +% sources to compute for the selected reactions. 'ec_tree' is the one +% that is supported (default none). The computed estimate replaces a +% source file of the same name, so it follows measurements and +% [kcat_sources.ec_tree] k of the model adapter (default 5) and is not +% outdated. +% measurements : struct +% BRENDA measurement table for the EC-tree estimate (default: +% loadBrendaMeasurements). +% saveAs : char +% path of a tab-separated file to write summary to (default: none). +% modelAdapter : ModelAdapter +% a loaded model adapter (default: the current default model adapter). +% +% Returns +% ------- +% evidence : table +% one row per kcat of a source, with the variables ecRxn (model.ec.rxns), +% kcat, source, substrate, detail and assigned (true when the kcat is the +% one that was assigned to the reaction: the kcat before tuning for a +% tuned reaction, and the current kcat otherwise). +% summary : table +% one row per selected reaction, with the variables ecRxn, kcat +% (current), tuned (logical), fold (kcat divided by prior; NaN without a +% positive prior), prior (the kcat before the first tuning, NaN when +% untuned), origin (the origin in model.ec.source), enzymes, eccodes and +% one variable src_ per source, in alphabetical order of the +% source names, with the median of the kcats of that +% source for the reaction (NaN without one). A conventional reaction name +% in rxns or tunedKcats selects every isozyme row of the reaction, as +% tunedKcats names the reactions of a light ecModel by their conventional +% name. +% rows : double +% the selected indices of model.ec.rxns. +% +% Examples +% -------- +% [model, tunedKcats] = sensitivityTuning(model); +% [~, summary] = kcatEvidence(model, 'tunedKcats', tunedKcats); +% [~, summary] = kcatEvidence(model, 'rxns', {'MAR03905'}, 'compute', {'ec_tree'}); +% [~, summary] = kcatEvidence(model, 'enzymes', flexEnz.uniprotIDs); +% +% See also +% -------- +% loadKcatSource, kcatsFromECTree, kcatsForReactions, sensitivityTuning + +checkOptions(varargin, {'rxns','enzymes','tunedKcats','sources','compute','measurements','saveAs','modelAdapter'}, 'kcatEvidence'); +p = parseGECKOargs(varargin, { ... + 'rxns', []; ... + 'enzymes', []; ... + 'tunedKcats', []; ... + 'sources', []; ... + 'compute', {}; ... + 'measurements', []; ... + 'saveAs', ''; ... + 'modelAdapter', []}); +modelAdapter = p.modelAdapter; +if isempty(modelAdapter) + modelAdapter = ModelAdapterManager.getDefault(); + if isempty(modelAdapter) + error('Either send in a modelAdapter or set the default model adapter in the ModelAdapterManager.') + end +end +compute = {}; +if ~isempty(p.compute) + compute = cellstr(p.compute); +end +unknown = setdiff(compute, {'ec_tree'}); +if ~isempty(unknown) + error('kcatEvidence:compute', 'Cannot compute %s; supported: ec_tree.', strjoin(unknown, ', ')) +end + +given = cellfun(@char, varargin(1:2:end), 'UniformOutput', false); +rows = selectRows(model, p.rxns, p.enzymes, p.tunedKcats, ismember({'rxns','enzymes','tunedKcats'}, given)); +nRows = numel(rows); + +kcatDir = fullfile(modelAdapter.params.path, 'data', 'kcats'); +sources = p.sources; +explicit = ~(isnumeric(sources) && isempty(sources)); +if isnumeric(sources) && isempty(sources) + files = dir(fullfile(kcatDir, '*.tsv')); + sources = sort(cellfun(@(f) f(1:end-4), {files.name}, 'UniformOutput', false)); +end +sources = unique(cellstr(sources), 'stable'); +if ismember('ec_tree', compute) + sources = sources(~strcmp(sources, 'ec_tree')); +end + +ecRxn = cell(0, 1); source = cell(0, 1); kcat = zeros(0, 1); +substrate = cell(0, 1); detail = cell(0, 1); +isFile = true(size(sources)); +for s = 1:numel(sources) + try + kcatList = loadKcatSource(model, sources{s}, 'modelAdapter', modelAdapter); + catch err + if explicit + rethrow(err) + end + printOrange(sprintf('%s is not read: %s\n', sources{s}, err.message)); % a file of the default list that is no source file + isFile(s) = false; + continue + end + [keep, ~] = ismember(kcatList.rxns, model.ec.rxns(rows)); + n = nnz(keep); + ecRxn = [ecRxn; kcatList.rxns(keep)]; %#ok + source = [source; repmat(sources(s), n, 1)]; %#ok + kcat = [kcat; kcatList.kcats(keep)]; %#ok + substrate = [substrate; fieldOrEmpty(kcatList, 'substrates', keep)]; %#ok + detail = [detail; fieldOrEmpty(kcatList, 'detail', keep)]; %#ok +end +sources = sources(isFile); +if ismember('ec_tree', compute) + sources = [sources(:); {'ec_tree'}]; +end +if ismember('ec_tree', compute) && nRows > 0 + config = kcatAssignmentConfig(modelAdapter.params); + k = 5; + if isfield(config.sources, 'ec_tree') && isfield(config.sources.ec_tree, 'k') + k = double(config.sources.ec_tree.k); + end + tree = kcatsFromECTree(model, 'k', k, 'ecRxns', rows, 'save', false, 'measurements', p.measurements, ... + 'modelAdapter', modelAdapter); + n = numel(tree.rxns); + ecRxn = [ecRxn; tree.rxns(:)]; + source = [source; repmat({'ec_tree'}, n, 1)]; + kcat = [kcat; tree.kcats(:)]; + substrate = [substrate; repmat({''}, n, 1)]; + detail = [detail; tree.detail(:)]; +end + +info = parseKcatSource(model.ec.source(rows)); +if nRows == 0 + info = struct('origin', {}, 'prior', {}, 'tuned', {}); +end +current = model.ec.kcat(rows); +current = current(:); +prior = reshape([info.prior], [], 1); +tuned = ~isnan(prior) | reshape(~cellfun(@isempty, {info.tuned}), [], 1); +reference = current; +reference(~isnan(prior)) = prior(~isnan(prior)); + +[~, at] = ismember(ecRxn, model.ec.rxns(rows)); +assigned = at > 0 & abs(log(kcat ./ reference(max(at, 1)))) < 1e-5; +evidence = table(ecRxn, kcat, source, substrate, detail, assigned); + +fold = nan(nRows, 1); +positive = prior > 0; +fold(positive) = current(positive) ./ prior(positive); +enzymes = cell(nRows, 1); +for i = 1:nRows + enzymes{i} = strjoin(model.ec.enzymes(model.ec.rxnEnzMat(rows(i), :) ~= 0)', ';'); +end +eccodes = model.ec.eccodes(rows); +eccodes = cellfun(@joinCodes, eccodes(:), 'UniformOutput', false); +summary = table(reshape(model.ec.rxns(rows), [], 1), current, tuned, fold, prior, ... + reshape({info.origin}, [], 1), enzymes, eccodes, ... + 'VariableNames', {'ecRxn', 'kcat', 'tuned', 'fold', 'prior', 'origin', 'enzymes', 'eccodes'}); +[~, bySource] = sort(lower(sources)); +for s = reshape(bySource, 1, []) + values = nan(nRows, 1); + isSource = strcmp(source, sources{s}); + [~, at] = ismember(ecRxn(isSource), summary.ecRxn); + if any(isSource) + values = accumarray(at, kcat(isSource), [nRows 1], @median, NaN); + end + summary.(matlab.lang.makeValidName(['src_' sources{s}])) = values; +end + +if ~isempty(p.saveAs) + writetable(summary, char(p.saveAs), 'FileType', 'text', 'Delimiter', '\t'); +end +end + +function rows = selectRows(model, rxns, enzymes, tunedKcats, given) +% Indices of the model.ec rows that rxns, enzymes or tunedKcats select; an +% argument that is given and empty selects none. +nEc = numel(model.ec.rxns); +if ~any(given) + rows = (1:nEc)'; + return +end +sel = false(nEc, 1); +baseRxns = getEcRxnKeys(model); +if given(1) && ~isempty(rxns) + if islogical(rxns) + if numel(rxns) ~= nEc + error('kcatEvidence:rxns', 'A logical rxns needs %d entries, one per row of model.ec.rxns.', nEc) + end + sel(rxns) = true; + elseif isnumeric(rxns) + if any(rxns < 1 | rxns > nEc | rxns ~= round(rxns)) + error('kcatEvidence:rxns', 'rxns has an index outside model.ec.rxns (%d rows).', nEc) + end + sel(rxns) = true; + else + sel = sel | namedRows(model, baseRxns, cellstr(rxns), 'rxns'); + end +end +if given(3) && ~isempty(tunedKcats) + if ~isstruct(tunedKcats) || ~isfield(tunedKcats, 'rxns') + error('kcatEvidence:tunedKcats', 'tunedKcats is the structure that sensitivityTuning returns, with the field rxns.') + end +end +if given(3) && ~isempty(tunedKcats) && ~isempty(tunedKcats.rxns) + sel = sel | namedRows(model, baseRxns, tunedKcats.rxns, 'tunedKcats.rxns'); +end +if given(2) && ~isempty(enzymes) + enzymes = cellstr(enzymes); + missing = setdiff(enzymes, model.ec.enzymes); + if ~isempty(missing) + error('kcatEvidence:enzymes', 'Not in model.ec.enzymes: %s.', strjoin(missing, ', ')) + end + sel = sel | any(model.ec.rxnEnzMat(:, ismember(model.ec.enzymes, enzymes)) ~= 0, 2); +end +rows = find(sel); +end + +function sel = namedRows(model, baseRxns, names, label) +% Rows named by their model.ec.rxns entry or by their conventional reaction. +names = names(:); +sel = ismember(model.ec.rxns(:), names) | ismember(baseRxns(:), names); +missing = names(~ismember(names, model.ec.rxns) & ~ismember(names, baseRxns)); +if ~isempty(missing) + error('kcatEvidence:rxns', 'Not reactions of model.ec (%s): %s.', label, strjoin(missing', ', ')) +end +end + +function out = fieldOrEmpty(s, field, keep) +if isfield(s, field) + out = reshape(s.(field)(keep), [], 1); +else + out = repmat({''}, nnz(keep), 1); +end +end + +function s = joinCodes(c) +if iscell(c) + s = strjoin(c(:)', ';'); +elseif ischar(c) || isstring(c) + s = char(c); +else + s = ''; +end +end + +function checkOptions(args, names, functionName) +% Options are name-value pairs with known names, so a misspelled option is +% an error instead of being taken as a positional argument. +id = [functionName ':arguments']; +given = args(1:2:end); +if mod(numel(args), 2) ~= 0 || ~all(cellfun(@(x) ischar(x) || (isstring(x) && isscalar(x)), given)) + error(id, 'Options of %s are name-value pairs. Options: %s.', functionName, strjoin(names, ', ')) +end +unknown = setdiff(cellfun(@char, given, 'UniformOutput', false), names); +if ~isempty(unknown) + error(id, 'Unknown option of %s: %s. Options: %s.', functionName, strjoin(unknown, ', '), ... + strjoin(names, ', ')) +end +end diff --git a/src/gather_kcats/kcatsForReactions.m b/src/gather_kcats/kcatsForReactions.m new file mode 100644 index 00000000..6c4e2e6f --- /dev/null +++ b/src/gather_kcats/kcatsForReactions.m @@ -0,0 +1,150 @@ +function [evidence, summary] = kcatsForReactions(model, rxns, varargin) +% kcatsForReactions Get the kcats of every source for a few reactions. +% +% Reads the kcats that the source files of the project give for the +% reactions, computes the EC-tree estimate for them, and optionally +% predicts their kcats with one or several OpenKineticsPredictor (OKP) +% methods. The result is shown next to the kcat of the model (see +% kcatEvidence). +% +% The OKP jobs have their own tag (see the jobTag option of kcatsFromOKP): +% they submit the enzyme-substrate pairs of the selected reactions only, and +% leave the job and the result that kcatsFromOKP keeps for all reactions as +% they are. The predictions are written to data/kcats/okp___query.tsv +% and read back as a source of kcatEvidence. The function waits for each OKP +% job to finish and submits a new job on every call. An OKP method that fails is +% reported and the other methods continue; the methods without predictions are +% listed at the end. Each OKP method submits a job and +% counts against the daily prediction quota of the API key. +% +% Parameters +% ---------- +% model : struct +% an ecModel (with ecModel.ec structure), with metabolite SMILES +% (findMetSmiles) and protein sequences when OKP is used. +% rxns : cell, char, double or logical +% the reactions, as in kcatEvidence: names of model.ec.rxns or +% conventional reaction names (a reverse direction ends with _REV), +% indices or a logical vector. +% +% Name-Value Arguments +% -------------------- +% okp : logical, char or cell +% OKP methods to predict with: false or empty for none (default), true for the +% method of the model adapter, 'all' for every method that kcatsFromOKP +% accepts, or a method name or cell array of method names. +% sources, compute, measurements, modelAdapter +% as in kcatEvidence; compute is {'ec_tree'} by default, so the EC-tree +% estimate is computed from the BRENDA measurements, also when the project +% has an ec_tree.tsv. With sources, the files of the OKP methods that were +% asked for are added to it. The default sources include the okp___query.tsv +% files of earlier queries, which show the predictions of an earlier query for the same +% reactions. +% +% Returns +% ------- +% evidence, summary : table +% as returned by kcatEvidence for the reactions. +% +% Examples +% -------- +% [~, summary] = kcatsForReactions(ecModel, 'MAR03905'); +% [~, summary] = kcatsForReactions(ecModel, {'MAR03905', 'MAR03905_REV'}, 'okp', 'all'); +% [~, summary] = kcatsForReactions(ecModel, 12, 'okp', {'KinForm-H', 'UniKP'}); +% +% See also +% -------- +% kcatEvidence, kcatsFromOKP, kcatsFromECTree + +checkOptions(varargin, {'okp','sources','compute','measurements','modelAdapter'}, 'kcatsForReactions'); +p = parseGECKOargs(varargin, { ... + 'okp', false; ... + 'sources', []; ... + 'compute', {'ec_tree'}; ... + 'measurements', []; ... + 'modelAdapter', []}); +modelAdapter = p.modelAdapter; +if isempty(modelAdapter) + modelAdapter = ModelAdapterManager.getDefault(); + if isempty(modelAdapter) + error('Either send in a modelAdapter or set the default model adapter in the ModelAdapterManager.') + end +end +[~, ~, rows] = kcatEvidence(model, 'rxns', rxns, 'sources', {}, 'modelAdapter', modelAdapter); +if isempty(rows) + error('kcatsForReactions:none', 'No reaction of model.ec is selected.') +end + +methods = okpMethods(p.okp, modelAdapter.params); +selected = false(numel(model.ec.rxns), 1); +selected(rows) = true; +queried = cell(1, 0); +failed = cell(1, 0); +for i = 1:numel(methods) + try + [~, done] = kcatsFromOKP(model, 'method', methods{i}, 'ecRxns', selected, ... + 'jobTag', 'query', 'resubmit', true, 'wait', true, 'modelAdapter', modelAdapter); + catch err + printOrange(sprintf('OKP %s failed: %s\n', methods{i}, err.message)); + done = false; + end + if done + queried{end+1} = ['okp_' okpTag(methods{i}) '__query']; %#ok + else + failed{end+1} = methods{i}; %#ok + end +end +if ~isempty(failed) + printOrange(sprintf('No OKP predictions from: %s.\n', strjoin(failed, ', '))); +end + +sources = p.sources; +if ~(isnumeric(sources) && isempty(sources)) + sources = [cellstr(sources(:))', queried]; +end +[evidence, summary] = kcatEvidence(model, 'rxns', rows, 'sources', sources, 'compute', p.compute, ... + 'measurements', p.measurements, 'modelAdapter', modelAdapter); +end + +function methods = okpMethods(okp, params) +% The OKP methods that okp asks for. +known = {'CataPro','CatRange','DLKcat','EITLEM','KinForm-H','KinForm-L', ... + 'OmniESI','OmniESI-O2DENet','UniKP'}; +if isempty(okp) || islogical(okp) || isnumeric(okp) + if isempty(okp) || ~okp + methods = {}; + else + config = kcatAssignmentConfig(params); + methods = config.okpMethods(1); + end +elseif (ischar(okp) || isstring(okp)) && strcmpi(okp, 'all') + methods = known; +else + methods = cellstr(okp); + unknown = setdiff(methods, known); + if ~isempty(unknown) + error('kcatsForReactions:okp', 'Unknown OKP methods: %s. Methods: %s.', ... + strjoin(unknown, ', '), strjoin(known, ', ')) + end +end +methods = methods(:)'; +end + +function tag = okpTag(method) +tag = lower(regexprep(regexprep(method, '[^A-Za-z0-9]+', '_'), '^_+|_+$', '')); +end + +function checkOptions(args, names, functionName) +% Options are name-value pairs with known names, so a misspelled option is +% an error instead of being taken as a positional argument. +id = [functionName ':arguments']; +given = args(1:2:end); +if mod(numel(args), 2) ~= 0 || ~all(cellfun(@(x) ischar(x) || (isstring(x) && isscalar(x)), given)) + error(id, 'Options of %s are name-value pairs. Options: %s.', functionName, strjoin(names, ', ')) +end +unknown = setdiff(cellfun(@char, given, 'UniformOutput', false), names); +if ~isempty(unknown) + error(id, 'Unknown option of %s: %s. Options: %s.', functionName, strjoin(unknown, ', '), ... + strjoin(names, ', ')) +end +end diff --git a/src/gather_kcats/kcatsFromECTree.m b/src/gather_kcats/kcatsFromECTree.m index d1906d83..dfc3529f 100644 --- a/src/gather_kcats/kcatsFromECTree.m +++ b/src/gather_kcats/kcatsFromECTree.m @@ -7,7 +7,10 @@ % for n measurements (see ecTreeEstimate). A reaction with several EC % numbers uses the one with most measurements. Reactions without an EC % number, or whose EC classes have no measurements, get no value. The -% result is written to data/kcats/ec_tree.tsv in the project folder (see +% estimate depends on the EC number only: BRENDA measurements have no +% direction, so a reaction and its reverse direction (_REV) get the same +% value, and the detail of a reverse direction ends with 'direction=reverse'. +% The result is written to data/kcats/ec_tree.tsv in the project folder (see % saveKcatSource). % % Parameters @@ -41,7 +44,8 @@ % kcatList : struct % the kcat values, with fields source, rxns, eccodes, kcats and detail % (the number of measurements of the EC, n, and the deepest EC level -% with measurements, depth). +% with measurements, depth; 'direction=reverse' is added for a reverse +% direction, whose value is the one of the forward direction). % % Examples % -------- @@ -96,6 +100,8 @@ kcatList.eccodes = ecUsed(found); kcatList.kcats = 10 .^ values(found); kcatList.detail = cellstr("n=" + string(n(found)) + "; depth=" + string(depth(found))); +isReverse = ~cellfun(@isempty, regexp(kcatList.rxns, '_REV(_EXP_\d+)?$', 'once')); +kcatList.detail(isReverse) = strcat(kcatList.detail(isReverse), '; direction=reverse'); if p.save parameters = struct('k', p.k); diff --git a/src/gather_kcats/kcatsFromOKP.m b/src/gather_kcats/kcatsFromOKP.m index bca5248e..4abf61e1 100644 --- a/src/gather_kcats/kcatsFromOKP.m +++ b/src/gather_kcats/kcatsFromOKP.m @@ -43,9 +43,20 @@ % useStored : logical % read the stored result of this method's job, without contacting OKP % (default false). -% ecRxns : logical -% for which model.ec.rxns kcats are predicted (default: all). Only -% used when a job is submitted. +% ecRxns : logical, double or cell +% for which model.ec.rxns kcats are predicted (default: all), as a +% logical vector, as indices, or as names of model.ec.rxns. Only used +% when a job is submitted. +% jobTag : char +% keeps the job, its input and its result apart from the job of the +% method without a tag: they are read and written as +% data/OKP_job___.txt, data/OKP_query_.csv and +% data/OKP_output___.csv, and the source file is +% okp___.tsv unless saveAs is given. The tag is written +% in lower case, with each run of other characters than letters and +% digits as _, and has at least one letter or digit (default: none). +% A job for a few reactions with a tag leaves the job and the result +% of all reactions as they are. % save : logical % write the source file (default true). % saveAs : char @@ -77,13 +88,14 @@ % -------- % kcatsFromBrenda, kcatsFromDLKcat, resolveOkpApiKey, saveKcatSource -checkOptions(varargin, {'method','wait','resubmit','useStored','ecRxns','save','saveAs','modelAdapter'}, 'kcatsFromOKP'); +checkOptions(varargin, {'method','wait','resubmit','useStored','ecRxns','jobTag','save','saveAs','modelAdapter'}, 'kcatsFromOKP'); p = parseGECKOargs(varargin, { ... 'method', []; ... 'wait', false; ... 'resubmit', false; ... 'useStored', false; ... 'ecRxns', []; ... + 'jobTag', ''; ... 'save', true; ... 'saveAs', []; ... 'modelAdapter', []}); @@ -107,6 +119,15 @@ % The file name of a method: lower case, runs of characters other than % letters and digits replaced by _ (the same rule as okp_ sources). tag = lower(regexprep(regexprep(method, '[^A-Za-z0-9]+', '_'), '^_+|_+$', '')); +jobTag = lower(regexprep(regexprep(char(p.jobTag), '[^A-Za-z0-9]+', '_'), '^_+|_+$', '')); +if ~isempty(char(p.jobTag)) && isempty(jobTag) + error('kcatsFromOKP:jobTag', 'jobTag ''%s'' has no letters or digits.', char(p.jobTag)) +end +if ~isempty(jobTag) + tag = [tag '__' jobTag]; +end +ecRxnsGiven = ismember('ecRxns', cellfun(@char, varargin(1:2:end), 'UniformOutput', false)); +p.ecRxns = ecRxnsToLogical(model, p.ecRxns, ecRxnsGiven); dataDir = fullfile(params.path, 'data'); jobFile = fullfile(dataDir, ['OKP_job_' tag '.txt']); outFile = fullfile(dataDir, ['OKP_output_' tag '.csv']); @@ -122,13 +143,13 @@ end if p.save file = fullfile(modelAdapter.params.path, 'data', 'kcats', [char(name) '.tsv']); - if submitting + if submitting && isempty(jobTag) warnSubset(p.ecRxns, numel(model.ec.rxns), file); end end if p.useStored - if ~isfield(job, 'jobId') + if ~isfield(job, 'jobId') && isempty(jobTag) adoptSharedResult(model, modelAdapter, dataDir, method, jobFile, outFile); job = readJobFile(jobFile); end @@ -143,7 +164,7 @@ if isfile(outFile) delete(outFile); end - jobId = submitOpenKineticsPredictor(model, method, p.ecRxns, modelAdapter); + jobId = submitOpenKineticsPredictor(model, method, p.ecRxns, modelAdapter, jobTag); job = struct('jobId', jobId, 'method', method, 'submittedAt', ... char(datetime('now', 'TimeZone', 'UTC', 'Format', 'yyyy-MM-dd''T''HH:mm:ss''Z'''))); if ~isempty(p.ecRxns) @@ -229,6 +250,37 @@ function writeJobFile(file, job) fclose(fid); end +function ecRxns = ecRxnsToLogical(model, ecRxns, given) +% ecRxns as a logical vector over model.ec.rxns, from a logical vector, indices or names. +if isempty(ecRxns) + if given + error('kcatsFromOKP:ecRxns', 'ecRxns selects no reaction; leave it out to predict for all reactions.') + end + return +end +if islogical(ecRxns) + if numel(ecRxns) ~= numel(model.ec.rxns) + error('kcatsFromOKP:ecRxns', 'A logical ecRxns needs %d entries, one per row of model.ec.rxns.', numel(model.ec.rxns)) + end + return +end +selected = false(numel(model.ec.rxns), 1); +if isnumeric(ecRxns) + if any(ecRxns < 1 | ecRxns > numel(selected) | ecRxns ~= round(ecRxns)) + error('kcatsFromOKP:ecRxns', 'ecRxns has an index outside model.ec.rxns (%d rows).', numel(selected)) + end + selected(ecRxns) = true; +else + names = cellstr(ecRxns); + missing = setdiff(names, model.ec.rxns); + if ~isempty(missing) + error('kcatsFromOKP:ecRxns', 'Not in model.ec.rxns: %s.', strjoin(missing, ', ')) + end + selected(ismember(model.ec.rxns, names)) = true; +end +ecRxns = selected; +end + function n = countRxns(ecRxns) if islogical(ecRxns) n = sum(ecRxns); @@ -260,7 +312,7 @@ function checkOptions(args, names, functionName) end end -function jobId = submitOpenKineticsPredictor(model, method, ecRxns, modelAdapter) +function jobId = submitOpenKineticsPredictor(model, method, ecRxns, modelAdapter, jobTag) % Writes the input of a job (data/OKP.csv) and submits it to the OKP REST API % (https://predictor.openkinetics.org/). The input is written before the API % key is resolved, so it can be checked without a key. @@ -280,8 +332,11 @@ function checkOptions(args, names, functionName) okp.method = method; filename = fullfile(params.path,'data','OKP.csv'); +if ~isempty(jobTag) + filename = fullfile(params.path,'data',['OKP_query_' jobTag '.csv']); +end writeOpenKineticsPredictorInput(model, 'ecRxns', ecRxns, 'modelAdapter', modelAdapter, ... - 'onlyWithSmiles', true, 'overwrite', true); + 'onlyWithSmiles', true, 'overwrite', true, 'file', filename); apiKey = resolveOkpApiKey('', params.path); %% Submit via the OKP REST API @@ -397,7 +452,8 @@ function writeOpenKineticsPredictorInput(model, varargin) 'ecRxns', []; ... 'modelAdapter', []; ... 'onlyWithSmiles', []; ... - 'overwrite', []}); + 'overwrite', []; ... + 'file', ''}); ecRxns = p.ecRxns; modelAdapter = p.modelAdapter; onlyWithSmiles = p.onlyWithSmiles; @@ -427,6 +483,9 @@ function writeOpenKineticsPredictorInput(model, varargin) %% Output files filename = fullfile(params.path,'data','OKP.csv'); +if ~isempty(p.file) + filename = p.file; +end if ~overwrite && exist(filename,'file') error('%s already exists. Set overwrite=true to replace it.', filename) end diff --git a/src/kcat_tuning/sensitivityTuning.m b/src/kcat_tuning/sensitivityTuning.m index 97b397a2..515ebf51 100644 --- a/src/kcat_tuning/sensitivityTuning.m +++ b/src/kcat_tuning/sensitivityTuning.m @@ -4,7 +4,9 @@ % Iteratively increases the kcat of whichever enzyme currently limits growth % the most, until the model reaches the desired growth rate, updating the % tuned values in model.ec.kcat. The loop also stops, with a warning, when an -% iteration raises growth by less than 1e-9. +% iteration raises growth by less than 1e-9. When two enzymes, or two +% reactions of an enzyme, tie (fluxes equal within a relative 1e-9), the one +% that is first in model.rxns is selected. % % This is the standard kcat tuning: it needs one maximum growth rate. % cmaesKcatTuning is the advanced tuning, which fits kcats to maximum @@ -29,6 +31,10 @@ % 'Q99271'} (default []). % verbose : logical % whether progress should be reported (default true). +% evidence : logical +% add tunedKcats.evidence, the kcats that every source file of the +% project gives for the tuned reactions next to the tuned kcat (see +% kcatEvidence; default false). % % Returns % ------- @@ -49,6 +55,8 @@ % - newKcat : kcat values in the output model, after tuning. % - source : source label of each kcat, taken from the input model before % tuning. +% - evidence : only with the option evidence; the summary table of +% kcatEvidence for the tuned reactions. % % model.ec.source of a tuned kcat keeps its origin and detail and gains the % tuning status, e.g. 'brenda (wc=0, origin=1) | tuned=sensitivity @@ -67,7 +75,8 @@ 'modelAdapter', []; ... 'foldChange', 10; ... 'protToIgnore', {}; ... - 'verbose', true}); + 'verbose', true; ... + 'evidence', false}); desiredGrowthRate = p.desiredGrowthRate; modelAdapter = p.modelAdapter; foldChange = p.foldChange; @@ -100,6 +109,7 @@ % previous iteration (the first iteration has nothing to compare with). lastGrowth = NaN; growthStallTol = 1e-9; +tieTol = 1e-9; if ~m.ec.geckoLight %for the full model, we first find the draw reaction with the most flux drawRxns = startsWith(m.rxns, 'usage_prot_'); @@ -133,12 +143,15 @@ printOrange('WARNING: No protein usage reaction carries flux, tuning cannot continue.\n'); break; end - [~,sel] = max(drawFluxes); % since bounds 0 to 1000 + % Equal fluxes (within tieTol) are a tie, which goes to the first reaction of the model. + best = max(drawFluxes); % since bounds 0 to 1000 + sel = find(drawFluxes >= best - tieTol * max(1, abs(best)), 1); %Now get the metabolite metSel = m.S(:,sel) > 0; % positive coeff (forward usage) %now find the reaction with the largest consumption of this protein protFluxes = m.S(metSel,:).' .* res.x; %negative - [~,rxnSel] = min(protFluxes); + best = min(protFluxes); + rxnSel = find(protFluxes <= best + tieTol * max(1, abs(best)), 1); kcatList = [kcatList, rxnSel]; rxn = m.rxns(rxnSel); targetSubRxn = strcmp(m.ec.rxns, rxn); @@ -182,7 +195,9 @@ printOrange('WARNING: No reaction draws on the protein pool, tuning cannot continue.\n'); break; end - [~,sel] = min(res.x .* protPoolStoich); %max consumption + usage = res.x .* protPoolStoich; + best = min(usage); %max consumption + sel = find(usage <= best + tieTol * max(1, abs(best)), 1); kcatList = [kcatList, sel]; rxn = m.rxns(sel.'); targetSubRxns = strcmp(origRxns, rxn); @@ -210,6 +225,13 @@ tunedKcats.source = model.ec.source(rxnIdx); model = m; +if p.evidence + try + [~, tunedKcats.evidence] = kcatEvidence(model, 'tunedKcats', tunedKcats, 'modelAdapter', modelAdapter); + catch err + printOrange(sprintf('The evidence of the tuned kcats could not be read: %s\n', err.message)); + end +end end function m = markTuned(m,rows) diff --git a/src/utilities/upgradeGECKOproject.m b/src/utilities/upgradeGECKOproject.m index 092c7f86..02378ecc 100644 --- a/src/utilities/upgradeGECKOproject.m +++ b/src/utilities/upgradeGECKOproject.m @@ -121,6 +121,9 @@ function keepOriginal(file) end okpFiles = dir(fullfile(projectPath, 'data', 'OKP_output*.csv')); for k = 1:numel(okpFiles) + if contains(okpFiles(k).name, '__') + continue % the result of a tagged query (kcatsFromOKP jobTag) + end method = okpMethod(projectPath, okpFiles(k).name); if ~isempty(method) name = ['okp_' lower(regexprep(regexprep(method, '[^A-Za-z0-9]+', '_'), '^_+|_+$', ''))]; diff --git a/test/unit_tests/ecTreeTests.m b/test/unit_tests/ecTreeTests.m index 70d8aaea..3a99d8ad 100644 --- a/test/unit_tests/ecTreeTests.m +++ b/test/unit_tests/ecTreeTests.m @@ -56,7 +56,10 @@ function testKcatsFromECTreeWritesFile_tc0086(testCase) verifyEqual(testCase, meta.parameters, '{"k":5}') verifyEqual(testCase, meta.data, 'BRENDA release test') verifyEqual(testCase, unique(records.source), {'ec_tree'}) - verifyTrue(testCase, all(~cellfun(@isempty, regexp(records.detail, '^n=\d+; depth=[234]$', 'once')))) + verifyTrue(testCase, all(~cellfun(@isempty, regexp(records.detail, '^n=\d+; depth=[234](; direction=reverse)?$', 'once')))) + isReverse = endsWith(records.detail, 'direction=reverse'); + verifyEqual(testCase, isReverse, endsWith(records.rxn, '_REV')) + verifyTrue(testCase, any(isReverse)) end function testBrendaEcTreePreset_tc0087(testCase) diff --git a/test/unit_tests/kcatEvidenceTests.m b/test/unit_tests/kcatEvidenceTests.m new file mode 100644 index 00000000..5d597369 --- /dev/null +++ b/test/unit_tests/kcatEvidenceTests.m @@ -0,0 +1,188 @@ +%run this test case with the command +%results = runtests('kcatEvidenceTests.m') + +function tests = kcatEvidenceTests + tests = functiontests(localfunctions); +end + +function testEvidenceListsEverySource_tc0748(testCase) + [model, adapter] = buildProject(); + rows = find(~cellfun(@isempty, model.ec.eccodes) & any(model.ec.rxnEnzMat, 2), 3); + sel = model.ec.rxns(rows); + a = struct('rxns', {sel}, 'kcats', [1; 2; 4]); + saveKcatSource(model, a, 'srcA', 'modelAdapter', adapter); + b = struct('rxns', {sel(1)}, 'kcats', 8); + saveKcatSource(model, b, 'srcB', 'modelAdapter', adapter); + [evidence, summary, idx] = kcatEvidence(model, 'rxns', sel, 'sources', {'srcA', 'srcB'}, ... + 'modelAdapter', adapter); + verifyEqual(testCase, idx(:), rows(:)) + verifyEqual(testCase, summary.ecRxn, sel(:)) + verifyEqual(testCase, summary.src_srcA, [1; 2; 4]) + verifyEqual(testCase, summary.src_srcB(1), 8) + verifyEqual(testCase, summary.Properties.VariableNames, {'ecRxn','kcat','tuned','fold','prior', ... + 'origin','enzymes','eccodes','src_srcA','src_srcB'}) + [~, summaryOrdered] = kcatEvidence(model, 'rxns', sel, 'sources', {'srcB', 'srcA'}, 'modelAdapter', adapter); + verifyEqual(testCase, summaryOrdered.Properties.VariableNames(end-1:end), {'src_srcA','src_srcB'}) + verifyEqual(testCase, evidence.Properties.VariableNames, {'ecRxn','kcat','source','substrate','detail','assigned'}) + verifyTrue(testCase, all(isnan(summary.src_srcB(2:3)))) + verifyEqual(testCase, height(evidence), 4) + verifyEqual(testCase, summary.kcat, model.ec.kcat(rows(:))) + % A source that is not listed is not read. + [~, summary] = kcatEvidence(model, 'rxns', rows, 'sources', {'srcB'}, 'modelAdapter', adapter); + verifyFalse(testCase, ismember('src_srcA', summary.Properties.VariableNames)) + verifyError(testCase, @() kcatEvidence(model, 'rxns', {'nope'}, 'modelAdapter', adapter), 'kcatEvidence:rxns') + verifyError(testCase, @() kcatEvidence(model, 'compute', {'x'}, 'modelAdapter', adapter), 'kcatEvidence:compute') +end + +function testEvidenceOfTunedKcat_tc0749(testCase) + [model, adapter] = buildProject(); + i = find(any(model.ec.rxnEnzMat, 2), 1); + prior = 0.5; + model.ec.kcat(i) = 5; + model.ec.source{i} = 'custom | tuned=sensitivity (prior=0.5)'; + a = struct('rxns', {model.ec.rxns(i)}, 'kcats', prior); + saveKcatSource(model, a, 'srcA', 'modelAdapter', adapter); + tunedKcats = struct('rxns', {model.ec.rxns(i)}); + if model.ec.geckoLight + tunedKcats.rxns = extractAfter(model.ec.rxns(i), 4); + end + [evidence, summary] = kcatEvidence(model, 'tunedKcats', tunedKcats, 'sources', {'srcA'}, ... + 'modelAdapter', adapter); + verifyEqual(testCase, summary.ecRxn, model.ec.rxns(i)) + verifyTrue(testCase, summary.tuned) + verifyEqual(testCase, [summary.kcat, summary.prior, summary.fold], [5, 0.5, 10], 'AbsTol', 1e-12) + verifyEqual(testCase, summary.origin, {'custom'}) + verifyTrue(testCase, evidence.assigned) + % The prior in ec.source has six significant digits: a source kcat that + % equals the assigned one up to that rounding is still the assigned one. + model.ec.kcat(i) = 123.456789; + model.ec.source{i} = 'custom | tuned=sensitivity (prior=12.3457)'; + saveKcatSource(model, struct('rxns', {model.ec.rxns(i)}, 'kcats', 12.3456789), 'srcA', 'modelAdapter', adapter); + evidence = kcatEvidence(model, 'rxns', model.ec.rxns(i), 'sources', {'srcA'}, 'modelAdapter', adapter); + verifyTrue(testCase, evidence.assigned) + % A tuning status without a prior is tuned, and has no fold. + model.ec.source{i} = 'custom | tuned=cmaes'; + [~, summary] = kcatEvidence(model, 'rxns', i, 'sources', {}, 'modelAdapter', adapter); + verifyTrue(testCase, summary.tuned && isnan(summary.prior) && isnan(summary.fold)) + model.ec.kcat(i) = 5; + model.ec.source{i} = 'custom | tuned=sensitivity (prior=0.5)'; + file = [tempname '.tsv']; + kcatEvidence(model, 'tunedKcats', tunedKcats, 'sources', {'srcA'}, 'saveAs', file, 'modelAdapter', adapter); + saved = readtable(file, 'FileType', 'text', 'Delimiter', '\t'); + verifyEqual(testCase, saved.fold, 10, 'AbsTol', 1e-9) +end + +function testEvidenceByEnzymeAndEcTree_tc0750(testCase) + [model, adapter] = buildProject(); + e = find(any(model.ec.rxnEnzMat ~= 0, 1), 1); + expected = find(model.ec.rxnEnzMat(:, e) ~= 0); + m = measurementsFor(model); + [evidence, summary, idx] = kcatEvidence(model, 'enzymes', model.ec.enzymes(e), 'sources', {}, ... + 'compute', {'ec_tree'}, 'measurements', m, 'modelAdapter', adapter); + verifyEqual(testCase, idx(:), expected(:)) + withEc = ~cellfun(@isempty, model.ec.eccodes(expected)); + verifyEqual(testCase, sum(~isnan(summary.src_ec_tree)), sum(withEc)) + verifyEqual(testCase, unique(evidence.source), {'ec_tree'}) + verifyError(testCase, @() kcatEvidence(model, 'enzymes', {'X00000'}, 'modelAdapter', adapter), 'kcatEvidence:enzymes') + % A computed EC-tree estimate replaces a file of that name. + e = find(~cellfun(@isempty, model.ec.eccodes), 1); + saveKcatSource(model, struct('rxns', {model.ec.rxns(e)}, 'kcats', 1e9), 'ec_tree', 'modelAdapter', adapter); + [~, summary] = kcatEvidence(model, 'rxns', e, 'compute', {'ec_tree'}, 'measurements', m, 'modelAdapter', adapter); + verifyEqual(testCase, summary.src_ec_tree, 10 .^ ecTreeEstimate(model.ec.eccodes(e), m, 5), 'RelTol', 1e-9) +end + +function testEmptySelectionSelectsNothing_tc0755(testCase) + [model, adapter] = buildProject(); + for args = {{'rxns', {}}, {'rxns', []}, {'enzymes', {}}, {'tunedKcats', []}, {'tunedKcats', struct('rxns', {{}})}} + [~, summary, rows] = kcatEvidence(model, args{1}{:}, 'sources', {}, 'modelAdapter', adapter); + verifyEmpty(testCase, rows) + verifyEqual(testCase, height(summary), 0) + end + [~, ~, rows] = kcatEvidence(model, 'sources', {}, 'modelAdapter', adapter); + verifyEqual(testCase, numel(rows), numel(model.ec.rxns)) + verifyError(testCase, @() kcatEvidence(model, 'rxns', 10^6, 'modelAdapter', adapter), 'kcatEvidence:rxns') + verifyError(testCase, @() kcatEvidence(model, 'rxns', true(2, 1), 'modelAdapter', adapter), 'kcatEvidence:rxns') + verifyError(testCase, @() kcatsForReactions(model, {}, 'modelAdapter', adapter), 'kcatsForReactions:none') + verifyError(testCase, @() kcatsForReactions(model, 1, 'measurement', 1, 'modelAdapter', adapter), 'kcatsForReactions:arguments') +end + +function testConventionalNameSelectsTheIsozymes_tc0756(testCase) + [model, adapter] = buildProject(true); + base = getEcRxnKeys(model); + [names, ~, g] = unique(base); + [~, most] = max(accumarray(g, 1)); + name = names{most}; + expected = find(strcmp(base, name)); + verifyGreaterThan(testCase, numel(expected), 1) + [~, ~, rows] = kcatEvidence(model, 'rxns', name, 'sources', {}, 'modelAdapter', adapter); + verifyEqual(testCase, rows(:), expected(:)) + [~, ~, rows] = kcatEvidence(model, 'tunedKcats', struct('rxns', {{name}}), 'sources', {}, 'modelAdapter', adapter); + verifyEqual(testCase, rows(:), expected(:)) +end + +function testKcatsForReactionsWithoutOkp_tc0751(testCase) + [model, adapter] = buildProject(); + i = find(~cellfun(@isempty, model.ec.eccodes) & any(model.ec.rxnEnzMat, 2), 1); + [~, summary] = kcatsForReactions(model, i, 'measurements', measurementsFor(model), 'modelAdapter', adapter); + verifyEqual(testCase, summary.ecRxn, model.ec.rxns(i)) + verifyFalse(testCase, isnan(summary.src_ec_tree)) + verifyError(testCase, @() kcatsForReactions(model, i, 'okp', 'NoSuchMethod', 'modelAdapter', adapter), ... + 'kcatsForReactions:okp') + % An empty okp asks for no OKP method: no job is submitted and no file is written. + [~, summary] = kcatsForReactions(model, i, 'okp', [], 'measurements', measurementsFor(model), 'modelAdapter', adapter); + verifyEqual(testCase, height(summary), 1) +end + +function testOkpJobTagAndNames_tc0752(testCase) + [model, adapter, project] = buildProject(); + verifyError(testCase, @() kcatsFromOKP(model, 'method', 'KinForm-H', 'ecRxns', {'nope'}, ... + 'modelAdapter', adapter), 'kcatsFromOKP:ecRxns') + % A tagged job has its own files: nothing is stored for it, whatever is stored for the method. + writeSharedJob(project); + verifyError(testCase, @() kcatsFromOKP(model, 'method', 'KinForm-H', 'jobTag', 'query', ... + 'useStored', true, 'modelAdapter', adapter), 'kcatsFromOKP:noStored') + try + kcatsFromOKP(model, 'method', 'KinForm-H', 'jobTag', 'query', 'useStored', true, 'modelAdapter', adapter); + catch err + verifyTrue(testCase, contains(err.message, 'OKP_job_kinform_h__query.txt')) + end + verifyError(testCase, @() kcatsFromOKP(model, 'method', 'KinForm-H', 'jobTag', '!!', 'useStored', true, ... + 'modelAdapter', adapter), 'kcatsFromOKP:jobTag') + verifyError(testCase, @() kcatsFromOKP(model, 'method', 'KinForm-H', 'ecRxns', 10^6, ... + 'modelAdapter', adapter), 'kcatsFromOKP:ecRxns') + verifyError(testCase, @() kcatsFromOKP(model, 'method', 'KinForm-H', 'ecRxns', {}, ... + 'modelAdapter', adapter), 'kcatsFromOKP:ecRxns') + verifyError(testCase, @() kcatsFromOKP(model, 'method', 'KinForm-H', 'ecRxns', true(2, 1), ... + 'modelAdapter', adapter), 'kcatsFromOKP:ecRxns') +end + +function writeSharedJob(project) + fid = fopen(fullfile(project, 'data', 'OKP_job_kinform_h.txt'), 'w'); + fprintf(fid, 'jobId: abc\nmethod: KinForm-H\nresultOf: abc\n'); + fclose(fid); + fid = fopen(fullfile(project, 'data', 'OKP_output_kinform_h.csv'), 'w'); + fprintf(fid, 'x\n'); + fclose(fid); +end + +function m = measurementsFor(model) + % Two measurements for each EC number of the model. + ecs = unique(strtrim(split(strjoin(model.ec.eccodes(~cellfun(@isempty, model.ec.eccodes)), ';'), ';'))); + ecs = ecs(~cellfun(@isempty, ecs)); + v = repelem((1:numel(ecs))', 2); + m = struct('ec', {repelem(ecs, 2)}, 'log10kcat', v, 'kcat', 10 .^ v, 'release', 'BRENDA release test'); +end + +function [base, adapter, project] = buildProject(light) + if nargin < 1 + light = false; + end + geckoPath = findGECKOroot; + adapter = ModelAdapterManager.getAdapter(fullfile(geckoPath,'test','unit_tests','ecTestGEM','TestGEMAdapter.m')); + project = tempname; + copyfile(fullfile(adapter.params.path, 'data'), fullfile(project, 'data')); + adapter.params.path = project; + model = getGeckoTestModel(); + base = makeEcModel(model, light, adapter); + base = getECfromGEM(base); +end diff --git a/test/unit_tests/kcatSourceFormatTests.m b/test/unit_tests/kcatSourceFormatTests.m index 204339cd..42b7b12e 100644 --- a/test/unit_tests/kcatSourceFormatTests.m +++ b/test/unit_tests/kcatSourceFormatTests.m @@ -206,6 +206,21 @@ function testResolveTunableContextGroupsATunedSourceByItsOrigin_tc0712(testCase) verifyEqual(testCase, sigma0log, [0.2; 0.3; 0.4; 0.5]) end +function testSensitivityTuningReturnsEvidence_tc0753(testCase) + % With evidence, tunedKcats.evidence has one row per tuned reaction, with the + % kcat after tuning, the kcat before tuning and their ratio. + [ecModel, tuneAdapter] = tuningModel(); + ecModel.ec.source(:) = {'brenda (wc=0, origin=1)'}; + cleanup = shadowSolveLP([1 1 50]); %#ok + [tuned, tunedKcats] = sensitivityTuning(ecModel, 'desiredGrowthRate', 50, ... + 'modelAdapter', tuneAdapter, 'protToIgnore', {'P4'}, 'verbose', false, 'evidence', true); + verifyEqual(testCase, sort(tunedKcats.evidence.ecRxn(:)), sort(unique(tunedKcats.rxns(:)))) + [~, i] = ismember(tunedKcats.evidence.ecRxn, tuned.ec.rxns); + verifyEqual(testCase, tunedKcats.evidence.kcat, tuned.ec.kcat(i)) + verifyEqual(testCase, tunedKcats.evidence.prior, ecModel.ec.kcat(i)) + verifyTrue(testCase, all(tunedKcats.evidence.fold > 1)) +end + function testSensitivityTuningExtendsTheStatusOnce_tc0713(testCase) % Every kcat the tuning changes gets the origin it had, the method % sensitivity and the kcat before the first tuning as prior. A second @@ -269,6 +284,24 @@ function testSensitivityTuningWritesUnknownForAnEmptyOrigin_tc0714(testCase) ecModel = getECfromGEM(ecModel); end +function testSensitivityTuningBreaksATieByModelOrder_tc0757(testCase) +% Two reactions of one enzyme consume equal amounts of it: the one that is +% first in the model is tuned. +[ecModel, tuneAdapter] = tuningModel(); +rows = (1:2)'; +column = find(ecModel.ec.rxnEnzMat(rows(1), :), 1); +ecModel.ec.rxnEnzMat(rows(2), :) = 0; +ecModel.ec.rxnEnzMat(rows(2), column) = 1; +ecModel.ec.kcat(rows) = 10; +ecModel = applyKcatConstraints(ecModel); +[~, order] = sort(cellfun(@(r) find(strcmp(ecModel.rxns, r)), ecModel.ec.rxns(rows))); +rows = rows(order); +cleanup = shadowSolveLP([1 1 100], ['usage_prot_' ecModel.ec.enzymes{column}], ecModel.ec.rxns(rows)); %#ok +[~, tunedKcats] = sensitivityTuning(ecModel, 'desiredGrowthRate', 50, ... + 'modelAdapter', tuneAdapter, 'verbose', false); +verifyEqual(testCase, tunedKcats.rxns, ecModel.ec.rxns(rows(1))) +end + function [ecModel, tuneAdapter] = tuningModel() % R3 limits growth, its enzyme P4 is ignored by the tests, so tuning raises R5. adapter = getAdapter(); @@ -291,10 +324,16 @@ function testSensitivityTuningWritesUnknownForAnEmptyOrigin_tc0714(testCase) tuneAdapter.params.bioRxn = 'R5'; end -function cleanup = shadowSolveLP(values) +function cleanup = shadowSolveLP(values, usage, consumers) % Puts a solveLP on the path that calls RAVEN's and then reports the growth -% of solve number n as values(min(n, end)). The path is restored when the -% returned object is cleared. +% of solve number n as values(min(n, end)). With usage and consumers, the +% flux of the reaction usage is 2, the flux of each reaction in consumers is +% 1 and all other fluxes are 0. The path is restored when the returned object +% is cleared. +if nargin > 1 + setappdata(0, 'gecko_test_solvelp_usage', usage); + setappdata(0, 'gecko_test_solvelp_consumers', consumers); +end setappdata(0, 'gecko_test_solvelp_real', @solveLP); setappdata(0, 'gecko_test_solvelp_count', 0); setappdata(0, 'gecko_test_solvelp_values', values); @@ -309,6 +348,12 @@ function testSensitivityTuningWritesUnknownForAnEmptyOrigin_tc0714(testCase) 'values = getappdata(0,''gecko_test_solvelp_values'');', ... '[res,hs] = real(varargin{:});', ... 'res.f = values(min(n,numel(values)));', ... + 'if isappdata(0,''gecko_test_solvelp_usage'')', ... + ' m = varargin{1};', ... + ' res.x = zeros(numel(m.rxns),1);', ... + ' res.x(strcmp(m.rxns,getappdata(0,''gecko_test_solvelp_usage''))) = 2;', ... + ' res.x(ismember(m.rxns,getappdata(0,''gecko_test_solvelp_consumers''))) = 1;', ... + 'end', ... 'end'); fclose(fid); addpath(stubDir, '-begin'); @@ -318,7 +363,7 @@ function testSensitivityTuningWritesUnknownForAnEmptyOrigin_tc0714(testCase) function removeShadow(stubDir) rmpath(stubDir); rmdir(stubDir, 's'); -for name = {'real', 'values'} +for name = {'real', 'values', 'usage', 'consumers'} if isappdata(0, ['gecko_test_solvelp_' name{1}]) rmappdata(0, ['gecko_test_solvelp_' name{1}]); end