From 85220cba69deb1fd0ce5aa75dc0c2af79425887a Mon Sep 17 00:00:00 2001 From: Finbar Argus Date: Tue, 29 Sep 2026 18:22:25 +1300 Subject: [PATCH 1/9] Speed up printing, analysing and equivalence searches of large models 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 --- src/analyser.cpp | 24 ++++++++-- src/analyser_p.h | 1 + src/api/libcellml/variable.h | 5 ++ src/printer.cpp | 93 ++++++++++++++++++------------------ src/utilities.cpp | 54 ++++++++++++++++----- src/utilities.h | 12 +++++ src/variable.cpp | 32 ++++++++++--- 7 files changed, 153 insertions(+), 68 deletions(-) diff --git a/src/analyser.cpp b/src/analyser.cpp index 1c3594e124..04105a4d47 100644 --- a/src/analyser.cpp +++ b/src/analyser.cpp @@ -410,11 +410,22 @@ AnalyserInternalVariablePtr Analyser::AnalyserImpl::internalVariable(const Varia return rawPtrIt->second; } - for (const auto &internalVariable : mInternalVariables) { - if (mAnalyserModel->areEquivalentVariables(variable, internalVariable->mVariable)) { - mInternalVariableMap[rawPtr] = internalVariable; + // Two variables are equivalent if and only if they are in the same group of + // the analyser model's equivalent variables cache, so look the internal + // variable up by group, rather than testing every internal variable (which + // is quadratic in the number of variables). A variable that is not in the + // cache is only equivalent to itself. + + const auto &groups = mAnalyserModel->mPimpl->mEquivalentVariableCache; + auto groupIt = groups.find(rawPtr); + + if (groupIt != groups.end()) { + auto internalVariableIt = mInternalVariableGroupMap.find(groupIt->second); - return internalVariable; + if (internalVariableIt != mInternalVariableGroupMap.end()) { + mInternalVariableMap[rawPtr] = internalVariableIt->second; + + return internalVariableIt->second; } } @@ -427,6 +438,10 @@ AnalyserInternalVariablePtr Analyser::AnalyserImpl::internalVariable(const Varia mInternalVariableMap[rawPtr] = res; + if (groupIt != groups.end()) { + mInternalVariableGroupMap[groupIt->second] = res; + } + return res; } @@ -2323,6 +2338,7 @@ void Analyser::AnalyserImpl::analyseModel(const ModelPtr &model) mInternalVariables.clear(); mInternalVariableMap.clear(); + mInternalVariableGroupMap.clear(); mInternalEquations.clear(); mCiCnUnits.clear(); diff --git a/src/analyser_p.h b/src/analyser_p.h index 2b821f2b86..6f7bdc0624 100644 --- a/src/analyser_p.h +++ b/src/analyser_p.h @@ -162,6 +162,7 @@ class Analyser::AnalyserImpl: public Logger::LoggerImpl AnalyserInternalVariablePtrs mInternalVariables; std::unordered_map mInternalVariableMap; + std::unordered_map mInternalVariableGroupMap; AnalyserInternalEquationPtrs mInternalEquations; GeneratorProfilePtr mGeneratorProfile = GeneratorProfile::create(); diff --git a/src/api/libcellml/variable.h b/src/api/libcellml/variable.h index 5bfa4630c9..1191e917e7 100644 --- a/src/api/libcellml/variable.h +++ b/src/api/libcellml/variable.h @@ -17,6 +17,7 @@ limitations under the License. #pragma once #include +#include #include "libcellml/exportdefinitions.h" #include "libcellml/namedentity.h" @@ -478,6 +479,10 @@ class LIBCELLML_EXPORT Variable: public NamedEntity VariableImpl *pFunc(); /**< Getter for private implementation pointer, @private. */ const VariableImpl *pFunc() const; /**< Const getter for private implementation pointer, @private. */ + +#ifndef SWIG + friend std::vector liveEquivalentVariables(const Variable &variable); /**< Internal traversal helper, @private. */ +#endif }; } // namespace libcellml diff --git a/src/printer.cpp b/src/printer.cpp index 6a39d3a5f5..6a3fa78db3 100644 --- a/src/printer.cpp +++ b/src/printer.cpp @@ -16,7 +16,9 @@ limitations under the License. #include "libcellml/printer.h" +#include #include +#include #include #include @@ -71,42 +73,34 @@ std::string printMapVariables(const VariablePairPtr &variablePair, IdList &idLis std::string printConnections(const ComponentMap &componentMap, const VariableMap &variableMap, IdList &idList, bool autoIds) { - std::string connections; - ComponentMap serialisedComponentMap; - size_t componentMapIndex1 = 0; - for (auto iterPair = componentMap.begin(); iterPair < componentMap.end(); ++iterPair) { - ComponentPtr currentComponent1 = iterPair->first; - ComponentPtr currentComponent2 = iterPair->second; - ComponentPair currentComponentPair = std::make_pair(currentComponent1, currentComponent2); - // Check whether this set of connections has already been serialised. - bool pairFound = false; - for (const auto &serialisedIterPair : serialisedComponentMap) { - if (serialisedIterPair == currentComponentPair) { - pairFound = true; - break; - } - } - // Continue to the next component pair if the current pair has already been serialised. - if (pairFound) { - ++componentMapIndex1; - continue; + // Group the variable equivalence pairs by their pair of parent components, in order of first appearance, in a + // single pass (rather than rescanning the remaining pairs for each new component pair, which is quadratic in the + // number of pairs). + std::vector> groups; + std::map, size_t> groupIndex; + for (size_t index = 0; index < componentMap.size(); ++index) { + auto key = std::make_pair(componentMap[index].first.get(), componentMap[index].second.get()); + auto found = groupIndex.find(key); + if (found == groupIndex.end()) { + groupIndex.emplace(key, groups.size()); + groups.push_back({index}); + } else { + groups[found->second].push_back(index); } + } + + std::string connections; + for (const auto &group : groups) { + ComponentPtr currentComponent1 = componentMap[group.front()].first; + ComponentPtr currentComponent2 = componentMap[group.front()].second; std::string mappingVariables; - const VariablePairPtr &variablePair = variableMap.at(componentMapIndex1); - std::string connectionId = Variable::equivalenceConnectionId(variablePair->variable1(), variablePair->variable2()); - mappingVariables += printMapVariables(variablePair, idList, autoIds); - // Check for subsequent variable equivalence pairs with the same parent components. - size_t componentMapIndex2 = componentMapIndex1 + 1; - for (auto iterPair2 = iterPair + 1; iterPair2 < componentMap.end(); ++iterPair2) { - ComponentPtr nextComponent1 = iterPair2->first; - ComponentPtr nextComponent2 = iterPair2->second; - const VariablePairPtr &variablePair2 = variableMap.at(componentMapIndex2); - if ((currentComponent1 == nextComponent1) && (currentComponent2 == nextComponent2)) { - mappingVariables += printMapVariables(variablePair2, idList, autoIds); - connectionId = Variable::equivalenceConnectionId(variablePair2->variable1(), variablePair2->variable2()); - } - ++componentMapIndex2; + for (size_t index : group) { + mappingVariables += printMapVariables(variableMap.at(index), idList, autoIds); } + // The connection takes its identifier from the last variable pair of the group (as it always has). Only that + // pair's identifier is used, so it is the only one that needs to be looked up. + const VariablePairPtr &lastVariablePair = variableMap.at(group.back()); + std::string connectionId = Variable::equivalenceConnectionId(lastVariablePair->variable1(), lastVariablePair->variable2()); // Serialise out the new connection. connections += "name() + "\""; if (currentComponent2 != nullptr) { @@ -118,8 +112,6 @@ std::string printConnections(const ComponentMap &componentMap, const VariableMap connections += " id=\"" + makeUniqueId(idList) + "\""; } connections += ">" + mappingVariables + ""; - serialisedComponentMap.push_back(currentComponentPair); - ++componentMapIndex1; } return connections; @@ -160,18 +152,20 @@ std::string Printer::PrinterImpl::printMath(const std::string &math) return ""; } -void buildMapsForComponentsVariables(const ComponentPtr &component, ComponentMap &componentMap, VariableMap &variableMap) +using VariablePairSet = std::set>; + +void buildMapsForComponentsVariables(const ComponentPtr &component, ComponentMap &componentMap, VariableMap &variableMap, + VariablePairSet &addedPairs) { for (size_t i = 0; i < component->variableCount(); ++i) { VariablePtr variable = component->variable(i); - for (size_t j = 0; j < variable->equivalentVariableCount(); ++j) { - VariablePtr equivalentVariable = variable->equivalentVariable(j); + for (const auto &equivalentVariable : liveEquivalentVariables(*variable)) { VariablePairPtr variablePair = VariablePair::create(variable, equivalentVariable); - auto pairFound = std::find_if(variableMap.begin(), variableMap.end(), - [variable, equivalentVariable](const VariablePairPtr &in) { - return (in->variable1() == equivalentVariable) && (in->variable2() == variable); - }); - if (pairFound == variableMap.end()) { + // Skip the pair if its reverse is already in the VariableMap (a set lookup, rather than a linear search of + // the map, which is quadratic in the number of equivalences). + bool pairFound = addedPairs.count(std::make_pair(equivalentVariable.get(), variable.get())) != 0; + if (!pairFound) { + addedPairs.emplace(variable.get(), equivalentVariable.get()); // Add new unique variable equivalence pair to the VariableMap. variableMap.push_back(variablePair); // Get parent components. @@ -185,15 +179,22 @@ void buildMapsForComponentsVariables(const ComponentPtr &component, ComponentMap } } -void buildMaps(const ComponentEntityPtr &componentEntity, ComponentMap &componentMap, VariableMap &variableMap) +void buildMaps(const ComponentEntityPtr &componentEntity, ComponentMap &componentMap, VariableMap &variableMap, + VariablePairSet &addedPairs) { for (size_t i = 0; i < componentEntity->componentCount(); ++i) { ComponentPtr component = componentEntity->component(i); - buildMapsForComponentsVariables(component, componentMap, variableMap); - buildMaps(component, componentMap, variableMap); + buildMapsForComponentsVariables(component, componentMap, variableMap, addedPairs); + buildMaps(component, componentMap, variableMap, addedPairs); } } +void buildMaps(const ComponentEntityPtr &componentEntity, ComponentMap &componentMap, VariableMap &variableMap) +{ + VariablePairSet addedPairs; + buildMaps(componentEntity, componentMap, variableMap, addedPairs); +} + std::string Printer::PrinterImpl::printUnits(const UnitsPtr &units, IdList &idList, bool autoIds) { std::string repr; diff --git a/src/utilities.cpp b/src/utilities.cpp index b589391739..3bcda8ac42 100644 --- a/src/utilities.cpp +++ b/src/utilities.cpp @@ -24,6 +24,7 @@ limitations under the License. #include #include #include +#include #include #include "libcellml/analyserequation.h" @@ -1015,6 +1016,30 @@ std::string makeUniqueId(IdList &idList) return id; } +/** + * @brief Find the first variable of a component in a variable's equivalence set. + * + * Visits the equivalence set in the same order as equivalentVariables() (the variable itself, then depth first), but + * stops at the first variable owned by @p component, rather than collecting the whole set first. + */ +VariablePtr firstEquivalentVariableInComponent(const VariablePtr &variable, const ComponentPtr &component, + std::unordered_set &visited) +{ + for (const auto &equivalentVariable : liveEquivalentVariables(*variable)) { + if (visited.insert(equivalentVariable.get()).second) { + if (owningComponent(equivalentVariable) == component) { + return equivalentVariable; + } + auto found = firstEquivalentVariableInComponent(equivalentVariable, component, visited); + if (found != nullptr) { + return found; + } + } + } + + return nullptr; +} + ConnectionMap createConnectionMap(const VariablePtr &variable1, const VariablePtr &variable2) { ConnectionMap map; @@ -1024,10 +1049,14 @@ ConnectionMap createConnectionMap(const VariablePtr &variable1, const VariablePt if ((component1 != nullptr) && (component2 != nullptr)) { for (size_t i = 0; i < component1->variableCount(); ++i) { auto v = component1->variable(i); - for (const auto &vEquiv : equivalentVariables(v)) { - if (owningComponent(vEquiv) == component2) { - map.insert(std::make_pair(v, vEquiv)); - } + // The map keeps the first equivalent variable in component2, in the order of equivalentVariables(v). + VariablePtr vEquiv = (component1 == component2) ? v : nullptr; + if (vEquiv == nullptr) { + std::unordered_set visited = {v.get()}; + vEquiv = firstEquivalentVariableInComponent(v, component2, visited); + } + if (vEquiv != nullptr) { + map.insert(std::make_pair(v, vEquiv)); } } } @@ -1035,24 +1064,27 @@ ConnectionMap createConnectionMap(const VariablePtr &variable1, const VariablePt return map; } -void recursiveEquivalentVariables(const VariablePtr &variable, std::vector &equivalentVariables) +void recursiveEquivalentVariables(const VariablePtr &variable, std::vector &equivalentVariables, + std::unordered_set &visited) { - for (size_t i = 0; i < variable->equivalentVariableCount(); ++i) { - VariablePtr equivalentVariable = variable->equivalentVariable(i); - - if (std::find(equivalentVariables.begin(), equivalentVariables.end(), equivalentVariable) == equivalentVariables.end()) { + for (const auto &equivalentVariable : liveEquivalentVariables(*variable)) { + if (visited.insert(equivalentVariable.get()).second) { equivalentVariables.push_back(equivalentVariable); - recursiveEquivalentVariables(equivalentVariable, equivalentVariables); + recursiveEquivalentVariables(equivalentVariable, equivalentVariables, visited); } } } std::vector equivalentVariables(const VariablePtr &variable) { + // The visited set gives constant-time membership tests, so collecting an equivalence set of size n is O(n), not + // O(n^2) (e.g., a time variable that is equivalent across every component of a large model). The order of the + // result is unchanged. std::vector res = {variable}; + std::unordered_set visited = {variable.get()}; - recursiveEquivalentVariables(variable, res); + recursiveEquivalentVariables(variable, res, visited); return res; } diff --git a/src/utilities.h b/src/utilities.h index 888447f1f2..b17531617b 100644 --- a/src/utilities.h +++ b/src/utilities.h @@ -700,6 +700,18 @@ ConnectionMap createConnectionMap(const VariablePtr &variable1, const VariablePt */ std::vector equivalentVariables(const VariablePtr &variable); +/** + * @brief The live equivalent variables of @p variable, in order, in one pass. + * + * Same as calling equivalentVariable(i) for i from 0 to equivalentVariableCount() - 1, but O(n) rather than O(n^2) + * in the number of equivalences. + * + * @param variable The variable. + * + * @return The equivalent variables. + */ +std::vector liveEquivalentVariables(const Variable &variable); + /** * @brief Test the given @p entities are equal to entities in @p owner. * diff --git a/src/variable.cpp b/src/variable.cpp index 06983ee978..6e928e69b2 100644 --- a/src/variable.cpp +++ b/src/variable.cpp @@ -19,6 +19,7 @@ limitations under the License. #include #include #include +#include #include #include "libcellml/units.h" @@ -178,6 +179,23 @@ size_t Variable::equivalentVariableCount() const return count; } +std::vector liveEquivalentVariables(const Variable &variable) +{ + // The live equivalent variables in one pass, in the order of equivalentVariable(0), equivalentVariable(1), ... + // Iterating with equivalentVariableCount() and equivalentVariable(i) is O(n^2) in the number of equivalences, since + // both walk the list, which matters for variables equivalent to many others (e.g., a time variable or a global + // constant shared by every component of a large model). + std::vector res; + res.reserve(variable.pFunc()->mEquivalentVariables.size()); + for (const auto &variableWeak : variable.pFunc()->mEquivalentVariables) { + auto equivalentVariable = variableWeak.lock(); + if (equivalentVariable != nullptr) { + res.push_back(equivalentVariable); + } + } + return res; +} + bool Variable::hasEquivalentVariable(const VariablePtr &equivalentVariable, bool considerIndirectEquivalences) const { return pFunc()->hasEquivalentVariable(equivalentVariable, considerIndirectEquivalences); @@ -218,13 +236,13 @@ bool Variable::VariableImpl::hasEquivalentVariable(const VariablePtr &equivalent * * @param variable1 The first variable to test. * @param variable2 The second variable to test. - * @param testedVariables Vector of previously tested variables. + * @param testedVariables Set of previously tested variables. * * @return True if the two given variables are equivalent, false otherwise. */ bool haveEquivalentVariables(const Variable *variable1, const Variable *variable2, - std::vector &testedVariables) + std::unordered_set &testedVariables) { if (variable1 == variable2) { return true; @@ -234,12 +252,12 @@ bool haveEquivalentVariables(const Variable *variable1, return false; } - testedVariables.push_back(variable2); + testedVariables.insert(variable2); - for (size_t i = 0; i < variable2->equivalentVariableCount(); ++i) { - Variable *equivalentVariable2 = variable2->equivalentVariable(i).get(); + for (const auto &equivalentVariable2Ptr : liveEquivalentVariables(*variable2)) { + Variable *equivalentVariable2 = equivalentVariable2Ptr.get(); - if ((std::find(testedVariables.begin(), testedVariables.end(), equivalentVariable2) == testedVariables.end()) + if ((testedVariables.count(equivalentVariable2) == 0) && haveEquivalentVariables(variable1, equivalentVariable2, testedVariables)) { return true; } @@ -254,7 +272,7 @@ bool Variable::VariableImpl::hasIndirectEquivalentVariable(const VariablePtr &eq return false; } - std::vector testedVariables; + std::unordered_set testedVariables; return haveEquivalentVariables(mVariable, equivalentVariable.get(), testedVariables); } From 367ec355295de1f83c7355a67f658f198e6d9130 Mon Sep 17 00:00:00 2001 From: Finbar Argus Date: Tue, 29 Sep 2026 18:36:09 +1300 Subject: [PATCH 2/9] Only search for connection identifiers where one can be stored 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 --- src/utilities.cpp | 15 ++++++++++----- src/utilities.h | 13 +++++++++++++ src/variable.cpp | 41 +++++++++++++++++++++++++++++++++++------ 3 files changed, 58 insertions(+), 11 deletions(-) diff --git a/src/utilities.cpp b/src/utilities.cpp index 3bcda8ac42..6a40a0bc8b 100644 --- a/src/utilities.cpp +++ b/src/utilities.cpp @@ -1040,6 +1040,15 @@ VariablePtr firstEquivalentVariableInComponent(const VariablePtr &variable, cons return nullptr; } +VariablePtr firstEquivalentVariableInComponent(const VariablePtr &variable, const ComponentPtr &component) +{ + if (owningComponent(variable) == component) { + return variable; + } + std::unordered_set visited = {variable.get()}; + return firstEquivalentVariableInComponent(variable, component, visited); +} + ConnectionMap createConnectionMap(const VariablePtr &variable1, const VariablePtr &variable2) { ConnectionMap map; @@ -1050,11 +1059,7 @@ ConnectionMap createConnectionMap(const VariablePtr &variable1, const VariablePt for (size_t i = 0; i < component1->variableCount(); ++i) { auto v = component1->variable(i); // The map keeps the first equivalent variable in component2, in the order of equivalentVariables(v). - VariablePtr vEquiv = (component1 == component2) ? v : nullptr; - if (vEquiv == nullptr) { - std::unordered_set visited = {v.get()}; - vEquiv = firstEquivalentVariableInComponent(v, component2, visited); - } + VariablePtr vEquiv = firstEquivalentVariableInComponent(v, component2); if (vEquiv != nullptr) { map.insert(std::make_pair(v, vEquiv)); } diff --git a/src/utilities.h b/src/utilities.h index b17531617b..7920f7a6d6 100644 --- a/src/utilities.h +++ b/src/utilities.h @@ -712,6 +712,19 @@ std::vector equivalentVariables(const VariablePtr &variable); */ std::vector liveEquivalentVariables(const Variable &variable); +/** + * @brief The first variable of @p component in the equivalence set of @p variable. + * + * The equivalence set is visited in the order of equivalentVariables(@p variable), stopping at the first variable + * owned by @p component (@p variable itself if it is owned by @p component). + * + * @param variable The variable. + * @param component The component. + * + * @return The first equivalent variable owned by @p component, or @c nullptr if there is none. + */ +VariablePtr firstEquivalentVariableInComponent(const VariablePtr &variable, const ComponentPtr &component); + /** * @brief Test the given @p entities are equal to entities in @p owner. * diff --git a/src/variable.cpp b/src/variable.cpp index 6e928e69b2..c232932861 100644 --- a/src/variable.cpp +++ b/src/variable.cpp @@ -24,6 +24,7 @@ limitations under the License. #include "libcellml/units.h" +#include "commonutils.h" #include "utilities.h" #include "variable_p.h" @@ -467,14 +468,42 @@ std::string Variable::equivalenceConnectionId(const VariablePtr &variable1, cons std::string id; if ((variable1 != nullptr) && (variable2 != nullptr)) { if (deepSearch) { - if (variable1->hasEquivalentVariable(variable2, true)) { - auto map = createConnectionMap(variable1, variable2); + if (variable1->hasEquivalentVariable(variable2, false) || variable1->hasEquivalentVariable(variable2, true)) { + // Same result as looking the identifier up for every pair of createConnectionMap(variable1, variable2), + // in the map's order, but a variable of the first component 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 + // for their equivalent variable in the second component. Models rarely store connection identifiers, + // and searching every variable's equivalence set is quadratic in the size of large models. + ComponentPtr component1 = owningComponent(variable1); + ComponentPtr component2 = owningComponent(variable2); + if ((component1 != nullptr) && (component2 != nullptr)) { + ConnectionMap candidates; + for (size_t i = 0; i < component1->variableCount(); ++i) { + auto v = component1->variable(i); + bool candidate = false; + for (const auto &entry : v->pFunc()->mConnectionIdMap) { + if (!entry.second.empty()) { + auto storedFor = entry.first.lock(); + if ((storedFor != nullptr) && (owningComponent(storedFor) == component2)) { + candidate = true; + break; + } + } + } + if (candidate) { + auto vEquiv = firstEquivalentVariableInComponent(v, component2); + if (vEquiv != nullptr) { + candidates.emplace(v, vEquiv); + } + } + } - for (auto &it : map) { - id = it.first->pFunc()->equivalentConnectionId(it.second); + for (auto &it : candidates) { + id = it.first->pFunc()->equivalentConnectionId(it.second); - if (!id.empty()) { - return id; + if (!id.empty()) { + return id; + } } } From 739ba83bddad96d7de309d704190681f03869b00 Mon Sep 17 00:00:00 2001 From: Finbar Argus Date: Tue, 29 Sep 2026 18:42:51 +1300 Subject: [PATCH 3/9] XmlNode::convertToString(): return plain text nodes directly 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 --- src/xmlnode.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/xmlnode.cpp b/src/xmlnode.cpp index 93a273ac02..75b72c16ff 100644 --- a/src/xmlnode.cpp +++ b/src/xmlnode.cpp @@ -310,6 +310,23 @@ XmlNodePtr XmlNode::parent() const std::string XmlNode::convertToString() const { + // Fast path for a text node whose content xmlNodeDump() would output unchanged: printable ASCII, tabs and new + // lines, with no characters that it escapes ('<', '>', '&' and carriage returns). This is the common case of the + // content of a ci or cn element, and it avoids a buffer allocation and a serialisation per call. + if ((mPimpl->mXmlNodePtr->type == XML_TEXT_NODE) && (mPimpl->mXmlNodePtr->content != nullptr)) { + const auto *content = reinterpret_cast(mPimpl->mXmlNodePtr->content); + bool plain = true; + for (const char *c = content; *c != '\0'; ++c) { + auto u = static_cast(*c); + if (((u < 0x20) && (u != '\t') && (u != '\n')) || (u > 0x7e) || (u == '<') || (u == '>') || (u == '&')) { + plain = false; + break; + } + } + if (plain) { + return content; + } + } xmlKeepBlanksDefault(1); xmlBufferPtr buffer = xmlBufferCreate(); xmlNodeDump(buffer, mPimpl->mXmlNodePtr->doc, mPimpl->mXmlNodePtr, 0, 0); From 005f2a489504a29607dc686ffec19ede0ab0c161 Mon Sep 17 00:00:00 2001 From: Finbar Argus Date: Wed, 30 Sep 2026 09:47:39 +1300 Subject: [PATCH 4/9] Full test coverage for the equivalence and printer changes 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 --- src/analyser.cpp | 27 +++--- src/utilities.cpp | 32 +------ src/utilities.h | 16 +--- src/variable.cpp | 6 +- src/xmlnode.cpp | 2 +- tests/connection/connection.cpp | 147 ++++++++++++++++++++++++++++++++ tests/validator/validator.cpp | 37 ++++++++ 7 files changed, 203 insertions(+), 64 deletions(-) diff --git a/src/analyser.cpp b/src/analyser.cpp index 04105a4d47..dc23a2b5bf 100644 --- a/src/analyser.cpp +++ b/src/analyser.cpp @@ -411,22 +411,18 @@ AnalyserInternalVariablePtr Analyser::AnalyserImpl::internalVariable(const Varia } // Two variables are equivalent if and only if they are in the same group of - // the analyser model's equivalent variables cache, so look the internal - // variable up by group, rather than testing every internal variable (which - // is quadratic in the number of variables). A variable that is not in the - // cache is only equivalent to itself. + // the analyser model's equivalent variables cache, which has every variable + // of the model, so look the internal variable up by group, rather than + // testing every internal variable (which is quadratic in the number of + // variables). - const auto &groups = mAnalyserModel->mPimpl->mEquivalentVariableCache; - auto groupIt = groups.find(rawPtr); + auto group = mAnalyserModel->mPimpl->mEquivalentVariableCache.at(rawPtr); + auto internalVariableIt = mInternalVariableGroupMap.find(group); - if (groupIt != groups.end()) { - auto internalVariableIt = mInternalVariableGroupMap.find(groupIt->second); + if (internalVariableIt != mInternalVariableGroupMap.end()) { + mInternalVariableMap[rawPtr] = internalVariableIt->second; - if (internalVariableIt != mInternalVariableGroupMap.end()) { - mInternalVariableMap[rawPtr] = internalVariableIt->second; - - return internalVariableIt->second; - } + return internalVariableIt->second; } // No internal variable exists for the given variable, so create one, track @@ -437,10 +433,7 @@ AnalyserInternalVariablePtr Analyser::AnalyserImpl::internalVariable(const Varia mInternalVariables.push_back(res); mInternalVariableMap[rawPtr] = res; - - if (groupIt != groups.end()) { - mInternalVariableGroupMap[groupIt->second] = res; - } + mInternalVariableGroupMap[group] = res; return res; } diff --git a/src/utilities.cpp b/src/utilities.cpp index 6a40a0bc8b..079faeb308 100644 --- a/src/utilities.cpp +++ b/src/utilities.cpp @@ -1019,8 +1019,9 @@ std::string makeUniqueId(IdList &idList) /** * @brief Find the first variable of a component in a variable's equivalence set. * - * Visits the equivalence set in the same order as equivalentVariables() (the variable itself, then depth first), but - * stops at the first variable owned by @p component, rather than collecting the whole set first. + * Visits the equivalence set depth first, in the order of each variable's equivalent variables, and stops at the first + * variable owned by @p component. A visited set gives constant-time membership tests, so the search is O(n) in the size + * of the equivalence set (e.g., a time variable that is equivalent across every component of a large model). */ VariablePtr firstEquivalentVariableInComponent(const VariablePtr &variable, const ComponentPtr &component, std::unordered_set &visited) @@ -1058,7 +1059,7 @@ ConnectionMap createConnectionMap(const VariablePtr &variable1, const VariablePt if ((component1 != nullptr) && (component2 != nullptr)) { for (size_t i = 0; i < component1->variableCount(); ++i) { auto v = component1->variable(i); - // The map keeps the first equivalent variable in component2, in the order of equivalentVariables(v). + // The map keeps the first equivalent variable in component2 (v itself, then depth first). VariablePtr vEquiv = firstEquivalentVariableInComponent(v, component2); if (vEquiv != nullptr) { map.insert(std::make_pair(v, vEquiv)); @@ -1069,31 +1070,6 @@ ConnectionMap createConnectionMap(const VariablePtr &variable1, const VariablePt return map; } -void recursiveEquivalentVariables(const VariablePtr &variable, std::vector &equivalentVariables, - std::unordered_set &visited) -{ - for (const auto &equivalentVariable : liveEquivalentVariables(*variable)) { - if (visited.insert(equivalentVariable.get()).second) { - equivalentVariables.push_back(equivalentVariable); - - recursiveEquivalentVariables(equivalentVariable, equivalentVariables, visited); - } - } -} - -std::vector equivalentVariables(const VariablePtr &variable) -{ - // The visited set gives constant-time membership tests, so collecting an equivalence set of size n is O(n), not - // O(n^2) (e.g., a time variable that is equivalent across every component of a large model). The order of the - // result is unchanged. - std::vector res = {variable}; - std::unordered_set visited = {variable.get()}; - - recursiveEquivalentVariables(variable, res, visited); - - return res; -} - bool linkComponentVariableUnits(const ComponentPtr &component, DescriptionList &descriptionList) { bool status = true; diff --git a/src/utilities.h b/src/utilities.h index 7920f7a6d6..8b4e1f4a39 100644 --- a/src/utilities.h +++ b/src/utilities.h @@ -688,18 +688,6 @@ bool areComponentVariableUnitsUnlinked(const ComponentPtr &component); */ ConnectionMap createConnectionMap(const VariablePtr &variable1, const VariablePtr &variable2); -/** - * @brief Make a list of all variables equivalent to the given variable. - * - * Collect all the equivalent variables of the given @p variable and return - * them as a list of @ref VariablePtr. - * - * @param variable The variable to find equivalent variables of. - * - * @return A @c std::vector of @ref VariablePtr. - */ -std::vector equivalentVariables(const VariablePtr &variable); - /** * @brief The live equivalent variables of @p variable, in order, in one pass. * @@ -715,8 +703,8 @@ std::vector liveEquivalentVariables(const Variable &variable); /** * @brief The first variable of @p component in the equivalence set of @p variable. * - * The equivalence set is visited in the order of equivalentVariables(@p variable), stopping at the first variable - * owned by @p component (@p variable itself if it is owned by @p component). + * The equivalence set is visited from @p variable itself, then depth first in the order of each variable's equivalent + * variables, stopping at the first variable owned by @p component. * * @param variable The variable. * @param component The component. diff --git a/src/variable.cpp b/src/variable.cpp index c232932861..0c45c1ed37 100644 --- a/src/variable.cpp +++ b/src/variable.cpp @@ -491,10 +491,8 @@ std::string Variable::equivalenceConnectionId(const VariablePtr &variable1, cons } } if (candidate) { - auto vEquiv = firstEquivalentVariableInComponent(v, component2); - if (vEquiv != nullptr) { - candidates.emplace(v, vEquiv); - } + // Without an equivalent variable in component2 (nullptr), there's no identifier to find. + candidates.emplace(v, firstEquivalentVariableInComponent(v, component2)); } } diff --git a/src/xmlnode.cpp b/src/xmlnode.cpp index 75b72c16ff..624963277e 100644 --- a/src/xmlnode.cpp +++ b/src/xmlnode.cpp @@ -313,7 +313,7 @@ std::string XmlNode::convertToString() const // Fast path for a text node whose content xmlNodeDump() would output unchanged: printable ASCII, tabs and new // lines, with no characters that it escapes ('<', '>', '&' and carriage returns). This is the common case of the // content of a ci or cn element, and it avoids a buffer allocation and a serialisation per call. - if ((mPimpl->mXmlNodePtr->type == XML_TEXT_NODE) && (mPimpl->mXmlNodePtr->content != nullptr)) { + if (mPimpl->mXmlNodePtr->type == XML_TEXT_NODE) { const auto *content = reinterpret_cast(mPimpl->mXmlNodePtr->content); bool plain = true; for (const char *c = content; *c != '\0'; ++c) { diff --git a/tests/connection/connection.cpp b/tests/connection/connection.cpp index 4789fe4b7f..dd62b71301 100644 --- a/tests/connection/connection.cpp +++ b/tests/connection/connection.cpp @@ -1015,6 +1015,153 @@ TEST(Connection, nonUniqueWayOfGettingEquivalenceConnectionId) EXPECT_EQ("connection_id", libcellml::Variable::equivalenceConnectionId(v2, v4)); } +TEST(Connection, connectionIdWithinOneComponent) +{ + auto model = libcellml::Model::create("model"); + auto component = libcellml::Component::create("component"); + auto v1 = libcellml::Variable::create("variable1"); + auto v2 = libcellml::Variable::create("variable2"); + + component->addVariable(v1); + component->addVariable(v2); + model->addComponent(component); + libcellml::Variable::addEquivalence(v1, v2); + libcellml::Variable::setEquivalenceConnectionId(v1, v2, "connection_id"); + + EXPECT_EQ("connection_id", libcellml::Variable::equivalenceConnectionId(v1, v2)); + EXPECT_EQ("connection_id", libcellml::Variable::equivalenceConnectionId(v2, v1)); +} + +TEST(Connection, connectionIdWithOneComponentlessVariable) +{ + auto model = libcellml::Model::create("model"); + auto component = libcellml::Component::create("component"); + auto v1 = libcellml::Variable::create("variable1"); + auto v2 = libcellml::Variable::create("variable2"); + + component->addVariable(v1); + model->addComponent(component); + libcellml::Variable::addEquivalence(v1, v2); + libcellml::Variable::setEquivalenceConnectionId(v1, v2, "connection_id"); + + EXPECT_EQ("connection_id", libcellml::Variable::equivalenceConnectionId(v1, v2)); + EXPECT_EQ("connection_id", libcellml::Variable::equivalenceConnectionId(v2, v1)); +} + +TEST(Connection, connectionIdOfIndirectlyEquivalentVariables) +{ + auto model = libcellml::Model::create("model"); + auto c1 = libcellml::Component::create("component1"); + auto c2 = libcellml::Component::create("component2"); + auto c3 = libcellml::Component::create("component3"); + auto v1 = libcellml::Variable::create("variable1"); + auto v2 = libcellml::Variable::create("variable2"); + auto v3 = libcellml::Variable::create("variable3"); + + c1->addVariable(v1); + c2->addVariable(v2); + c3->addVariable(v3); + model->addComponent(c1); + model->addComponent(c2); + model->addComponent(c3); + libcellml::Variable::addEquivalence(v1, v2); + libcellml::Variable::addEquivalence(v2, v3); + + EXPECT_EQ("", libcellml::Variable::equivalenceConnectionId(v1, v3)); + + libcellml::Variable::setEquivalenceConnectionId(v1, v3, "connection_id"); + + EXPECT_EQ("connection_id", libcellml::Variable::equivalenceConnectionId(v1, v3)); + EXPECT_EQ("connection_id", libcellml::Variable::equivalenceConnectionId(v3, v1)); +} + +TEST(Connection, connectionIdAfterItIsRemoved) +{ + auto model = libcellml::Model::create("model"); + auto c1 = libcellml::Component::create("component1"); + auto c2 = libcellml::Component::create("component2"); + auto v1 = libcellml::Variable::create("variable1"); + auto v2 = libcellml::Variable::create("variable2"); + auto v3 = libcellml::Variable::create("variable3"); + auto v4 = libcellml::Variable::create("variable4"); + + c1->addVariable(v1); + c1->addVariable(v2); + c2->addVariable(v3); + c2->addVariable(v4); + model->addComponent(c1); + model->addComponent(c2); + libcellml::Variable::addEquivalence(v1, v3); + libcellml::Variable::addEquivalence(v2, v4); + libcellml::Variable::setEquivalenceConnectionId(v1, v3, "connection_id"); + + EXPECT_EQ("connection_id", libcellml::Variable::equivalenceConnectionId(v2, v4)); + + libcellml::Variable::removeEquivalenceConnectionId(v1, v3); + + EXPECT_EQ("", libcellml::Variable::equivalenceConnectionId(v2, v4)); + EXPECT_EQ("", libcellml::Variable::equivalenceConnectionId(v1, v3)); +} + +TEST(Connection, connectionIdWithExpiredVariable) +{ + auto model = libcellml::Model::create("model"); + auto c1 = libcellml::Component::create("component1"); + auto c2 = libcellml::Component::create("component2"); + auto v1 = libcellml::Variable::create("variable1"); + auto v2 = libcellml::Variable::create("variable2"); + auto v3 = libcellml::Variable::create("variable3"); + auto v4 = libcellml::Variable::create("variable4"); + + c1->addVariable(v1); + c1->addVariable(v2); + c2->addVariable(v3); + c2->addVariable(v4); + model->addComponent(c1); + model->addComponent(c2); + libcellml::Variable::addEquivalence(v1, v3); + libcellml::Variable::addEquivalence(v2, v4); + libcellml::Variable::setEquivalenceConnectionId(v1, v3, "connection_id"); + + // variable1 keeps the identifier it stored for variable3 after variable3 is gone. + c2->removeVariable(v3); + v3 = nullptr; + + EXPECT_EQ("connection_id", libcellml::Variable::equivalenceConnectionId(v2, v4)); +} + +TEST(Connection, connectionIdStoredForAVariableThatIsNoLongerEquivalent) +{ + auto model = libcellml::Model::create("model"); + auto c1 = libcellml::Component::create("component1"); + auto c2 = libcellml::Component::create("component2"); + auto c3 = libcellml::Component::create("component3"); + auto v1 = libcellml::Variable::create("variable1"); + auto v2 = libcellml::Variable::create("variable2"); + auto v3 = libcellml::Variable::create("variable3"); + auto v4 = libcellml::Variable::create("variable4"); + auto v5 = libcellml::Variable::create("variable5"); + + c1->addVariable(v1); + c1->addVariable(v4); + c2->addVariable(v2); + c3->addVariable(v3); + c3->addVariable(v5); + model->addComponent(c1); + model->addComponent(c2); + model->addComponent(c3); + libcellml::Variable::addEquivalence(v1, v2); + libcellml::Variable::addEquivalence(v2, v3); + libcellml::Variable::setEquivalenceConnectionId(v1, v3, "connection_id"); + + // variable1 keeps the identifier it stored for variable3, but is no longer equivalent to any variable of + // component3. + libcellml::Variable::removeEquivalence(v2, v3); + libcellml::Variable::addEquivalence(v4, v5); + + EXPECT_EQ("", libcellml::Variable::equivalenceConnectionId(v4, v5)); +} + TEST(Connection, connectionIdFromReverseVariablesToThoseSet) { libcellml::ModelPtr m = libcellml::Model::create(); diff --git a/tests/validator/validator.cpp b/tests/validator/validator.cpp index b3527f98db..1da22c1c4c 100644 --- a/tests/validator/validator.cpp +++ b/tests/validator/validator.cpp @@ -858,6 +858,43 @@ TEST(Validator, invalidSimpleMathmlCellMLUnits) EXPECT_EQ_ISSUES(expectedIssues, v); } +TEST(Validator, invalidMathMLVariablesWithEscapedOrNonAsciiCharacters) +{ + // Identifiers with a carriage return, a non-ASCII character, '<', '>' or '&' are reported as they are serialised + // (escaped where needed), not as their raw text. + const std::string in = + "\n" + "\n" + " \n" + " \n" + " \n" + " xa b\n" + " xc\xc3\xa9\n" + " xd<e\n" + " xf>g\n" + " xh&i\n" + " \n" + " \n" + "\n"; + const std::vector expectedIssues = { + "MathML ci element has the child text 'a b' which does not correspond with any variable names present in component 'component'.", + "MathML ci element has the child text 'c\xc3\xa9' which does not correspond with any variable names present in component 'component'.", + "MathML ci element has the child text 'd<e' which does not correspond with any variable names present in component 'component'.", + "MathML ci element has the child text 'f>g' which does not correspond with any variable names present in component 'component'.", + "MathML ci element has the child text 'h&i' which does not correspond with any variable names present in component 'component'.", + }; + + auto parser = libcellml::Parser::create(); + auto model = parser->parseModel(in); + auto validator = libcellml::Validator::create(); + + EXPECT_EQ(size_t(0), parser->issueCount()); + + validator->validateModel(model); + + EXPECT_EQ_ISSUES(expectedIssues, validator); +} + TEST(Validator, invalidMathmlCellMLNsOnNode) { const std::string math = From e1a94774c39cdfb5186af50b6a0ed08a78f7cea9 Mon Sep 17 00:00:00 2001 From: Finbar Argus Date: Wed, 30 Sep 2026 11:24:43 +1300 Subject: [PATCH 5/9] XmlNode::convertToStrippedString(): pass isspace() an unsigned char 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 --- src/xmlnode.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/xmlnode.cpp b/src/xmlnode.cpp index 624963277e..7f8eda89bc 100644 --- a/src/xmlnode.cpp +++ b/src/xmlnode.cpp @@ -337,9 +337,12 @@ std::string XmlNode::convertToString() const std::string XmlNode::convertToStrippedString() const { + // isspace() needs the value of an unsigned char: a char with the top bit set (e.g., a byte of a UTF-8 encoded + // non-ASCII character) is negative, which is undefined behaviour (and an assertion in MSVC's debug runtime). + auto isSpace = [](unsigned char c) { return isspace(c) != 0; }; std::string contentString = convertToString(); - contentString.erase(contentString.begin(), find_if_not(contentString.begin(), contentString.end(), [](int c) { return isspace(c); })); - contentString.erase(find_if_not(contentString.rbegin(), contentString.rend(), [](int c) { return isspace(c); }).base(), contentString.end()); + contentString.erase(contentString.begin(), find_if_not(contentString.begin(), contentString.end(), isSpace)); + contentString.erase(find_if_not(contentString.rbegin(), contentString.rend(), isSpace).base(), contentString.end()); return contentString; } From 6cfaedfa08bd09fb5e7a18bda93ae9aa96bfe8bc Mon Sep 17 00:00:00 2001 From: Finbar Argus Date: Wed, 30 Sep 2026 12:40:53 +1300 Subject: [PATCH 6/9] Keep the equivalence traversal helper out of the public API header 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 --- src/api/libcellml/variable.h | 5 ----- src/printer.cpp | 3 ++- src/utilities.cpp | 3 ++- src/utilities.h | 12 ------------ src/variable.cpp | 30 +++++++----------------------- src/variable_p.h | 26 ++++++++++++++++++++++++++ 6 files changed, 37 insertions(+), 42 deletions(-) diff --git a/src/api/libcellml/variable.h b/src/api/libcellml/variable.h index 1191e917e7..5bfa4630c9 100644 --- a/src/api/libcellml/variable.h +++ b/src/api/libcellml/variable.h @@ -17,7 +17,6 @@ limitations under the License. #pragma once #include -#include #include "libcellml/exportdefinitions.h" #include "libcellml/namedentity.h" @@ -479,10 +478,6 @@ class LIBCELLML_EXPORT Variable: public NamedEntity VariableImpl *pFunc(); /**< Getter for private implementation pointer, @private. */ const VariableImpl *pFunc() const; /**< Const getter for private implementation pointer, @private. */ - -#ifndef SWIG - friend std::vector liveEquivalentVariables(const Variable &variable); /**< Internal traversal helper, @private. */ -#endif }; } // namespace libcellml diff --git a/src/printer.cpp b/src/printer.cpp index 6a3fa78db3..1868652430 100644 --- a/src/printer.cpp +++ b/src/printer.cpp @@ -159,7 +159,8 @@ void buildMapsForComponentsVariables(const ComponentPtr &component, ComponentMap { for (size_t i = 0; i < component->variableCount(); ++i) { VariablePtr variable = component->variable(i); - for (const auto &equivalentVariable : liveEquivalentVariables(*variable)) { + for (size_t j = 0, n = variable->equivalentVariableCount(); j < n; ++j) { + VariablePtr equivalentVariable = variable->equivalentVariable(j); VariablePairPtr variablePair = VariablePair::create(variable, equivalentVariable); // Skip the pair if its reverse is already in the VariableMap (a set lookup, rather than a linear search of // the map, which is quadratic in the number of equivalences). diff --git a/src/utilities.cpp b/src/utilities.cpp index 079faeb308..8cb95b4b26 100644 --- a/src/utilities.cpp +++ b/src/utilities.cpp @@ -1026,7 +1026,8 @@ std::string makeUniqueId(IdList &idList) VariablePtr firstEquivalentVariableInComponent(const VariablePtr &variable, const ComponentPtr &component, std::unordered_set &visited) { - for (const auto &equivalentVariable : liveEquivalentVariables(*variable)) { + for (size_t i = 0, n = variable->equivalentVariableCount(); i < n; ++i) { + auto equivalentVariable = variable->equivalentVariable(i); if (visited.insert(equivalentVariable.get()).second) { if (owningComponent(equivalentVariable) == component) { return equivalentVariable; diff --git a/src/utilities.h b/src/utilities.h index 8b4e1f4a39..514535d4e6 100644 --- a/src/utilities.h +++ b/src/utilities.h @@ -688,18 +688,6 @@ bool areComponentVariableUnitsUnlinked(const ComponentPtr &component); */ ConnectionMap createConnectionMap(const VariablePtr &variable1, const VariablePtr &variable2); -/** - * @brief The live equivalent variables of @p variable, in order, in one pass. - * - * Same as calling equivalentVariable(i) for i from 0 to equivalentVariableCount() - 1, but O(n) rather than O(n^2) - * in the number of equivalences. - * - * @param variable The variable. - * - * @return The equivalent variables. - */ -std::vector liveEquivalentVariables(const Variable &variable); - /** * @brief The first variable of @p component in the equivalence set of @p variable. * diff --git a/src/variable.cpp b/src/variable.cpp index 0c45c1ed37..cfd39fa85b 100644 --- a/src/variable.cpp +++ b/src/variable.cpp @@ -180,15 +180,11 @@ size_t Variable::equivalentVariableCount() const return count; } -std::vector liveEquivalentVariables(const Variable &variable) +std::vector Variable::VariableImpl::liveEquivalentVariables() const { - // The live equivalent variables in one pass, in the order of equivalentVariable(0), equivalentVariable(1), ... - // Iterating with equivalentVariableCount() and equivalentVariable(i) is O(n^2) in the number of equivalences, since - // both walk the list, which matters for variables equivalent to many others (e.g., a time variable or a global - // constant shared by every component of a large model). std::vector res; - res.reserve(variable.pFunc()->mEquivalentVariables.size()); - for (const auto &variableWeak : variable.pFunc()->mEquivalentVariables) { + res.reserve(mEquivalentVariables.size()); + for (const auto &variableWeak : mEquivalentVariables) { auto equivalentVariable = variableWeak.lock(); if (equivalentVariable != nullptr) { res.push_back(equivalentVariable); @@ -229,21 +225,9 @@ bool Variable::VariableImpl::hasEquivalentVariable(const VariablePtr &equivalent return equivalent; } -/** - * @brief Test if the two variables given are equivalent, directly or indirectly. - * - * Traverse the variable equivalence network to determine if the two given variables - * are equivalent. Returns true if they are equivalent and false otherwise. - * - * @param variable1 The first variable to test. - * @param variable2 The second variable to test. - * @param testedVariables Set of previously tested variables. - * - * @return True if the two given variables are equivalent, false otherwise. - */ -bool haveEquivalentVariables(const Variable *variable1, - const Variable *variable2, - std::unordered_set &testedVariables) +bool Variable::VariableImpl::haveEquivalentVariables(const Variable *variable1, + const Variable *variable2, + std::unordered_set &testedVariables) { if (variable1 == variable2) { return true; @@ -255,7 +239,7 @@ bool haveEquivalentVariables(const Variable *variable1, testedVariables.insert(variable2); - for (const auto &equivalentVariable2Ptr : liveEquivalentVariables(*variable2)) { + for (const auto &equivalentVariable2Ptr : variable2->pFunc()->liveEquivalentVariables()) { Variable *equivalentVariable2 = equivalentVariable2Ptr.get(); if ((testedVariables.count(equivalentVariable2) == 0) diff --git a/src/variable_p.h b/src/variable_p.h index 23507aa4e0..5f5102a070 100644 --- a/src/variable_p.h +++ b/src/variable_p.h @@ -16,6 +16,7 @@ limitations under the License. #pragma once +#include #include #include "libcellml/variable.h" @@ -115,6 +116,31 @@ class Variable::VariableImpl: public NamedEntityImpl */ bool hasIndirectEquivalentVariable(const VariablePtr &equivalentVariable) const; + /** + * @brief The live equivalent variables of this variable, in order, in one pass. + * + * Same as calling equivalentVariable(i) for i from 0 to equivalentVariableCount() - 1, but O(n) rather than + * O(n^2) in the number of equivalences, since both of those walk the whole list. + * + * @return The equivalent variables. + */ + std::vector liveEquivalentVariables() const; + + /** + * @brief Test if the two variables given are equivalent, directly or indirectly. + * + * Traverse the variable equivalence network to determine if the two given variables + * are equivalent. + * + * @param variable1 The first variable to test. + * @param variable2 The second variable to test. + * @param testedVariables Set of previously tested variables. + * + * @return True if the two given variables are equivalent, false otherwise. + */ + static bool haveEquivalentVariables(const Variable *variable1, const Variable *variable2, + std::unordered_set &testedVariables); + /** * @brief Set the equivalent mapping identifier for this equivalence. * From efa22ebe17bf308a88bb4c59e52a209733c121da Mon Sep 17 00:00:00 2001 From: Finbar Argus Date: Wed, 30 Sep 2026 15:04:55 +1300 Subject: [PATCH 7/9] Comments describe the current code; restore haveEquivalentVariables() 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 --- src/analyser.cpp | 4 +--- src/printer.cpp | 10 +++------- src/variable.cpp | 21 ++++++++++++++++----- src/variable_p.h | 15 +++------------ 4 files changed, 23 insertions(+), 27 deletions(-) diff --git a/src/analyser.cpp b/src/analyser.cpp index dc23a2b5bf..baa2efb82b 100644 --- a/src/analyser.cpp +++ b/src/analyser.cpp @@ -412,9 +412,7 @@ AnalyserInternalVariablePtr Analyser::AnalyserImpl::internalVariable(const Varia // Two variables are equivalent if and only if they are in the same group of // the analyser model's equivalent variables cache, which has every variable - // of the model, so look the internal variable up by group, rather than - // testing every internal variable (which is quadratic in the number of - // variables). + // of the model, so an existing internal variable is found by its group. auto group = mAnalyserModel->mPimpl->mEquivalentVariableCache.at(rawPtr); auto internalVariableIt = mInternalVariableGroupMap.find(group); diff --git a/src/printer.cpp b/src/printer.cpp index 1868652430..22f6344d01 100644 --- a/src/printer.cpp +++ b/src/printer.cpp @@ -73,9 +73,7 @@ std::string printMapVariables(const VariablePairPtr &variablePair, IdList &idLis std::string printConnections(const ComponentMap &componentMap, const VariableMap &variableMap, IdList &idList, bool autoIds) { - // Group the variable equivalence pairs by their pair of parent components, in order of first appearance, in a - // single pass (rather than rescanning the remaining pairs for each new component pair, which is quadratic in the - // number of pairs). + // Group the variable equivalence pairs by their pair of parent components, in order of first appearance. std::vector> groups; std::map, size_t> groupIndex; for (size_t index = 0; index < componentMap.size(); ++index) { @@ -97,8 +95,7 @@ std::string printConnections(const ComponentMap &componentMap, const VariableMap for (size_t index : group) { mappingVariables += printMapVariables(variableMap.at(index), idList, autoIds); } - // The connection takes its identifier from the last variable pair of the group (as it always has). Only that - // pair's identifier is used, so it is the only one that needs to be looked up. + // The connection takes its identifier from the last variable pair of the group. const VariablePairPtr &lastVariablePair = variableMap.at(group.back()); std::string connectionId = Variable::equivalenceConnectionId(lastVariablePair->variable1(), lastVariablePair->variable2()); // Serialise out the new connection. @@ -162,8 +159,7 @@ void buildMapsForComponentsVariables(const ComponentPtr &component, ComponentMap for (size_t j = 0, n = variable->equivalentVariableCount(); j < n; ++j) { VariablePtr equivalentVariable = variable->equivalentVariable(j); VariablePairPtr variablePair = VariablePair::create(variable, equivalentVariable); - // Skip the pair if its reverse is already in the VariableMap (a set lookup, rather than a linear search of - // the map, which is quadratic in the number of equivalences). + // Skip the pair if its reverse is already in the VariableMap. bool pairFound = addedPairs.count(std::make_pair(equivalentVariable.get(), variable.get())) != 0; if (!pairFound) { addedPairs.emplace(variable.get(), equivalentVariable.get()); diff --git a/src/variable.cpp b/src/variable.cpp index cfd39fa85b..17a2e45073 100644 --- a/src/variable.cpp +++ b/src/variable.cpp @@ -225,6 +225,18 @@ bool Variable::VariableImpl::hasEquivalentVariable(const VariablePtr &equivalent return equivalent; } +/** + * @brief Test if the two variables given are equivalent, directly or indirectly. + * + * Traverse the variable equivalence network to determine if the two given variables + * are equivalent. Returns true if they are equivalent and false otherwise. + * + * @param variable1 The first variable to test. + * @param variable2 The second variable to test. + * @param testedVariables Set of previously tested variables. + * + * @return True if the two given variables are equivalent, false otherwise. + */ bool Variable::VariableImpl::haveEquivalentVariables(const Variable *variable1, const Variable *variable2, std::unordered_set &testedVariables) @@ -453,11 +465,10 @@ std::string Variable::equivalenceConnectionId(const VariablePtr &variable1, cons if ((variable1 != nullptr) && (variable2 != nullptr)) { if (deepSearch) { if (variable1->hasEquivalentVariable(variable2, false) || variable1->hasEquivalentVariable(variable2, true)) { - // Same result as looking the identifier up for every pair of createConnectionMap(variable1, variable2), - // in the map's order, but a variable of the first component 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 - // for their equivalent variable in the second component. Models rarely store connection identifiers, - // and searching every variable's equivalence set is quadratic in the size of large models. + // Only a variable of the first component that has stored a non-empty identifier for a variable of the + // second component can give an identifier, so only those variables are searched for their first + // equivalent variable in the second component. The identifier is the first one found, in the order + // of the candidate variables. ComponentPtr component1 = owningComponent(variable1); ComponentPtr component2 = owningComponent(variable2); if ((component1 != nullptr) && (component2 != nullptr)) { diff --git a/src/variable_p.h b/src/variable_p.h index 5f5102a070..238678b46f 100644 --- a/src/variable_p.h +++ b/src/variable_p.h @@ -117,10 +117,10 @@ class Variable::VariableImpl: public NamedEntityImpl bool hasIndirectEquivalentVariable(const VariablePtr &equivalentVariable) const; /** - * @brief The live equivalent variables of this variable, in order, in one pass. + * @brief The live equivalent variables of this variable, in order. * - * Same as calling equivalentVariable(i) for i from 0 to equivalentVariableCount() - 1, but O(n) rather than - * O(n^2) in the number of equivalences, since both of those walk the whole list. + * The equivalent variables that equivalentVariable(i) gives for i from 0 to equivalentVariableCount() - 1, + * collected in one pass over the list. * * @return The equivalent variables. */ @@ -128,15 +128,6 @@ class Variable::VariableImpl: public NamedEntityImpl /** * @brief Test if the two variables given are equivalent, directly or indirectly. - * - * Traverse the variable equivalence network to determine if the two given variables - * are equivalent. - * - * @param variable1 The first variable to test. - * @param variable2 The second variable to test. - * @param testedVariables Set of previously tested variables. - * - * @return True if the two given variables are equivalent, false otherwise. */ static bool haveEquivalentVariables(const Variable *variable1, const Variable *variable2, std::unordered_set &testedVariables); From 5baad160492e19d9b759e4e86a6e02020d796aae Mon Sep 17 00:00:00 2001 From: Hugh Sorby Date: Wed, 30 Sep 2026 22:26:43 +1300 Subject: [PATCH 8/9] Move the doxygen comment to the declaration of the haveEquivalentVariables. --- src/variable.cpp | 12 ------------ src/variable_p.h | 6 ++++++ 2 files changed, 6 insertions(+), 12 deletions(-) diff --git a/src/variable.cpp b/src/variable.cpp index 17a2e45073..06aa97ba88 100644 --- a/src/variable.cpp +++ b/src/variable.cpp @@ -225,18 +225,6 @@ bool Variable::VariableImpl::hasEquivalentVariable(const VariablePtr &equivalent return equivalent; } -/** - * @brief Test if the two variables given are equivalent, directly or indirectly. - * - * Traverse the variable equivalence network to determine if the two given variables - * are equivalent. Returns true if they are equivalent and false otherwise. - * - * @param variable1 The first variable to test. - * @param variable2 The second variable to test. - * @param testedVariables Set of previously tested variables. - * - * @return True if the two given variables are equivalent, false otherwise. - */ bool Variable::VariableImpl::haveEquivalentVariables(const Variable *variable1, const Variable *variable2, std::unordered_set &testedVariables) diff --git a/src/variable_p.h b/src/variable_p.h index 238678b46f..f9bbf9a353 100644 --- a/src/variable_p.h +++ b/src/variable_p.h @@ -128,6 +128,12 @@ class Variable::VariableImpl: public NamedEntityImpl /** * @brief Test if the two variables given are equivalent, directly or indirectly. + * * Traverse the variable equivalence network to determine if the two given variables + * are equivalent. Returns true if they are equivalent and false otherwise. + * * @param variable1 The first variable to test. + * @param variable2 The second variable to test. + * @param testedVariables Set of previously tested variables. + * * @return True if the two given variables are equivalent, false otherwise. */ static bool haveEquivalentVariables(const Variable *variable1, const Variable *variable2, std::unordered_set &testedVariables); From 5a167b98040d7b54e6cb301c6ba6f997921fef1c Mon Sep 17 00:00:00 2001 From: Finbar Argus Date: Thu, 1 Oct 2026 14:37:02 +1300 Subject: [PATCH 9/9] Variable::equivalentVariable(i) and equivalentVariableCount() in constant 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 --- src/variable.cpp | 17 +++++++++++++++++ src/variable_p.h | 10 +++++++--- tests/connection/connection.cpp | 29 +++++++++++++++++++++++++++++ 3 files changed, 53 insertions(+), 3 deletions(-) diff --git a/src/variable.cpp b/src/variable.cpp index 06aa97ba88..b92f146a61 100644 --- a/src/variable.cpp +++ b/src/variable.cpp @@ -67,6 +67,14 @@ Variable::Variable(const std::string &name) Variable::~Variable() { + // An equivalence is held by both of its variables, so this tells every variable left holding an expired + // reference to this one. + for (const auto &variableWeak : pFunc()->mEquivalentVariables) { + auto equivalentVariable = variableWeak.lock(); + if (equivalentVariable != nullptr) { + equivalentVariable->pFunc()->mMayHaveExpiredEquivalentVariables = true; + } + } delete pFunc(); } @@ -154,6 +162,10 @@ void Variable::removeAllEquivalences() VariablePtr Variable::equivalentVariable(size_t index) const { + if (!pFunc()->mMayHaveExpiredEquivalentVariables) { + return (index < pFunc()->mEquivalentVariables.size()) ? pFunc()->mEquivalentVariables[index].lock() : nullptr; + } + size_t count = 0; for (const auto &variableWeak : pFunc()->mEquivalentVariables) { auto variable = variableWeak.lock(); @@ -170,6 +182,10 @@ VariablePtr Variable::equivalentVariable(size_t index) const size_t Variable::equivalentVariableCount() const { + if (!pFunc()->mMayHaveExpiredEquivalentVariables) { + return pFunc()->mEquivalentVariables.size(); + } + size_t count = 0; for (const auto &variableWeak : pFunc()->mEquivalentVariables) { auto variable = variableWeak.lock(); @@ -201,6 +217,7 @@ bool Variable::hasEquivalentVariable(const VariablePtr &equivalentVariable, bool void Variable::VariableImpl::cleanExpiredVariables() { mEquivalentVariables.erase(std::remove_if(mEquivalentVariables.begin(), mEquivalentVariables.end(), [=](const VariableWeakPtr &variableWeak) -> bool { return variableWeak.expired(); }), mEquivalentVariables.end()); + mMayHaveExpiredEquivalentVariables = false; } void Variable::VariableImpl::unsafeResetEquivalenceIds(const VariablePtr &equivalentVariable) diff --git a/src/variable_p.h b/src/variable_p.h index f9bbf9a353..b138b1a6d8 100644 --- a/src/variable_p.h +++ b/src/variable_p.h @@ -37,6 +37,7 @@ class Variable::VariableImpl: public NamedEntityImpl public: Variable *mVariable = nullptr; std::vector mEquivalentVariables; /**< Equivalent variables for this Variable. */ + bool mMayHaveExpiredEquivalentVariables = false; /**< Whether an equivalent variable may have been deleted since the list was last cleaned. */ std::map> mMappingIdMap; /**< Mapping identifier map for equivalent variable. */ std::map> mConnectionIdMap; /**< Connection identifier map for equivalent variable. */ std::string mInitialValue; /**< Initial value for this Variable. */ @@ -128,12 +129,15 @@ class Variable::VariableImpl: public NamedEntityImpl /** * @brief Test if the two variables given are equivalent, directly or indirectly. - * * Traverse the variable equivalence network to determine if the two given variables + * + * Traverse the variable equivalence network to determine if the two given variables * are equivalent. Returns true if they are equivalent and false otherwise. - * * @param variable1 The first variable to test. + * + * @param variable1 The first variable to test. * @param variable2 The second variable to test. * @param testedVariables Set of previously tested variables. - * * @return True if the two given variables are equivalent, false otherwise. + * + * @return True if the two given variables are equivalent, false otherwise. */ static bool haveEquivalentVariables(const Variable *variable1, const Variable *variable2, std::unordered_set &testedVariables); diff --git a/tests/connection/connection.cpp b/tests/connection/connection.cpp index dd62b71301..adf80871d9 100644 --- a/tests/connection/connection.cpp +++ b/tests/connection/connection.cpp @@ -1682,3 +1682,32 @@ TEST(Connection, addEquivalenceConnectionIdClearedAfterDisconnect) libcellml::Variable::addEquivalence(v1, v2); EXPECT_EQ("", libcellml::Variable::equivalenceConnectionId(v1, v2)); } + +TEST(Connection, equivalentVariablesBeforeAndAfterDeletingAnEquivalentVariable) +{ + auto v1 = libcellml::Variable::create("v1"); + auto v2 = libcellml::Variable::create("v2"); + auto v3 = libcellml::Variable::create("v3"); + + libcellml::Variable::addEquivalence(v1, v2); + libcellml::Variable::addEquivalence(v1, v3); + + EXPECT_EQ(size_t(2), v1->equivalentVariableCount()); + EXPECT_EQ(v2, v1->equivalentVariable(0)); + EXPECT_EQ(v3, v1->equivalentVariable(1)); + EXPECT_EQ(nullptr, v1->equivalentVariable(2)); + + v2.reset(); + + EXPECT_EQ(size_t(1), v1->equivalentVariableCount()); + EXPECT_EQ(v3, v1->equivalentVariable(0)); + EXPECT_EQ(nullptr, v1->equivalentVariable(1)); + + auto v4 = libcellml::Variable::create("v4"); + libcellml::Variable::addEquivalence(v1, v4); + + EXPECT_EQ(size_t(2), v1->equivalentVariableCount()); + EXPECT_EQ(v3, v1->equivalentVariable(0)); + EXPECT_EQ(v4, v1->equivalentVariable(1)); + EXPECT_EQ(nullptr, v1->equivalentVariable(2)); +}