Utilities#
MATLAB functions in RAVEN/src/utils of the RAVEN toolbox.
Functions#
Function |
Summary |
|---|---|
Ensure input is a cell array of character vectors. |
|
Warn once per session that a function is deprecated. |
|
Convert a grRule to disjunctive normal form. |
|
Render a grRule syntax tree back to a string. |
|
Test whether a grRule is in disjunctive normal form. |
|
Point a caller at the recommended method, once. |
|
Return the parfor worker count for a given setting. |
|
Parse a grRule into a syntax tree. |
|
Resolve optional arguments passed positionally or by name. |
|
Print an orange-coloured string to the MATLAB Command Window. |
|
Format a header and item list for warning() or error(). |
|
Declarative registry of all RAVEN model struct fields. |
|
Run all RAVEN function tests. |
|
Set the RAVEN progress-reporting backend. |
Reference#
convertCharArray#
function inputConverted = convertCharArray(funcInput)
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.
Parameters
funcInput: char or cell or stringfunction input that should be checked.
Returns
inputConverted: cellcell array of character vectors.
Examples
inputConverted = convertCharArray(funcInput);
deprecationWarning#
function deprecationWarning(oldFunction, replacement)
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.
Parameters
oldFunction: charname of the deprecated function.
replacement: charwhat to call instead, written as it would be typed, e.g. 'findLeakMetabolite(model,''produce'',...)'.
Examples
deprecationWarning('makeSomething','findLeakMetabolite(model,''produce'',...)');
grRuleToDNF#
function clauses=grRuleToDNF(rule)
Convert a grRule to disjunctive normal form.
Returns the rule as a list of AND-clauses, applying distributivity where needed: "G1 and (G2 or G3)" becomes {{G1,G2},{G1,G3}}. Each clause is one isozyme; the genes within it are the subunits of that complex.
Parameters
rule: char or string or structa grRule, or a tree from parseGrRule.
Returns
clauses: cellone cell array of gene IDs per AND-clause. An empty rule yields {}. A rule with no OR anywhere yields a single clause.
Notes
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.
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.
Examples
grRuleToDNF('(G1 and G2) or G3') % {{'G1','G2'}, {'G3'}}
grRuleToDNF('G1 and (G2 or G3)') % {{'G1','G2'}, {'G1','G3'}}
See also: parseGrRule, isDnfGrRule, expandModel
grRuleToString#
function rule=grRuleToString(tree)
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.
Parameters
tree: structa tree from parseGrRule. An empty tree yields ''.
Returns
rule: charthe rendered grRule.
Examples
grRuleToString(parseGrRule('(G1 and G2) or G3')) % '(G1 and G2) or G3'
See also: parseGrRule, standardizeGrRules
isDnfGrRule#
function tf=isDnfGrRule(rule)
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.
Parameters
rule: char or string or structa grRule, or a tree from parseGrRule. An empty rule is trivially DNF.
Returns
tf: logicaltrue if the rule is in disjunctive normal form.
Examples
isDnfGrRule('(G1 and G2) or G3') % true
isDnfGrRule('(G1 or G2) and G3') % false
See also: parseGrRule, grRuleToDNF, findPotentialErrors
legacyMethodNotice#
function legacyMethodNotice(oldFunction, preferred)
Point a caller at the recommended method, once.
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.
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').
Parameters
oldFunction: charname of the function being called.
preferred: charwhat to use instead for new work, written as it would be typed.
Examples
legacyMethodNotice('getINITModel','ftINIT');
See Also
deprecationWarning
parallelWorkersRAVEN#
function nW = parallelWorkersRAVEN(runParallel)
Return the parfor worker count for a given setting.
Returns a value for use with the parfor worker-count syntax:
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.
Parameters
runParallel: logicalwhether the caller should use parallel workers.
Returns
nW: double0 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).
parseGrRule#
function tree=parseGrRule(rule)
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.
Parameters
rule: char or stringa grRule, e.g. "(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.
Returns
tree: structa 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.
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:
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.
Examples
tree = parseGrRule('(G1 and G2) or G3');
tree.type % 'or'
numel(tree.children) % 2
See also: isDnfGrRule, grRuleToDNF, grRuleToString
parseRAVENargs#
function args = parseRAVENargs(rawArgs, spec)
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.
Parameters
rawArgs: cellthe varargin of the function, i.e. whatever was supplied after the required positional arguments.
spec: cellan N-by-2 or N-by-3 cell array describing the optional parameters, one per row:
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.
Returns
args: structa struct with one field per parameter name, holding the resolved value.
Notes
Calling convention is resolved as follows:
If rawArgs is empty, all parameters take their defaults.
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.
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.
This means three styles are accepted interchangeably:
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.
Examples
% inside exportToExcelFormat(model, varargin):
p = parseRAVENargs(varargin, { ...
"fileName", []; ...
"sortIds", false});
fileName = p.fileName;
sortIds = p.sortIds;
% the caller may use any of these:
exportToExcelFormat(model, "model.xlsx", true) % positional
exportToExcelFormat(model, "sortIds", true) % named
exportToExcelFormat(model, "model.xlsx", "sortIds", true) % hybrid
printOrange#
function orangeString = printOrange(stringToPrint)
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.
Parameters
stringToPrint: charstring that should be printed 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.
Returns
orangeString: charthe input string wrapped with the formatting codes for orange colour.
Examples
printOrange(stringToPrint);
ravenList#
function msg = ravenList(header, items, trim)
Format a header and item list for warning() or error().
Parameters
header: charmessage header string.
items: cellcell array of items to list below the header.
trim: logicalcap the list at 10 items (default true).
Returns
msg: charheader + newline + tab-indented items, ready to pass to warning() or error() as the format string.
Examples
warning("RAVEN:warning", "%s", ravenList("Missing metabolites:", badMets));
error("RAVEN:badInput", "%s", ravenList("Invalid reactions:", badRxns, false));
ravenModelFields#
function reg = ravenModelFields()
Declarative registry of all RAVEN model struct fields.
Returns a struct array. Each element describes one field:
.name - field name (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:
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)
runRAVENtests#
function testResults = runRAVENtests
Run all RAVEN function tests.
Runs all unit tests found at RAVEN/test/function_tests, and prints output in the command window.
Returns
testResults: matlab.unittest.TestResultarray of test results returned by runtests.
Examples
testResults = runRAVENtests;
setRavenProgress#
function setRavenProgress(mode)
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.
Parameters
mode: charone 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.
'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.
Examples
setRavenProgress('log'); % e.g. on a compute cluster
setRavenProgress('off'); % silence all progress reporting
setRavenProgress('auto'); % restore the default behaviour
See also
progressReport