Utilities#

MATLAB functions in RAVEN/src/utils of the RAVEN toolbox.

Functions#

Function

Summary

convertCharArray

Ensure input is a cell array of character vectors.

deprecationWarning

Warn once per session that a function is deprecated.

grRuleToDNF

Convert a grRule to disjunctive normal form.

grRuleToString

Render a grRule syntax tree back to a string.

isDnfGrRule

Test whether a grRule is in disjunctive normal form.

legacyMethodNotice

Warn once that a function has a recommended replacement.

parallelWorkersRAVEN

Return the parfor worker count for a given setting.

parseGrRule

Parse a grRule into a syntax tree.

parseRAVENargs

Resolve optional arguments passed positionally or by name.

printOrange

Print an orange-coloured string to the MATLAB Command Window.

ravenList

Format a header and a list of items for warning() or error().

ravenModelFields

Declarative registry of all RAVEN model struct fields.

runRAVENtests

Run all RAVEN function tests.

setRavenProgress

Set the RAVEN progress-reporting backend.

Reference#

convertCharArray#

function inputConverted = convertCharArray(funcInput)

Ensure input is a cell array of character vectors.

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

funcInput : char or cell or string

function input that should be checked.

Returns

inputConverted : cell

cell array of character vectors, or [] if funcInput is empty.

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 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, for example '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 struct

a grRule, or a tree from parseGrRule. A grRule is read by parseGrRule: 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.

Returns

clauses : cell

one cell array of gene IDs per AND-clause. An empty rule yields {}. A rule with no OR anywhere yields a single clause.

Notes

A malformed rule (an operator without an operand, unbalanced or empty parentheses, two genes without an operator between them) raises RAVEN:badGrRule.

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 change the rule.

The number of clauses is the product of the OR-arities across a complex, 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

    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, 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

tree : struct

a tree from parseGrRule. An empty tree yields ''.

Returns

rule : char

the 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.

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

rule : char or string or struct

a grRule, or a tree from parseGrRule. An empty rule is trivially DNF.

Returns

tf : logical

true 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)

Warn once that a function has a recommended replacement.

For functions that remain supported and maintained but have a recommended replacement for new work. Unlike deprecationWarning, the notice announces no removal.

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. The notice is issued once per name.

preferred : char

name of the recommended replacement for new work, written as in the warning text.

Examples

legacyMethodNotice('getINITModel','ftINIT');

See also

deprecationWarning

parallelWorkersRAVEN#

function nW = parallelWorkersRAVEN(runParallel)

Return the parfor worker count for a given setting.

Returns the value for the maximum-workers argument of parfor:

nW = parallelWorkersRAVEN(runParallel);
parfor (i = 1:N, nW)
    ...
end

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

true to use parallel workers, false for sequential execution.

Returns

nW : double

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).

parseGrRule#

function tree=parseGrRule(rule)

Parse a grRule into a syntax tree.

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, 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.

Returns

tree : struct

a scalar struct with fields:

  • 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

AND binds tighter than OR. The grammar is:

expr   := term ( OR term )*
term   := factor ( AND factor )*
factor := gene | '(' expr ')'

Malformed rules raise the error RAVEN:badGrRule. findPotentialErrors catches this error and reports the rule.

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 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, 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:

  • 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 (the default when the parameter was not supplied) and should error on an invalid value, for example @mustBeNumeric. [] means no validation.

Returns

args : struct

a struct with one field per parameter name, holding the resolved value.

Notes

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 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.

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

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

% inside exportToExcelFormat(model, varargin):
p = parseRAVENargs(varargin, { ...
    "fileName", []; ...
    "sortIds",  false});
fileName = p.fileName;
sortIds  = p.sortIds;

% 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

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. 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 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.

Returns

orangeString : char

the input string wrapped with the formatting codes for orange colour.

Examples

printOrange(stringToPrint);

ravenList#

function msg = ravenList(header, items, trim)

Format a header and a list of items for warning() or error().

Parameters

header : char

message header string.

items : cell

cell array of items, listed one per line after the header.

trim : logical

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, 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

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 with one element per field. The elements have the
fields:
  .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. 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 the compartments are permuted, the
      values of these arrays are remapped; the arrays are not permuted

runRAVENtests#

function testResults = runRAVENtests

Run all RAVEN function tests.

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

testResults : matlab.unittest.TestResult

array 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 stored as the RAVEN preference progressBar and persists across MATLAB sessions.

Parameters

mode : char

one of:

  • '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, which are readable in redirected logs and on headless servers.

  • 'none' or 'off' : never show progress.

Examples

setRavenProgress('log');   % for example on a compute cluster
setRavenProgress('off');   % silence all progress reporting
setRavenProgress('auto');  % restore the default behaviour

See also

progressReport