From 04f15db13ab1a1c0a94a6ad25909c9f6bd84c22c Mon Sep 17 00:00:00 2001 From: Jan Kleinert Date: Mon, 5 Oct 2026 15:41:12 +0200 Subject: [PATCH] Add swap_node and swap_param to replace a parameter (#22) --- Changelog.md | 1 + docs/usage.rst | 21 ++++++ parametric/core.hpp | 28 ++++++++ parametric/dag.hpp | 75 +++++++++++++++++++++ tests/dag.cpp | 127 ++++++++++++++++++++++++++++++++++++ tests/eval.cpp | 155 +++++++++++++++++++++++++++++++++++++++++++- 6 files changed, 406 insertions(+), 1 deletion(-) diff --git a/Changelog.md b/Changelog.md index 246a459..86a64fc 100644 --- a/Changelog.md +++ b/Changelog.md @@ -6,6 +6,7 @@ SPDX-License-Identifier: Apache-2.0 # Unreleased +- Add `swap_param` and `swap_node` to replace a parameter in a DAG (#22) - Fix undefined behaviour in `DAGNode::~DAGNode()`, which erased from the parent list while iterating over it (#86) - Fix dead child entries accumulating in long-lived nodes, which made attaching N consumers cost O(N^2) (#85) diff --git a/docs/usage.rst b/docs/usage.rst index 2138d17..286608e 100644 --- a/docs/usage.rst +++ b/docs/usage.rst @@ -91,6 +91,27 @@ In this example, only ``base`` goes in as a parameter whereas the exponent is co and captured by the lambda. +Replacing a parameter +--------------------- + +An input of an existing computation can be exchanged with ``parametric::swap_param``. All results +that depend on the old parameter then depend on the new one, at the same argument position: + +.. code-block:: cpp + + auto a = parametric::new_param(1.0); + auto b = parametric::new_param(2.0); + auto c = parametric::new_param(10.0); + + auto sum = parametric::eval(add, a, b); // 3.0 + parametric::swap_param(a, c); + sum.value(); // 12.0 + +Both parameters must have the same type. The old parameter stays valid, but does not have any dependents anymore. +If the new parameter depends on the old one, the replacement would create a cycle. In this case a ``std::runtime_error`` +is thrown and nothing is changed. On the level of generic DAG nodes, ``parametric::swap_node`` provides the same functionality. + + The object oriented approach ---------------------------- diff --git a/parametric/core.hpp b/parametric/core.hpp index f48dce8..b3a70d1 100644 --- a/parametric/core.hpp +++ b/parametric/core.hpp @@ -233,6 +233,34 @@ void add_parent(const std::shared_ptr>&, cons static_assert(AlwaysFalse::value, "Connecting two parametric values is not allowed"); } +/** + * @brief Replaces the parameter old_p by new_p in all computations that depend on old_p + * + * Every compute node that used old_p as an input uses new_p instead, at the same argument position. + * Results that depend on old_p are invalidated and recomputed from new_p on next access. The parameter + * old_p stays valid, but does not have any dependents afterwards. The parents of new_p are not modified. + * + * Both parameters must have the same value and serializer type. If the replacement would introduce a + * cycle, e.g. because new_p depends on old_p, a std::runtime_error is thrown and nothing is changed. + * + * \code{cpp} + * auto a = parametric::new_param(1.0); + * auto b = parametric::new_param(2.0); + * auto c = parametric::new_param(10.0); + * auto sum = parametric::eval(add, a, b); // 3.0 + * parametric::swap_param(a, c); + * sum.value(); // 12.0 + * \endcode + * + * @param old_p The parameter to be replaced + * @param new_p The parameter taking its place + */ +template +void swap_param(param const& old_p, param const& new_p) +{ + swap_node(old_p.node_pointer(), new_p.node_pointer()); +} + /// @private /// A type representing the input arguments of a compute node template diff --git a/parametric/dag.hpp b/parametric/dag.hpp index 77d376c..927e7fc 100644 --- a/parametric/dag.hpp +++ b/parametric/dag.hpp @@ -41,6 +41,23 @@ typedef std::shared_ptr NodeRef; */ void add_parent(const NodeRef& child, const NodeRef& parent); +/** + * @brief Replaces old_node by new_node as a parent of all children of old_node + * + * After the call, every child that depended on old_node depends on new_node instead, at the same + * position in its parent list. This also holds if old_node appears multiple times in the parent list + * of a child. The moved children and all their descendants are invalidated. old_node itself stays valid + * and keeps its own parents, but has no children afterwards. The parents of new_node are not modified. + * + * The function has the strong exception guarantee: if it throws, the graph is unchanged. + * + * @param old_node The node to be replaced. + * @param new_node The node that takes over the children of old_node. + * @throws std::invalid_argument if one of the nodes is null or has positional children (e.g. compute nodes). + * @throws std::runtime_error if the replacement would introduce a cycle. + */ +void swap_node(const NodeRef& old_node, const NodeRef& new_node); + /** * @brief This class provides a basis node of a directed acyclic graph (DAG) * @@ -117,6 +134,51 @@ class DAGNode child->parents.push_back(parent); } + friend void swap_node(const NodeRef& old_node, const NodeRef& new_node) + { + if (!old_node || !new_node) { + throw std::invalid_argument("Cannot swap node: null pointer passed."); + } + + if (old_node->has_positional_children() || new_node->has_positional_children()) { + throw std::invalid_argument("Cannot swap node: nodes with positional children (e.g. compute nodes) are not supported."); + } + + if (old_node == new_node) { + return; + } + + // Take a snapshot of the live children, because the child list of old_node is modified below. + std::vector moved; + for (auto const& c : old_node->childs) { + if (NodeRef cp = c.lock()) { + moved.push_back(std::move(cp)); + } + } + + // Validate everything before modifying anything. + for (auto const& c : moved) { + if (c == new_node || c->precedes(*new_node)) { + throw std::runtime_error("Cannot swap node: cycles are not allowed."); + } + } + + for (auto const& c : moved) { + c->replace_parent(*old_node, new_node); + + auto predicate = [&c](auto const& x) { return x.lock() == c; }; + if (std::find_if(new_node->childs.begin(), new_node->childs.end(), predicate) == new_node->childs.end()) { + new_node->childs.push_back(c); + } + } + old_node->childs.clear(); + + for (auto const& c : moved) { + c->invalidateSelf(); + c->invalidate(); + } + } + /** * @brief Returns the identifier of the node * @return The id as a string @@ -365,6 +427,19 @@ class DAGNode std::string _id; /**< @private */ protected: + /** + * @brief Replaces all occurrences of parent_old in the parent list by parent_new, keeping their + * positions. The child lists of the parents are not modified. + */ + void replace_parent(const DAGNode& parent_old, const NodeRef& parent_new) + { + for (auto& p : parents) { + if (p.get() == &parent_old) { + p = parent_new; + } + } + } + mutable std::vector> childs; /**< @brief Pointer to child nodes */ std::vector> parents; /**< @brief Pointer to parent nodes */ diff --git a/tests/dag.cpp b/tests/dag.cpp index e29759e..2946f6a 100644 --- a/tests/dag.cpp +++ b/tests/dag.cpp @@ -124,3 +124,130 @@ TEST(DAG, deadChildrenArePruned) EXPECT_EQ(1, x->num_children()); EXPECT_TRUE(x->precedes(*alive)); } + +// Replacing a parent. See https://github.com/grunk-dev/parametric/issues/22 +TEST(DAG, swapNode) +{ + NodeRef a(new DAGNode("a")); + NodeRef a2(new DAGNode("a2")); + NodeRef p(new DAGNode("p")); + NodeRef b(new DAGNode("b")); + NodeRef c(new DAGNode("c")); + NodeRef d(new DAGNode("d")); + + add_parent(a, p); + add_parent(b, a); + add_parent(c, d); + add_parent(c, a); // a is not the first parent of c + add_parent(a2, d); + + swap_node(a, a2); + + // old node keeps its parents, but has no children anymore + EXPECT_EQ(1, a->num_parents()); + EXPECT_EQ(0, a->num_children()); + EXPECT_TRUE(p->precedes(*a)); + + // new node keeps its parents and received the children + EXPECT_EQ(1, a2->num_parents()); + EXPECT_EQ(2, a2->num_children()); + EXPECT_TRUE(a2->precedes(*b)); + EXPECT_TRUE(a2->precedes(*c)); + EXPECT_FALSE(a->precedes(*b)); + EXPECT_FALSE(a->precedes(*c)); + EXPECT_FALSE(p->precedes(*b)); + + // the position in the parent list is kept + ASSERT_EQ(2, c->num_parents()); + EXPECT_EQ(d, c->get_parents()[0]); + EXPECT_EQ(a2, c->get_parents()[1]); +} + +TEST(DAG, swapNodeDuplicateParents) +{ + NodeRef a(new DAGNode("a")); + NodeRef a2(new DAGNode("a2")); + NodeRef b(new DAGNode("b")); + + add_parent(b, a); + add_parent(b, a); + + swap_node(a, a2); + + ASSERT_EQ(2, b->num_parents()); + EXPECT_EQ(a2, b->get_parents()[0]); + EXPECT_EQ(a2, b->get_parents()[1]); + EXPECT_EQ(1, a2->num_children()); + EXPECT_EQ(0, a->num_children()); +} + +TEST(DAG, swapNodeNewIsAlreadyParent) +{ + NodeRef a(new DAGNode("a")); + NodeRef a2(new DAGNode("a2")); + NodeRef b(new DAGNode("b")); + + add_parent(b, a); + add_parent(b, a2); + + swap_node(a, a2); + + // the child list is unique + EXPECT_EQ(1, a2->num_children()); + EXPECT_EQ(2, b->num_parents()); + EXPECT_EQ(0, a->num_children()); +} + +TEST(DAG, swapNodeCycle) +{ + NodeRef a(new DAGNode("a")); + NodeRef b(new DAGNode("b")); + NodeRef c(new DAGNode("c")); + NodeRef a2(new DAGNode("a2")); + + add_parent(b, a); + add_parent(c, b); + add_parent(a2, c); // a2 is downstream of a + + EXPECT_THROW(swap_node(a, a2), std::runtime_error); + EXPECT_THROW(swap_node(a, b), std::runtime_error); + + // nothing has changed + EXPECT_EQ(1, a->num_children()); + EXPECT_EQ(a, b->get_parents()[0]); + EXPECT_EQ(0, a2->num_children()); + EXPECT_EQ(1, a2->num_parents()); +} + +TEST(DAG, swapNodeInvalidArguments) +{ + NodeRef a(new DAGNode("a")); + NodeRef b(new DAGNode("b")); + add_parent(b, a); + + EXPECT_THROW(swap_node(nullptr, a), std::invalid_argument); + EXPECT_THROW(swap_node(a, nullptr), std::invalid_argument); + + // swapping a node with itself is a no-op + swap_node(a, a); + EXPECT_EQ(1, a->num_children()); + EXPECT_EQ(a, b->get_parents()[0]); +} + +TEST(DAG, swapNodeIgnoresDeadChildren) +{ + NodeRef a(new DAGNode("a")); + NodeRef a2(new DAGNode("a2")); + NodeRef alive(new DAGNode("alive")); + { + NodeRef dead(new DAGNode("dead")); + add_parent(dead, a); + add_parent(alive, a); + } + + swap_node(a, a2); + + EXPECT_EQ(0, a->num_children()); + EXPECT_EQ(1, a2->num_children()); + EXPECT_EQ(a2, alive->get_parents()[0]); +} diff --git a/tests/eval.cpp b/tests/eval.cpp index 648bcaa..1be2e1c 100644 --- a/tests/eval.cpp +++ b/tests/eval.cpp @@ -114,4 +114,157 @@ TEST(Eval, member_access) { auto o = parametric::eval(&Foo::bar, i); static_assert(std::is_same_v>); EXPECT_EQ(o, 42.); -} \ No newline at end of file +} + +// Replacing a parameter. See https://github.com/grunk-dev/parametric/issues/22 +TEST(Eval, swapParam) +{ + auto a = parametric::new_param(3.0); + auto b = parametric::new_param(7.0); + auto a2 = parametric::new_param(100.0); + + auto c = parametric::eval(add, a, b); + auto d = parametric::eval(add, a, c); // a has two consumers + EXPECT_NEAR(10.0, c, 1e-12); + EXPECT_NEAR(13.0, d, 1e-12); + + parametric::swap_param(a, a2); + + // results are recomputed using the new parameter + EXPECT_NEAR(107.0, c, 1e-12); + EXPECT_NEAR(207.0, d, 1e-12); + + // the new parameter drives the results ... + a2 = 1.0; + EXPECT_NEAR(8.0, c, 1e-12); + EXPECT_NEAR(9.0, d, 1e-12); + + // ... the old one does not anymore + a = 1000.0; + EXPECT_NEAR(8.0, c, 1e-12); + EXPECT_NEAR(9.0, d, 1e-12); + EXPECT_NEAR(1000.0, a, 1e-12); +} + +TEST(Eval, swapParamInvalidatesResult) +{ + auto a = parametric::new_param(1.0); + auto b = parametric::new_param(2.0); + auto a2 = parametric::new_param(10.0); + + auto c = parametric::eval(add, a, b); + EXPECT_NEAR(3.0, c, 1e-12); + EXPECT_TRUE(c.is_valid()); + + parametric::swap_param(a, a2); + EXPECT_FALSE(c.is_valid()); + EXPECT_NEAR(12.0, c, 1e-12); +} + +TEST(Eval, swapParamDuplicateArgument) +{ + auto a = parametric::new_param(3.0); + auto a2 = parametric::new_param(5.0); + + auto c = parametric::eval(add, a, a); // c = a + a + EXPECT_NEAR(6.0, c, 1e-12); + + parametric::swap_param(a, a2); + EXPECT_NEAR(10.0, c, 1e-12); +} + +TEST(Eval, swapParamOldParamDestroyed) +{ + auto a2 = parametric::new_param(5.0); + auto b = parametric::new_param(1.0); + auto c = [&]() { + auto a = parametric::new_param(3.0); + auto c = parametric::eval(add, a, b); + parametric::swap_param(a, a2); + return c; + }(); + + EXPECT_NEAR(6.0, c, 1e-12); + a2 = 6.0; + EXPECT_NEAR(7.0, c, 1e-12); +} + +TEST(Eval, swapParamCycle) +{ + auto a = parametric::new_param(1.0); + auto b = parametric::new_param(2.0); + auto c = parametric::eval(add, a, b); + + // c depends on a, so it cannot replace a + EXPECT_THROW(parametric::swap_param(a, c), std::runtime_error); + + // the graph still works + a = 5.0; + EXPECT_NEAR(7.0, c, 1e-12); +} + +TEST(Eval, swapParamResultOfComputation) +{ + auto a = parametric::new_param(1.0); + auto b = parametric::new_param(2.0); + auto s = parametric::eval(add, a, b); // 3 + auto t = parametric::new_param(10.0); + auto u = parametric::eval(add, s, t); // 13 + + // replace a computed parameter by an independent one + auto s2 = parametric::new_param(100.0); + parametric::swap_param(s, s2); + EXPECT_NEAR(110.0, u, 1e-12); + + // s is still a valid, working parameter + a = 4.0; + EXPECT_NEAR(6.0, s, 1e-12); + EXPECT_NEAR(110.0, u, 1e-12); +} + +namespace { +class SumDiff : public parametric::ComputeNode< + SumDiff, + parametric::Results, + parametric::Arguments> +{ +public: + void eval() const override { + if (auto s = res<0>(); s) { + s->set_value(arg<0>().value() + arg<1>().value()); + } + if (auto d = res<1>(); d) { + d->set_value(arg<0>().value() - arg<1>().value()); + } + } +}; +} + +TEST(Eval, swapParamMultipleOutputs) +{ + auto a = parametric::new_param(5.0); + auto b = parametric::new_param(3.0); + auto a2 = parametric::new_param(10.0); + + auto [sum, diff] = parametric::compute(a, b); + EXPECT_NEAR(8.0, sum, 1e-12); + EXPECT_NEAR(2.0, diff, 1e-12); + + parametric::swap_param(a, a2); + EXPECT_NEAR(13.0, sum, 1e-12); + EXPECT_NEAR(7.0, diff, 1e-12); +} + +TEST(Eval, swapParamClone) +{ + auto a = parametric::new_param(1.0); + auto b = parametric::new_param(2.0); + auto a2 = parametric::new_param(10.0); + auto c = parametric::eval(add, a, b); + + parametric::swap_param(a, a2); + + auto c_clone = c.clone(); + EXPECT_NEAR(12.0, c_clone, 1e-12); + EXPECT_NEAR(12.0, c, 1e-12); +}