Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
21 changes: 21 additions & 0 deletions docs/usage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
----------------------------

Expand Down
28 changes: 28 additions & 0 deletions parametric/core.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,34 @@ void add_parent(const std::shared_ptr<parametric::impl::param_holder<C1>>&, cons
static_assert(AlwaysFalse<C1>::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 <typename T, typename S>
void swap_param(param<T, S> const& old_p, param<T, S> 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 <typename S=DefaultSerializer>
Expand Down
75 changes: 75 additions & 0 deletions parametric/dag.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,23 @@ typedef std::shared_ptr<parametric::DAGNode> 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)
*
Expand Down Expand Up @@ -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<NodeRef> 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
Expand Down Expand Up @@ -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<std::weak_ptr<DAGNode>> childs; /**< @brief Pointer to child nodes */
std::vector<std::shared_ptr<DAGNode>> parents; /**< @brief Pointer to parent nodes */

Expand Down
127 changes: 127 additions & 0 deletions tests/dag.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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]);
}
Loading
Loading