Skip to content

Commit

Permalink
Adds GetSubsystemByName to Diagram
Browse files Browse the repository at this point in the history
Give a programmatic means for retrieving a subsystem without having to store every pointer to every added system.
  • Loading branch information
RussTedrake committed Oct 14, 2018
1 parent de81cd2 commit 9d32b64
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
14 changes: 14 additions & 0 deletions systems/framework/diagram.h
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,20 @@ class Diagram : public System<T>, internal::SystemParentServiceInterface {
}
}

/// Retrieves a reference to the subsystem with name @p name returned by
/// get_name().
/// @throws std::logic_error if a match cannot be found.
/// @see System<T>::get_name()
const System<T>& GetSubsystemByName(const std::string& name) const {
for (const auto& child : registered_systems_) {
if (child->get_name() == name) {
return *child;
}
}
throw std::logic_error("System " + this->GetSystemName() +
" does not have a subsystem named " + name);
}

/// Retrieves the state derivatives for a particular subsystem from the
/// derivatives for the entire diagram. Aborts if @p subsystem is not
/// actually a subsystem of this diagram. Returns a 0-length ContinuousState
Expand Down
11 changes: 11 additions & 0 deletions systems/framework/test/diagram_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -812,6 +812,17 @@ TEST_F(DiagramTest, AllocateInputs) {
}
}

TEST_F(DiagramTest, GetSubsystemByName) {
const System<double>& stateless = diagram_->GetSubsystemByName("stateless");
EXPECT_NE(
dynamic_cast<const analysis_test::StatelessSystem<double>*>(&stateless),
nullptr);

DRAKE_EXPECT_THROWS_MESSAGE(
diagram_->GetSubsystemByName("not_a_subsystem"), std::logic_error,
"System .* does not have a subsystem named not_a_subsystem");
}

// Tests that ContextBase methods for affecting cache behavior propagate
// through to subcontexts. Since leaf output ports have cache entries in their
// corresponding subcontext, we'll pick one and check its behavior.
Expand Down

0 comments on commit 9d32b64

Please sign in to comment.