Skip to content

Remove quadratic terms from printing, equivalence searches and the analyser - #1479

Open
FinbarArgus wants to merge 9 commits into
cellml:mainfrom
FinbarArgus:perf/printer-analyser-scaling
Open

FinbarArgus wants to merge 9 commits into
cellml:mainfrom
FinbarArgus:perf/printer-analyser-scaling

Conversation

@FinbarArgus

@FinbarArgus FinbarArgus commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Addresses #1478.

Removes the quadratic (and, combined, cubic) terms that dominate printing, and part of analysing, models with many connected components. There's no change in behaviour: on the models below, printed models are byte-identical to main and every variable is classified the same by the analyser.

  • liveEquivalentVariables() (internal, a private friend of Variable, hidden from SWIG): a variable's live equivalent variables in one pass. The internal traversals use it instead of equivalentVariable(i) for i < equivalentVariableCount(), which is O(n^2) in the number of equivalences.
  • equivalentVariables() and the indirect-equivalence search keep a hash set of visited variables instead of std::find on a vector. The visiting order is unchanged.
  • createConnectionMap() stops at the first equivalent variable in the other component, visiting in the same order.
  • Variable::equivalenceConnectionId() only searches variables that have stored a non-empty connection id for a variable of the other component, since only those can give an id. It returns the same result, and for models without connection ids (the usual case) it does no search.
  • Printer: buildMaps() finds reverse pairs with a set lookup. printConnections() groups the variable pairs by component pair in one pass, and looks up the connection id once per connection (from its last pair, as before).
  • Analyser: internalVariable() finds an existing internal variable by its equivalence group from the analyser model's cache (Improve caching of equivalent variables in analyser model. #1389) instead of testing every internal variable.
  • XmlNode::convertToString() returns a plain text node's content directly (printable ASCII, tabs and new lines, no <, > or &, i.e. when xmlNodeDump() would output it unchanged). Anything else still goes through xmlNodeDump().

Timings (seconds, Release, GCC 11, libxml2 2.9.13), for models generated by circulatory_autogen: chains of finite-volume cells (each cell 4 components), and an open-loop arterial network:

model printModel main this PR analyseModel main this PR
arterial network (186 vessels) 3.74 0.066 2.64 2.29
50 cells 0.71 0.040 3.30 3.05
200 cells 31.2 0.18 15.1 12.9
400 cells 220 0.41 40.0 38.5

Most of the remaining analysis time is the validator re-parsing the MathML DTD for every math block, which #1477 addresses. The two combine well: with both, analyseModel takes 2.2 s for 400 cells.

All 75 test targets pass (built with TWAE=ON), and clang-format 18 reports no changes.

🤖 Generated with Claude Code

Finbar Argus and others added 3 commits September 30, 2026 09:02
Removes the quadratic and cubic terms that dominate printing and
analysing models with many connected components (e.g. hundreds of
components sharing a time variable and global constants). The output is
unchanged: printed models are byte-identical and every variable is
classified the same.

- liveEquivalentVariables(): one pass over a variable's live equivalent
  variables. Iterating with equivalentVariableCount() and
  equivalentVariable(i) is O(n^2) in the number of equivalences, since
  both walk (and lock) the whole weak-pointer list.
- equivalentVariables() and the indirect-equivalence search use a hash
  set of visited variables instead of std::find on a vector.
- createConnectionMap() stops at the first equivalent variable in the
  other component, visiting in the same order as before.
- Printer: buildMaps() checks for a reverse pair with a set lookup rather
  than a linear search, and printConnections() groups the variable pairs
  by component pair in one pass. A connection's id comes from its last
  variable pair, so it is the only one looked up.
- Analyser: internalVariable() finds an existing internal variable by
  its equivalence group (from the analyser model's cache) instead of
  testing every internal variable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Variable::equivalenceConnectionId() built a connection map for the two
components, searching the equivalence set of every variable of the first
component, and returned the first non-empty identifier. A variable can
only give an identifier if it has stored a non-empty one for a variable
of the second component, so only those variables are searched now. The
result is the same; for models without connection identifiers (the usual
case) no equivalence set is searched. This was quadratic in the size of
models with global variables, e.g. printing a 400-component model: 2.0 s
to 0.4 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The analyser and validator read the name or value in every ci and cn
element with convertToString()/convertToStrippedString(), which
serialised the text node with xmlNodeDump() into a new buffer. For a
text node of printable ASCII (plus tabs and new lines) with no '<', '>'
or '&', that output is the node's content, so return the content
directly. Anything else still goes through xmlNodeDump().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@hsorby

hsorby commented Sep 29, 2026

Copy link
Copy Markdown
Contributor

Claude, you need to run the coverage tests and either write tests for the uncovered lines and branches of code, or remove the code if it is unreachable.

Remove code that is unreachable:
- equivalentVariables() and recursiveEquivalentVariables(): no longer used
  since createConnectionMap() uses firstEquivalentVariableInComponent().
- Analyser: every variable of the model is in the analyser model's
  equivalent variables cache, so internalVariable() looks its group up with
  at() rather than handling a missing entry.
- XmlNode::convertToString(): a text node always has content.
- Variable::equivalenceConnectionId(): a candidate without an equivalent
  variable in the other component is kept as a nullptr pair, whose lookup
  gives no identifier, rather than being skipped.

Add tests for the reachable cases: connection identifiers within one
component, with a variable without a component, between indirectly
equivalent variables, after an identifier is removed, stored for a variable
that no longer exists or is no longer equivalent; and ci identifiers with a
carriage return, a non-ASCII character, '<', '>' and '&'.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@FinbarArgus

FinbarArgus commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks, done in 005f2a4. I (claude) ran the LLVM coverage as CI does (ninja llvm_coverage, clang 23 locally), and it now reports 100% regions, functions, lines and branches. (Locally, Printer.mathMLWithSyntaxError, Printer.mathMLInResetWithSyntaxError and Parser.invalidXMLElements fail on main as well, because of a newer libxml2's error wording. So I ran every test binary and merged the profiles rather than stopping at the first failure. main measured the same way is also at 100%.)

Removed as unreachable:

  • equivalentVariables() / recursiveEquivalentVariables(): nothing uses them any more.
  • Analyser internalVariable(): every variable of the model is in the analyser model's equivalence cache, so it uses at() instead of handling a missing entry.
  • XmlNode::convertToString(): the content != nullptr check, since a text node always has content.
  • Variable::equivalenceConnectionId(): the nullptr check on a candidate's equivalent variable. A nullptr pair's lookup gives no identifier anyway.

New tests for the reachable cases:

  • Connection identifiers within one component, with a component-less variable, between indirectly equivalent variables, after an identifier is removed, stored for a variable that no longer exists, and stored for one that is no longer equivalent.
  • ci identifiers with a carriage return, a non-ASCII character, <, > and &, for the convertToString() fallback.

The expected values in the new tests are what main gives, and the printed models and analyses of the benchmark models are still identical to main.

@hsorby

hsorby commented Sep 29, 2026

Copy link
Copy Markdown
Contributor

Hi Claude, me again. It seems the Windows test machine didn’t like the invalidMathMLVariablesWithEscapedOrNonAsciiCharacters test. It seems it stalled and never finished, ctest timed it out after 120 seconds. Can you investigate why Windows couldn’t complete the test but other platforms can (Linux, macOS).

A char with the top bit set, e.g. a byte of a UTF-8 encoded non-ASCII
character, is negative, and passing it to isspace() is undefined
behaviour. MSVC's debug runtime asserts on it, which made the new test
with a ci identifier ending in a non-ASCII character hang on Windows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@FinbarArgus

Copy link
Copy Markdown
Contributor Author

The Windows jobs timed out in Validator.invalidMathMLVariablesWithEscapedOrNonAsciiCharacters. XmlNode::convertToStrippedString() passed a plain char to isspace(), and the last byte of a UTF-8 encoded non-ASCII character is negative, which is undefined behaviour. MSVC's debug runtime asserts on it, so the test hung waiting on the assertion dialog. This bug was already in main; the new test is the first to hit it with a ci identifier ending in a non-ASCII character. Fixed in e1a9477 by passing an unsigned char. Linux tests and LLVM coverage (100%) are unchanged. The CI runs for this commit need approval to start.

Comment thread src/api/libcellml/variable.h Resolved

@hsorby hsorby left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A minor change requested plus one additional comment to be answered.

Comment thread src/variable.cpp Resolved
liveEquivalentVariables() is now a member of Variable::VariableImpl, and
the indirect-equivalence search a static member, so variable.h is
unchanged. The printer and firstEquivalentVariableInComponent() iterate
with equivalentVariableCount() and equivalentVariable(i) again: they are
no longer on a quadratic path (connection identifiers are only searched
for where one is stored), and printing a 400-component model takes the
same time as with the helper.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comment thread src/variable.cpp Resolved
Finbar Argus and others added 2 commits September 30, 2026 15:04
… docs

Rewrite comments that compared the code with what it replaced so they
describe what it does, and put the doxygen comment for
haveEquivalentVariables() back with its definition.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
hsorby
hsorby previously approved these changes Sep 30, 2026

@hsorby hsorby left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this looks good now.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

Two new indexed equivalence traversals retain quadratic behavior in the performance-critical paths.

Review effort: Balanced
Findings: 2 Medium severity

Open (2)
What changed in this PR

Optimizes equivalence traversal, connection printing, analyser lookup, and XML text serialization.

Changes:

  • Adds hashed equivalence tracking and cached analyser-group lookup.
  • Groups printer connections and narrows connection-ID searches.
  • Adds XML text fast paths and regression tests.
File Description
src/​analyser.cpp Uses cached equivalence groups.
src/​analyser_p.h Stores internal variables by group.
src/​printer.cpp Optimizes connection grouping and pair lookup.
src/​utilities.cpp Adds component-targeted equivalence traversal.
src/​utilities.h Declares the targeted traversal helper.
src/​variable.cpp Optimizes equivalence and connection-ID searches.
src/​variable_p.h Declares internal traversal helpers.
src/​xmlnode.cpp Fast-paths plain text serialization.
tests/​connection/​connection.cpp Covers connection-ID edge cases.
tests/​validator/​validator.cpp Covers escaped and non-ASCII MathML text.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread src/printer.cpp
Comment on lines +159 to 160
for (size_t j = 0, n = variable->equivalentVariableCount(); j < n; ++j) {
VariablePtr equivalentVariable = variable->equivalentVariable(j);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Measured with one variable mapped to N components: printing took 1.7 / 12 / 94 s at N = 1000 / 2000 / 4000. Rather than expose the private helper (we're keeping variable.h unchanged), 5a167b9 makes equivalentVariable(i) and equivalentVariableCount() constant time: a deleted variable marks each of its equivalent variables, and unmarked variables index their list directly. Printing now takes 0.08 / 0.30 / 1.2 s, and output is unchanged.

Comment thread src/utilities.cpp
Comment on lines +1029 to +1030
for (size_t i = 0, n = variable->equivalentVariableCount(); i < n; ++i) {
auto equivalentVariable = variable->equivalentVariable(i);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Measured with one variable mapped to N components: printing took 1.7 / 12 / 94 s at N = 1000 / 2000 / 4000. Rather than expose the private helper (we're keeping variable.h unchanged), 5a167b9 makes equivalentVariable(i) and equivalentVariableCount() constant time: a deleted variable marks each of its equivalent variables, and unmarked variables index their list directly. Printing now takes 0.08 / 0.30 / 1.2 s, and output is unchanged.

…tant time

Each call walked the list of weak references from the start, skipping
any that had expired, so a loop over a variable's d equivalent variables
cost O(d^2). This loop is in the printer and in the depth-first search
for connection identifiers, so printing a model with one variable mapped
to N components grew as N^3.

An equivalence is always held by both of its variables, so a variable
that is deleted now marks each of its equivalent variables as possibly
holding an expired reference. A variable that isn't marked has no
expired references, and the accessors index its list directly.
cleanExpiredVariables() clears the mark. The public header is unchanged.

Printing a model whose time variable is mapped to 4000 components drops
from 94 s to 1.2 s. The printed and analysed benchmark models are
identical to main.

Also restores the blank lines in the haveEquivalentVariables() comment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants