diff --git a/src/analyser.cpp b/src/analyser.cpp index 1c3594e124..baa2efb82b 100644 --- a/src/analyser.cpp +++ b/src/analyser.cpp @@ -410,12 +410,17 @@ 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, which has every variable + // of the model, so an existing internal variable is found by its group. - return internalVariable; - } + auto group = mAnalyserModel->mPimpl->mEquivalentVariableCache.at(rawPtr); + auto internalVariableIt = mInternalVariableGroupMap.find(group); + + if (internalVariableIt != mInternalVariableGroupMap.end()) { + mInternalVariableMap[rawPtr] = internalVariableIt->second; + + return internalVariableIt->second; } // No internal variable exists for the given variable, so create one, track @@ -426,6 +431,7 @@ AnalyserInternalVariablePtr Analyser::AnalyserImpl::internalVariable(const Varia mInternalVariables.push_back(res); mInternalVariableMap[rawPtr] = res; + mInternalVariableGroupMap[group] = res; return res; } @@ -2323,6 +2329,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/printer.cpp b/src/printer.cpp index 6a39d3a5f5..22f6344d01 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,31 @@ 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. + 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. + 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 +109,6 @@ std::string printConnections(const ComponentMap &componentMap, const VariableMap connections += " id=\"" + makeUniqueId(idList) + "\""; } connections += ">" + mappingVariables + ""; - serialisedComponentMap.push_back(currentComponentPair); - ++componentMapIndex1; } return connections; @@ -160,18 +149,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) { + for (size_t j = 0, n = variable->equivalentVariableCount(); j < n; ++j) { VariablePtr equivalentVariable = variable->equivalentVariable(j); 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. + 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 +176,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..8cb95b4b26 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,41 @@ 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 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) +{ + 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; + } + auto found = firstEquivalentVariableInComponent(equivalentVariable, component, visited); + if (found != nullptr) { + return found; + } + } + } + + 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; @@ -1024,10 +1060,10 @@ 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 (v itself, then depth first). + VariablePtr vEquiv = firstEquivalentVariableInComponent(v, component2); + if (vEquiv != nullptr) { + map.insert(std::make_pair(v, vEquiv)); } } } @@ -1035,28 +1071,6 @@ ConnectionMap createConnectionMap(const VariablePtr &variable1, const VariablePt return map; } -void recursiveEquivalentVariables(const VariablePtr &variable, std::vector &equivalentVariables) -{ - for (size_t i = 0; i < variable->equivalentVariableCount(); ++i) { - VariablePtr equivalentVariable = variable->equivalentVariable(i); - - if (std::find(equivalentVariables.begin(), equivalentVariables.end(), equivalentVariable) == equivalentVariables.end()) { - equivalentVariables.push_back(equivalentVariable); - - recursiveEquivalentVariables(equivalentVariable, equivalentVariables); - } - } -} - -std::vector equivalentVariables(const VariablePtr &variable) -{ - std::vector res = {variable}; - - recursiveEquivalentVariables(variable, res); - - return res; -} - bool linkComponentVariableUnits(const ComponentPtr &component, DescriptionList &descriptionList) { bool status = true; diff --git a/src/utilities.h b/src/utilities.h index 888447f1f2..514535d4e6 100644 --- a/src/utilities.h +++ b/src/utilities.h @@ -689,16 +689,17 @@ 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. + * @brief The first variable of @p component in the equivalence set of @p variable. * - * Collect all the equivalent variables of the given @p variable and return - * them as a list of @ref VariablePtr. + * 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 to find equivalent variables of. + * @param variable The variable. + * @param component The component. * - * @return A @c std::vector of @ref VariablePtr. + * @return The first equivalent variable owned by @p component, or @c nullptr if there is none. */ -std::vector equivalentVariables(const VariablePtr &variable); +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 06983ee978..b92f146a61 100644 --- a/src/variable.cpp +++ b/src/variable.cpp @@ -19,10 +19,12 @@ limitations under the License. #include #include #include +#include #include #include "libcellml/units.h" +#include "commonutils.h" #include "utilities.h" #include "variable_p.h" @@ -65,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(); } @@ -152,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(); @@ -168,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(); @@ -178,6 +196,19 @@ size_t Variable::equivalentVariableCount() const return count; } +std::vector Variable::VariableImpl::liveEquivalentVariables() const +{ + std::vector res; + res.reserve(mEquivalentVariables.size()); + for (const auto &variableWeak : 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); @@ -186,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) @@ -210,21 +242,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 Vector 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) +bool Variable::VariableImpl::haveEquivalentVariables(const Variable *variable1, + const Variable *variable2, + std::unordered_set &testedVariables) { if (variable1 == variable2) { return true; @@ -234,12 +254,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 : variable2->pFunc()->liveEquivalentVariables()) { + 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 +274,7 @@ bool Variable::VariableImpl::hasIndirectEquivalentVariable(const VariablePtr &eq return false; } - std::vector testedVariables; + std::unordered_set testedVariables; return haveEquivalentVariables(mVariable, equivalentVariable.get(), testedVariables); } @@ -449,14 +469,39 @@ 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)) { + // 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)) { + 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) { + // Without an equivalent variable in component2 (nullptr), there's no identifier to find. + candidates.emplace(v, firstEquivalentVariableInComponent(v, component2)); + } + } - 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; + } } } diff --git a/src/variable_p.h b/src/variable_p.h index 23507aa4e0..b138b1a6d8 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" @@ -36,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. */ @@ -115,6 +117,31 @@ class Variable::VariableImpl: public NamedEntityImpl */ bool hasIndirectEquivalentVariable(const VariablePtr &equivalentVariable) const; + /** + * @brief The live equivalent variables of this variable, in order. + * + * 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. + */ + 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. 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); + /** * @brief Set the equivalent mapping identifier for this equivalence. * diff --git a/src/xmlnode.cpp b/src/xmlnode.cpp index 93a273ac02..7f8eda89bc 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) { + 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); @@ -320,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; } diff --git a/tests/connection/connection.cpp b/tests/connection/connection.cpp index 4789fe4b7f..adf80871d9 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(); @@ -1535,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)); +} 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 =